かんたんな説明
山の地形を扱う教科書の1章を、番号付きの図7点とともに2段で組みます。本文が初めて図にふれたあとの最初の空いた場所へ、各図が移っていくしくみを示します。
できあがり
200 × 250 mmのページに組む地形学の教科書『Mountain Landforms』の第2章です。章扉では、章番号を入れた青いリボンが天から垂れ下がり、その横に表題の氷青色の板が置かれます。続いてFaustinaの両端そろえの2段が流れます。拡散モデルで生成した画像にコードでラベルを付けた7点の図には、初出順に番号が振られます。6点は、最初に引用した段落から数えて、配置の指定が許す最初の空いた場所へフロートします。autoの図2.1は章扉の下部に、図2.3は28ページの右段の先頭に、図2.2は同じページの下部に収まります。図2.4と図2.5は29ページの2つの段の先頭に入ります。図2.6は本文が埋め込んだ位置に組まれます。図2.7は30ページで引用されるtopのフロートなので31ページを待つはずですが、フロートは章の外に出られないため、30ページの下部に入ります。
このレシピが答える質問
- 番号付きキャプションのある図を加え、本文で参照するには(「図3.2を参照」)?
- 図の位置を制御するには(ページの上端、2段をまたぐ、まさにこの位置、余白)?
- 「図」や「表」のラベルを文書の言語で表示するには?
- 画像や表を、Markdownの![]()ではなくコードから(リソースとして)追加するには?
手短な答え
// In the Markdown, :ref{id="valleys" case="lower"} prints 'fig. 2.1' and places Figure 2.1.
// Captions, credits and alt texts come from content.figures.<lang>.md.
const figure = (id, height, placement) => {
if (!TEXTS[id]) throw new Error(`content.figures has no caption block for "${id}"`);
const [caption, note, altText] = TEXTS[id];
// An SVG fills the width of its slot (a column or the text block, or a fraction of
// either), so its width and height only give its shape.
const width = (placement.span === 'page' ? MEASURE : COLUMN) * (placement.width ?? 1);
return { id, typeId: 'figure', kind: 'svg', caption, note, altText,
svg: { fileId: `${id}.svg`, width, height }, placement, createdAt: 0, updatedAt: 0 };
};
// In any order: the first mention of each one in the text, a :ref or a ::resource line,
// decides its number.
const resources = [
// Cited on the opener page: 'auto' may take that page's foot band, where 'top'
// could only open the next page (gotcha: top-float-next-page).
figure('valleys', 56, { position: 'auto', span: 'page' }),
// Across both columns, but only in a foot band: the page it is cited on, if both
// columns still have room there, else the foot of the next page.
figure('profile', 60, { position: 'bottom', span: 'page' }),
// A column figure that takes only a column head: the next one still empty after its
// citation, here the right column of the same page, above the text that follows it.
figure('cirque', 48, { position: 'top' }),
// Cited in the same sentence, the two take the next two column heads, side by side.
figure('abrasion', 48, { position: 'top' }),
figure('plucking', 48, { position: 'top' }),
// No float: set exactly where ::resource{id="roche"} stands, with the same gap above it
// and below it.
figure('roche', 42, { position: 'here' }),
// A band of its own, half the text width and centred. It is cited on the chapter's last
// page, where a 'top' float would wait for the next page; a float cannot leave its
// chapter, so this one goes to the foot of the last page.
figure('moraines', 50, { position: 'top', span: 'page', width: 0.5, align: 'center' }),
];
材料
- 機能
- 図を配置する参照図の配置番号付きキャプションその場に置く図フロートの障壁「図」と「表」を文書の言語でキャプションのスタイル出典とクレジットリソースとしての図と表独自のリソースの種類デザインした章扉段抜きの章見出し帯見出しの属性番号付き見出しハイフネーションと文書の言語柱とノンブルページの役割ごとの柱セマンティックカラーパレット段末そろえ
- 併用する機能
- 段落スタイル
- 種類
- Faustina, Montserrat, IBM Plex Sans Condensed (SIL OFL 1.1)
- 素材
abrasion-1080.jpgcirque-1080.jpgmoraines-1080.jpgplucking-1080.jpgprofile-1400.jpgroche-1080.jpgvalleys-1536.jpg- Figure 2.1: a V-shaped river valley and a U-shaped glacial valley (Generated With Diffusion Models, オリジナル)
- Figure 2.2: long profile of a valley glacier (Generated With Diffusion Models, オリジナル)
- Figure 2.3: a glacial cirque in section (Generated With Diffusion Models, オリジナル)
- Figure 2.4: abrasion at the base of the ice (Generated With Diffusion Models, オリジナル)
- Figure 2.5: plucking on a rock step (Generated With Diffusion Models, オリジナル)
- Figure 2.6: a roche moutonnée (Generated With Diffusion Models, オリジナル)
- Figure 2.7: lateral, medial and terminal moraines in plan (Generated With Diffusion Models, オリジナル)
作り方
#1 · ページと図にひとつのパレット
const palette = {
ink: '#1b2227', // text: a cold near-black
glacier: '#34729a', // the accent: kicker, ribbon, caption labels, references, folios, water
ice: '#e3f1f8', // the opener slab
rock: '#5b5a57', // bedrock in the drawings
moss: '#7d8f4e', // valley floors and pines
rule: '#c6d3db', // the hairline under the running heads
muted: '#5d6a72', // running heads, credit notes, the colophon
paper: '#ffffff',
};
// A linked colour carries its hex and the palette entry it follows.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
// The engine's defaults link to 'main-color' (#295aa3): pointing it at the accent keeps
// that second blue off the page.
{ id: 'main-color', name: 'glacier (defaults)', value: { hex: palette.glacier, model: 'hex' } },
];
設定のどの色もこのパレットのいずれかの項目にリンクしています。画像も同じスレート、氷河の青、苔の色で生成したので、図はページの色になじみます。画像は自分の色を保ちます。glacierの値を変えると、リボン、板、ラベルの色は変わりますが、図の中の氷の色は変わりません。アクセントの色は小さな文字にも使える暗さです。キャプションのラベルと引用では白に対して5.2:1、キッカーでは氷青色の板に対して4.5:1です。各図は、画像をJPEGのデータURLとして埋め込み、その上に細い白の縁取り付きの文字でラベルを重ねたSVGです。こうするとラベルはくっきりと保たれ、版の言語に従います。ラベルはSVGの上でIBM Plex Sans Condensedを指定し、キットのloadSvgがエンジンのinlineSvgFontsを通して、使われている2つのウェイトを埋め込みます。画像として表示されるSVGは、それだけではページのフォントに届かないからです。
#2 · 図の名前を読み手の言語で
const captions = () => ({
// The built-in types take their names from the locale: 'Figure 2.3' and 'fig. 2.3' with
// 'en-us', 'Figura 2.3' with 'es', numbered {h1}.{n} per chapter. It sets hyphenation too.
locale: t({ en: 'en-us', es: 'es' }),
captionStyle: { // the text colour follows bodyText; the note is 0.85 × the caption size
fontFamily: LABEL, fontSize: pt(8.3), gap: mm(2.2),
labelColor: col('glacier'), descriptionItalic: true, // the label is bold by default
note: { color: col('muted'), gap: mm(0.6) }, // the credit line
},
});
localeが、組み込みの種類に文書の言語で名前を付けます。キャプションは、英語版ではFigure 2.3、スペイン語版ではFigura 2.3となります。同じ'es'がスペイン語のハイフネーションのパターンも選びます。各引用は、その文に必要な形をとります。case="lower"で(fig. 2.1)、さらにstyle="full"を加えて(figure 2.2)、複数形のあとではstyle="number"(「figures 2.4 and 2.5」)、そしてtext="…"で、番号を印字しない「the chapter’s first figure」のような語句になります。この語句は、すでに配置された図を指し戻すためのものです。初出として使うと、やはり図に番号が振られ、配置されます。
#3 · 章扉のリボンと氷の板
const at = (to, edge, x, y, width, height) => ({ anchor: { to, edge },
offset: { x: mm(x), y: mm(y) },
...(width && { size: { width: mm(width), height: height ? mm(height) : 'auto' } }) });
const text = (id, content, family, size, color, placement, extra) => ({ kind: 'text', id,
content, fontFamily: family, fontSize: pt(size), color: col(color), placement,
align: 'left', ...extra });
const caps = (size) => ({ fontWeight: 600, textTransform: 'uppercase',
letterSpacing: pt(size * 0.18) }); // capitals tracked 0.18 em
const [SLAB, RIBBON, RIBBON_END] = [64, 30, 70]; // mm: slab height; ribbon width and length
const [TEXT_X, KICKER_Y] = [RIBBON + 8, 10]; // mm: the opener texts start 8 mm right of the ribbon
const [TITLE_W, LEAD_W] = [118, 112]; // mm: the title's measure, and a shorter standfirst
const opener = {
enabled: true,
// At least 5 mm under the slab; the reserve then rounds up to whole 13.4 pt grid lines,
// so here 69 mm becomes 15 lines (70.9 mm) and the text starts about 7 mm under the slab.
minHeight: mm(SLAB + 5),
slot: { elements: [
{ kind: 'box', id: 'slab', style: { backgroundColor: col('ice') }, // runs off the fore-edge
placement: at('container', 'top-left', 0, 0, MEASURE + OUTER, SLAB) },
{ kind: 'box', id: 'ribbon', style: { backgroundColor: col('glacier') }, // hangs from the head
placement: at('page', 'top-left', INNER, 0, RIBBON, RIBBON_END) },
text('numeral', '{chapterNumber}', DISPLAY, 80, 'paper', // an 80 pt line box is 28 mm tall:
at('page', 'top-left', INNER, RIBBON_END - 31, RIBBON), // it ends 3 mm above the foot
{ fontWeight: 800, lineHeight: 1, align: 'center' }),
text('kicker', t({ en: 'Chapter {chapterNumber} · {attr.topic}',
es: 'Capítulo {chapterNumber} · {attr.topic}' }), LABEL, 8.5, 'glacier',
at('container', 'top-left', TEXT_X, KICKER_Y), caps(8.5)),
text('title', '{titleText}', DISPLAY, 27, 'ink', at('#kicker', 'below', 0, 2.6, TITLE_W),
{ fontWeight: 800, lineHeight: 1.06 }),
text('lead', '{attr.lead}', TEXT, 10.6, 'ink', at('#title', 'below', 0, 4.2, LEAD_W),
{ italic: true, lineHeight: 1.38, hyphenate: true }),
] },
};
const HAIRLINE = TOP - 5; // mm from the top edge: the rule under the running heads
const HEAD_Y = HAIRLINE - 4.4; // the running heads' line box, 4.4 mm above the hairline
const head = (id, content, parity, edge, x, extra) => text(id, content, LABEL, 7.6, 'muted',
at('page', edge, x, HEAD_Y), { ...caps(7.6), parity, pages: 'body', ...extra });
const folio = (id, parity, edge, x, extra) => text(id, '{pageNumber}', DISPLAY, 8.5, 'glacier',
at('page', edge, x, HEAD_Y), { fontWeight: 800, parity, pages: 'body', ...extra });
const header = { elements: [ // outer corners, over a hairline; never on the opener
folio('verso-folio', 'even', 'top-left', OUTER),
head('verso-title', '{title}', 'even', 'top-left', OUTER + 8),
head('recto-title', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 8), { align: 'right' }),
folio('recto-folio', 'odd', 'top-right', -OUTER, { align: 'right' }),
{ kind: 'rule', id: 'hairline', pages: 'body', direction: 'horizontal', color: col('rule'),
thickness: pt(0.5), placement: { ...at('container', 'top-left', 0, HAIRLINE),
size: { width: 'fill', height: 'auto' } } },
] };
const footer = { elements: [ // the drop folio: on the opener only, centred 9 mm under the text
text('drop-folio', '{pageNumber}', DISPLAY, 8.5, 'glacier', at('container', 'top', 0, 9),
{ fontWeight: 800, align: 'center', pages: 'opener' })] };
章扉は2つのボックスと4つの文字でできています。天から垂れ下がり下端に章番号を入れたリボン、小口の外へはみ出す氷の板、見出しのtopic属性から取るキッカー、その下に連ねた表題とリード文です。minHeightは板と、その下の少なくとも5 mmを確保し、グリッドの行単位に切り上げます(ここでは約7 mm)。こうして図2.1も同じページの下部の帯に収まります。柱は小口側の隅に、ruleの色の細罫の上に置かれ、pages: 'body'で章扉には付けません。章扉には代わりにページの下にノンブルを入れます。
#4 · 未知のidと引用されない図で止める
// The build lists every :ref and ::resource to an id no resource has in doc.contentWarnings
// (kind 'unknownResourceId'); each prints '?' on the page. A figure nobody names is never
// placed and raises no warning, so the pen reads the mentions with the engine's own parser;
// an embed needs double quotes (gotcha: resource-double-quotes).
function checkFigures(doc) {
const [named, embedded] = [new Set(), new Set()];
for (const block of parseMarkdown(markdown)) {
if (block.type === 'resourceBlock' && block.resourceId) {
named.add(block.resourceId);
embedded.add(block.resourceId);
}
for (const span of block.spans) if (span.ref?.resourceId) named.add(span.ref.resourceId);
}
const unknown = (doc.contentWarnings ?? []).filter((w) => w.kind === 'unknownResourceId');
const problems = [
...new Set(unknown.map((w) => `unknown id "${w.resourceId}"`)),
...resources.filter((r) => !named.has(r.id)).map((r) => `"${r.id}" is never cited`),
...resources.filter((r) => r.placement.position === 'here' && !embedded.has(r.id))
.map((r) => `"${r.id}" is placed 'here' but no ::resource line embeds it`),
];
if (problems.length) throw new Error(`Figures: ${problems.join('; ')}`);
}
どのリソースにもないidを指す:refや::resourceは「?」と印字され、何も配置されません。ビルドはその1件ずつを、idとソース上の位置とともにunknownResourceIdとしてdoc.contentWarningsに記録します。だれも言及しない図は配置されず、警告も出ません。そこでこの検査は、エンジン自身のパーサーであるparseMarkdownでMarkdownを読み、言及と図を突き合わせます。未知のid、引用されない図、::resourceの行がないhereの図を、ページを表示する前に1つのエラーにまとめます。
#5 · 本の現在位置から数え始める
for (const { id, svg: { fileId, width, height } } of resources) { // each under its svg.fileId
const art = await dataUrl(PAINTINGS[id]);
await loadSvg(fileId, svg(width, height, `<image href="${art}" width="${n2(width)}" `
+ `height="${n2(height)}" preserveAspectRatio="none"/>${DRAWINGS[id](width, height)}`));
}
// One chapter came before: figures number 2.1, 2.2… and the folios start at 27.
const continuation = { pageNumbering: { startAt: 27 }, // odd, to match the recto of page 1
headings: { h1: 1, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0 } }; // the next # is chapter 2
const doc = await buildDocumentWithFonts({ markdown, resources, continuation }, config(),
{ ...kitFonts(FONTS), text: words });
checkFigures(doc); // a wrong id stops here, and the viewer's bar says why
showPages(doc, { title: t({ en: 'Figures that float to where you cite them',
es: 'Figuras que flotan hasta donde las citas' }) });
これは長い本の第2章なので、continuationには前に1章あることを記録します。{h1}.{n}で番号を振る図は2.1から、ノンブルは27から始まります。28ページでは図2.3が図2.2の上に立ちます。図2.2の番号が小さいのは、本文がそちらを先に引用しているからです。Markdownの![]()は取り除かれるので、図はすべてリソースで、そのSVGはビルドの前にsvg.fileIdの名前で登録します。各図の配置は引用される位置から決めます。図2.1は板が章扉の上部を埋めるのでauto、縦断面図は引用したページの下部にまだ入れるのでbottom、段の図は次に空いている段の先頭を占めるのでtopです。図2.7もtopですが、フロートは章の中にとどまるので、30ページの下部に収まります。
レシピの全体
// ═══ Postext Cookbook · Nº 009 · Figures that float to where you cite them ═════════
// https://postext.dev/en/cookbook/figures-float-where-cited
// Code: MIT · Text: original (CC BY 4.0) · Figures: diffusion models, labels in code
// Fonts: Faustina, Montserrat, IBM Plex Sans Condensed (SIL OFL 1.1) · Needs postext ≥ 1.25.0
//
// Chapter 2 of a geomorphology textbook. Six of its seven figures float, each to the first
// free slot its placement allows, counting from the paragraph that first cites it. Figure 2.6
// is set where ::resource embeds it. The figures are numbered in order of first mention.
import {
buildDocumentWithFonts, prepareFonts, renderPageToCanvas, registerResourceImage,
inlineSvgFonts, parseMarkdown,
} from 'https://esm.sh/postext';
const LANG = 'es'; // @lang: the language of the sample document ('es' | 'en')
const RECIPE = 'figures-float-where-cited';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: eight named colours; the paintings were made to match them
const palette = {
ink: '#1b2227', // text: a cold near-black
glacier: '#34729a', // the accent: kicker, ribbon, caption labels, references, folios, water
ice: '#e3f1f8', // the opener slab
rock: '#5b5a57', // bedrock in the drawings
moss: '#7d8f4e', // valley floors and pines
rule: '#c6d3db', // the hairline under the running heads
muted: '#5d6a72', // running heads, credit notes, the colophon
paper: '#ffffff',
};
// A linked colour carries its hex and the palette entry it follows.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
// The engine's defaults link to 'main-color' (#295aa3): pointing it at the accent keeps
// that second blue off the page.
{ id: 'main-color', name: 'glacier (defaults)', value: { hex: palette.glacier, model: 'hex' } },
];
// #endregion
const TEXT = 'Faustina'; // one family each for text, display and labels
const DISPLAY = 'Montserrat';
const LABEL = 'IBM Plex Sans Condensed';
const LEAD = 13.4; // body leading in pt: the grid every float band snaps to
const [PAGE_W, PAGE_H, TOP, BOTTOM, INNER, OUTER, GUTTER] = [200, 250, 22, 20, 18, 14, 6]; // mm
const MEASURE = PAGE_W - INNER - OUTER; // 168 mm: the text block, and a page-wide figure
const COLUMN = (MEASURE - GUTTER) / 2; // 81 mm: a column, and a column figure
// #region captions: the type name in the document's language; bold label, italic description
const captions = () => ({
// The built-in types take their names from the locale: 'Figure 2.3' and 'fig. 2.3' with
組み立てたscript.jsはそのまま動きます。任意のページのモジュールスクリプトに貼り付けるか、レシピをCodePenで開いてください。 GitHub上のレシピのフォルダー ↗ (新しいタブで開きます)
アレンジ
#章番号を付けずに図番号を振る
番号から章を外すと、図は1〜7と印字されます。本全体で1つの通し番号にするには、章をbuildBundleで組むか、各章に前の章のcontinuationAfter()を渡します。
- inlineSvgFonts, parseMarkdown,
+ inlineSvgFonts, parseMarkdown, defaultResourceTypes,
@@
locale: t({ en: 'en-us', es: 'es' }),
+ resourceTypes: defaultResourceTypes(LANG).map((type) => ({ ...type,
+ numberingTemplate: '{n}', resetOn: 'never' })),#キャプションを上に、帯に載せて
キャプションは図の上に移り、パレットの氷青色の帯に載ります。クレジットの行は図の下に残ります。こうするとどちらの版も5ページ目にはみ出すので、本文の分量を調整し直してください。
captionStyle: { // the text colour follows bodyText; the note is 0.85 × the caption size
+ position: 'above', backgroundEnabled: true, background: col('ice'),
fontFamily: LABEL, fontSize: pt(8.3), gap: mm(2.2),#図を余白に置く
段と半段のページなら、本文が入らない小口側の溝を図とキャプションに与えられます。余白に段を設けた教科書を参照してください。
#表も同じようにフロートさせる
表もリソースで、同じ規則で引用され配置されます。長い表はページをまたいで分割されます。技術データシートを参照してください。
よくあるつまずき
つまずき
'top'のフロートは参照ページの先頭を許さない限り次のページに置かれる
既定では、フロートが自分の参照より上に置かれることはありません。そのため、Nページで参照したページ幅の'top'フロートはN+1ページの頭に置かれます。リソースまたはその種類のdefaultPlacementにplacement.citingPage: trueを設定すると(本全体ならlayout.floatsAtCitingPage、postext 1.25から)、layout.maxTopFraction以内に収まり参照行がそのページに残る場合は代わりにNページの先頭に置かれ、参照より前の本文はその下に送られます。章の最初のページと強制改ページの後のページの先頭には置かれません。その場合は次のページに置かれ、'auto'または'bottom'なら参照したページの下端に入れられます。 図の配置 →
つまずき
::resource{id="…"}は二重引用符でしか書けない
ブロックの埋め込みとして認識されるのは、二重引用符を使った::resource{id="…"}の形だけです。ほかの書き方は、目に見える1行として本文に残ります。 その場に置く図 →
つまずき
SVGの図に<marker>やフィルターを使わない(ラスターにフォールバックする)
SVGの図がPDFでベクターのまま残るのは、<marker>、フィルター、マスクを使っていない場合だけです。使っているとラスターにフォールバックし、深く入れ子にしたフィルターはChromeで図を真っ白にすることがあります。矢じりはパスで描いてください。 リソースとしての図と表 →
Sandboxの検査 · unknownResourceId
不明なリソース
原因. :refまたは::resourceが、どのリソースにもないidを指定しています。参照は「?」と印字され、何も配置されません。
対処. idを修正する(二重引用符のみ使えます)か、リソースを追加してください。 ドキュメント →
クレジット
- 本文
- 書き下ろしの文章, CC BY 4.0
- 画像
- Figure 2.1: a V-shaped river valley and a U-shaped glacial valley · Generated With Diffusion Models · オリジナル
- Figure 2.2: long profile of a valley glacier · Generated With Diffusion Models · オリジナル
- Figure 2.3: a glacial cirque in section · Generated With Diffusion Models · オリジナル
- Figure 2.4: abrasion at the base of the ice · Generated With Diffusion Models · オリジナル
- Figure 2.5: plucking on a rock step · Generated With Diffusion Models · オリジナル
- Figure 2.6: a roche moutonnée · Generated With Diffusion Models · オリジナル
- Figure 2.7: lateral, medial and terminal moraines in plan · Generated With Diffusion Models · オリジナル
- フォント
- Faustina (SIL OFL 1.1) · Montserrat (SIL OFL 1.1) · IBM Plex Sans Condensed (SIL OFL 1.1)


