In breve
Un capitolo di un manuale sulle montagne, su due colonne con sette immagini numerate. Mostra come ogni immagine si sposta nel primo spazio libero dopo che il testo la cita per la prima volta.
Che cosa comporrai
Il capitolo 2 di Mountain Landforms, un manuale di geomorfologia su una pagina di 200 × 250 mm. Un nastro blu con il numero del capitolo pende dalla testa dell’apertura, accanto alla lastra azzurro ghiaccio del titolo; seguono due colonne giustificate in Faustina. Le sette figure, dipinti generati con modelli di diffusione ed etichettati nel codice, sono numerate nell’ordine della prima citazione. Sei, come elementi flottanti, vanno nel primo posto libero che il loro placement consente, a partire dal paragrafo che le cita per primo. La figura 2.1, auto, finisce al piede dell’apertura; la 2.3 apre la colonna destra di pagina 28 e la 2.2 riempie il piede della stessa pagina; la 2.4 e la 2.5 aprono le due colonne di pagina 29. La figura 2.6 sta dove il testo la inserisce. La figura 2.7, un elemento flottante top citato a pagina 30, aspetterebbe pagina 31, ma un elemento flottante non può lasciare il suo capitolo, quindi va al piede di pagina 30.
Questa ricetta risponde a
- Come aggiungo una figura con didascalia numerata e la cito nel testo («vedi Fig. 3.2»)?
- Come decido dove va una figura: in testa alla pagina, su entrambe le colonne, esattamente qui o nel margine?
- Come ottengo le etichette «Figura» e «Tabella» nella lingua del mio documento?
- Come aggiungo immagini e tabelle dal codice (risorse) invece che con ![]() in Markdown?
La risposta breve
// 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' }),
];
Ingredienti
- Funzionalità
- Citazioni che collocano le figureCollocazione delle figureDidascalie numerateFigure proprio quiBarriere per gli elementi flottantiFigura e Tabella nella tua linguaStile delle didascalieRighe di fonte e creditiFigure e tabelle come risorseTipi di risorsa personalizzatiAperture progettateFascia di capitolo a tutta larghezzaAttributi dei titoliTitoli numeratiSillabazione e lingua del documentoTestatine e folioTestatine secondo il ruolo della paginaTavolozza di colori semanticaBilanciamento delle colonne
- Usa anche
- Stili di paragrafo
- Tipo
- Faustina, Montserrat, IBM Plex Sans Condensed (SIL OFL 1.1)
- Risorse
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, originale)
- Figure 2.2: long profile of a valley glacier (Generated With Diffusion Models, originale)
- Figure 2.3: a glacial cirque in section (Generated With Diffusion Models, originale)
- Figure 2.4: abrasion at the base of the ice (Generated With Diffusion Models, originale)
- Figure 2.5: plucking on a rock step (Generated With Diffusion Models, originale)
- Figure 2.6: a roche moutonnée (Generated With Diffusion Models, originale)
- Figure 2.7: lateral, medial and terminal moraines in plan (Generated With Diffusion Models, originale)
Preparazione
#1 · Una sola tavolozza per le pagine e le figure
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' } },
];
Ogni colore della configurazione rimanda a una di queste voci, e i dipinti sono stati generati negli stessi toni di ardesia, blu ghiacciaio e muschio, così le figure stanno nei colori della pagina. Un dipinto conserva i suoi colori: un nuovo valore di glacier cambia il nastro, la lastra e le etichette, non il ghiaccio nelle figure. L’accento è abbastanza scuro per il testo piccolo: 5,2:1 sul bianco per le etichette delle didascalie e le citazioni, 4,5:1 sulla lastra di ghiaccio per l’occhiello. Ogni figura è un SVG che contiene il suo dipinto come data URL JPEG e vi sovrappone le etichette come testo, con un sottile alone bianco, così restano nitide e seguono la lingua dell’edizione. Le etichette indicano IBM Plex Sans Condensed nell’SVG, e il loadSvg del kit incorpora i due pesi che usano tramite inlineSvgFonts del motore, perché un SVG mostrato come immagine non può raggiungere da solo i font della pagina.
#2 · Dai un nome alle figure nella lingua del lettore
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 dà il nome ai tipi predefiniti nella lingua del documento: qui le didascalie riportano Figure 2.3 e nell’edizione spagnola Figura 2.3, dove lo stesso 'es' sceglie anche i modelli di sillabazione spagnoli. Ogni citazione prende poi la forma che la sua frase richiede: case="lower" per (fig. 2.1) e, con style="full", per (figure 2.2); style="number" dopo un plurale (figures 2.4 and 2.5); e text="…" per una locuzione come the chapter’s first figure, che non stampa alcun numero. Quella locuzione rimanda a una figura già collocata; come prima citazione la numererebbe e la collocherebbe comunque.
#3 · Un nastro e una lastra di ghiaccio per l’apertura
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' })] };
L’apertura è fatta di due riquadri e quattro testi: un nastro che pende dalla testa con il numero del capitolo al piede, una lastra di ghiaccio che esce dal margine esterno, l’occhiello preso dall’attributo topic del titolo, e il titolo e il sommario concatenati sotto. minHeight riserva la lastra e almeno 5 mm sotto di essa, arrotondati per eccesso a righe intere della griglia (qui circa 7 mm), così la figura 2.1 entra ancora nella fascia di piede della stessa pagina. Le testatine stanno agli angoli esterni sopra un filetto sottile del colore rule, e pages: 'body' le tiene lontane dall’apertura, che riceve invece un numero di pagina a piè di pagina.
#4 · Fermati su un id sconosciuto o su una figura non citata
// 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('; ')}`);
}
Un :ref o un ::resource verso un id che nessuna risorsa ha stampa «?» e non colloca nulla; la build registra ciascuno in doc.contentWarnings come unknownResourceId, con l’id e la sua posizione nel sorgente. Una figura che nessuno cita non viene mai collocata e non genera avvisi, quindi il controllo legge il Markdown con parseMarkdown, il parser del motore stesso, e confronta le citazioni con le figure. Un id sconosciuto, una figura non citata o una figura here senza riga ::resource diventano un errore prima che le pagine vengano mostrate.
#5 · Comincia il conteggio dal punto del libro in cui ti trovi
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' }) });
Questo è il capitolo 2 di un libro più lungo, quindi continuation registra un capitolo prima di esso: le figure numerate {h1}.{n} partono da 2.1 e i numeri di pagina da 27. A pagina 28 la figura 2.3 sta sopra la figura 2.2, che ha il numero più basso perché il testo la cita per prima. Il ![]() del Markdown viene eliminato, quindi ogni figura è una risorsa il cui SVG è registrato sotto il suo svg.fileId prima della build. Ogni placement dipende da dove la figura è citata: auto per la 2.1, perché la lastra riempie la testa dell’apertura; bottom per il profilo, che può ancora prendere il piede della pagina che lo cita; top per le figure di colonna, che aprono le successive teste di colonna libere; e top anche per la 2.7, che finisce al piede di pagina 30 perché un elemento flottante resta nel suo capitolo.
La ricetta completa
// ═══ 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 = 'en'; // @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
Lo script.js composto funziona così com’è: incollalo nello script modulo di qualsiasi pagina, oppure apri la ricetta su CodePen. Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)
Varianti
#Numera le figure senza il capitolo
Togli il capitolo dai numeri e le figure stampano da 1 a 7; per un unico conteggio lungo tutto un libro, impagina i capitoli con buildBundle oppure passa a ogni capitolo il continuationAfter() del precedente.
- inlineSvgFonts, parseMarkdown,
+ inlineSvgFonts, parseMarkdown, defaultResourceTypes,
@@
locale: t({ en: 'en-us', es: 'es' }),
+ resourceTypes: defaultResourceTypes(LANG).map((type) => ({ ...type,
+ numberingTemplate: '{n}', resetOn: 'never' })),#Metti le didascalie sopra, su una barra
La didascalia passa sopra la figura su una barra nell’azzurro ghiaccio della tavolozza e la riga dei crediti resta sotto la figura; riadatta il testo, perché entrambe le edizioni finiscono allora su una quinta pagina.
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),#Metti una figura nel margine
Una pagina a colonna e mezza dà alle figure e alle didascalie un canale esterno in cui il testo non entra mai: vedi il manuale con una colonna a margine.
#Fai flottare le tabelle allo stesso modo
Anche le tabelle sono risorse, citate e collocate con le stesse regole, e una tabella lunga si divide tra le pagine: vedi la scheda tecnica.
Errori frequenti
Errore frequente
Un elemento flottante 'top' va alla pagina dopo la sua citazione, a meno che non possa aprire la pagina che lo cita
Per impostazione predefinita un elemento flottante non va mai sopra il proprio riferimento, quindi un flottante 'top' a tutta larghezza citato a pagina N apre la pagina N+1. Imposta placement.citingPage: true sulla risorsa o sul defaultPlacement del suo tipo (o layout.floatsAtCitingPage per tutto il libro, da postext 1.25) e aprirà invece la pagina N, con il testo sopra il riferimento che scende sotto di esso, quando entra entro layout.maxTopFraction e la riga che lo cita resta su quella pagina. Non apre mai la prima pagina di un capitolo né una pagina dopo un’interruzione forzata: lì apre ancora la pagina successiva, e 'auto' o 'bottom' possono prendere il piede della pagina che lo cita. Collocazione delle figure →
Errore frequente
::resource{id="…"} accetta solo virgolette doppie
Un inserimento a blocco viene riconosciuto solo come ::resource{id="…"} con virgolette doppie; qualsiasi altra forma resta nel testo come riga visibile. Figure proprio qui →
Errore frequente
Niente <marker> né filtri nelle illustrazioni SVG (ripiego raster)
Una figura SVG resta vettoriale nel PDF solo senza <marker>, filtri e maschere; altrimenti ripiega su un raster, e filtri annidati in profondità possono farla sparire in Chrome. Disegna le punte delle frecce come tracciati. Figure e tabelle come risorse →
Verifica della Sandbox · unknownResourceId
Risorsa sconosciuta
Perché. Un :ref o un ::resource indica un id che nessuna risorsa ha; il rimando stampa «?» e non viene collocato nulla.
Soluzione. Correggi l’id (solo virgolette doppie) oppure aggiungi la risorsa. Documentazione →
Crediti
- Ricetta
- Ignacio Ferro
- Testo
- Testo originale, CC BY 4.0
- Immagini
- Figure 2.1: a V-shaped river valley and a U-shaped glacial valley · Generated With Diffusion Models · originale
- Figure 2.2: long profile of a valley glacier · Generated With Diffusion Models · originale
- Figure 2.3: a glacial cirque in section · Generated With Diffusion Models · originale
- Figure 2.4: abrasion at the base of the ice · Generated With Diffusion Models · originale
- Figure 2.5: plucking on a rock step · Generated With Diffusion Models · originale
- Figure 2.6: a roche moutonnée · Generated With Diffusion Models · originale
- Figure 2.7: lateral, medial and terminal moraines in plan · Generated With Diffusion Models · originale
- Font
- Faustina (SIL OFL 1.1) · Montserrat (SIL OFL 1.1) · IBM Plex Sans Condensed (SIL OFL 1.1)
- Codice
- MIT, come Postext
Modifica questo testo ↗ (si apre in una nuova scheda)Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)


