Vai al contenuto principale
Ricetta numero 94

Ricettario · Capitolo 5 · Struttura del libro

Un libro tecnico con rimandi tra capitoli

Un manuale solare di tre capitoli il cui testo scrive :sun, :loads e :array-size, e buildBundle stampa ogni numero e pagina tra i capitoli.

In questa pagina
  • Esempio in inglese: non c’è ancora un’edizione italiana
  • Formato 178 × 233 mm
  • 1 colonna
  • IBM Plex Serif 9,6/13,8
  • IBM Plex Mono
  • IBM Plex Sans Condensed
  • 9 pagine
  • Livello
  • Postext 1.57.1
  • Impaginato in 134 ms
  • 246 righe di codice

In breve

Un breve manuale per dimensionare pannelli solari e batterie per una baita. Quando il capitolo 3 rimanda a una tabella del capitolo 1, o il capitolo 1 anticipa una sezione del capitolo 2, si stampano il numero e la pagina giusti, come link.

Che cosa comporrai

Un breve manuale tecnico, Power for a Cabin, composto in IBM Plex su una pagina di 178 × 233 mm: una copertina con i percorsi del sole disegnati nel codice, una pagina di indice e tre capitoli sotto una fascia blu notte. Il libro dimensiona un piccolo impianto solare, quindi ogni capitolo si appoggia agli altri. Il capitolo 3 cita la tabella dei carichi del capitolo 1 e il grafico delle ore di sole del capitolo 2; il capitolo 1 manda il lettore avanti alla sezione 2.3 e ne dà la pagina. L’autore scrive @tbl:loads e @sec:array-size, come li legge pandoc-crossref, in quattro file Markdown separati. buildBundle li impagina come un unico libro, così ogni rimando stampa il numero che il suo bersaglio ha ricevuto nel proprio capitolo, la pagina su cui è finito e un link.

Questa ricetta risponde a

  • Come rimando a una figura, una tabella o una sezione in un altro capitolo, nello stile di pandoc-crossref, mantenendo corretti i numeri?
  • Come rimando a una sezione e alla pagina in cui si trova, mantenendo corretti entrambi quando il libro cambia?

La risposta breve

script.js · righe 44–61nel codice completo
// buildBundle lays the chapters out in order. Each chapter whose text names a target it
// does not hold (`@sec:array-size` in chapter 1, `@tbl:loads` in chapter 3) is laid out
// with the outline of the whole book, so the reference prints "section 2.3" and its page,
// and links to it. Headings carry their ids in the Markdown, `## Sizing the array
// {#sec:array-size}`; figures and tables are resources whose ids are what follows the @.
const book = () => buildBundle({ chapters, config: config(), resources });
const crossRefs = {
  chapter: t({ en: 'chapter {n}', es: 'capítulo {n}' }), // @sec:array → "chapter 2"
  section: t({ en: 'section {n}', es: 'apartado {n}' }), // @sec:losses → "section 2.2"
  page: t({ en: 'p. {n}', es: 'pág. {n}' }), // :ref{id="sec:losses" style=page} → "p. 7"
};
// Figures and tables count per chapter ({h1}.{n}) and carry on from one document to the
// next. A reference prints the type's shortLabel: @fig:sun → "Fig. 2.1", @Tbl:loads (capital
// T, at the start of a sentence) → "Table 1.1", [-@tbl:loads] → the bare "1.1".
const resourceTypes = defaultResourceTypes(LANG).map((type) => ({ ...type,
  shortLabel: type.id === 'table' ? t({ en: 'table', es: 'tabla' })
    : t({ en: 'fig.', es: 'figura' }),
  ...(type.id === 'table' && { captionStyle: { position: 'above' } }) }));

Ingredienti

Tipo
IBM Plex Serif, IBM Plex Sans Condensed, IBM Plex Mono (SIL OFL 1.1)
Risorse
Nessuna: ogni immagine è disegnata nel codice

Preparazione

#1 · Nomina ogni bersaglio una volta, per tutto il libro

Il codice è nella risposta breve qui sopra. I titoli prendono un identificatore Pandoc con il suo prefisso, ## Sizing the array {#sec:array-size}. Figure e tabelle sono risorse dichiarate nello script, e i loro id si scrivono allo stesso modo, fig:sun e tbl:loads, così il testo scrive @fig:sun che la figura sia due paragrafi più in là o due capitoli prima. Un id deve essere unico in tutto il libro, non solo nel suo capitolo.

#2 · Impagina i capitoli come un unico libro

script.js · righe 44–61nel codice completo
// buildBundle lays the chapters out in order. Each chapter whose text names a target it
// does not hold (`@sec:array-size` in chapter 1, `@tbl:loads` in chapter 3) is laid out
// with the outline of the whole book, so the reference prints "section 2.3" and its page,
// and links to it. Headings carry their ids in the Markdown, `## Sizing the array
// {#sec:array-size}`; figures and tables are resources whose ids are what follows the @.
const book = () => buildBundle({ chapters, config: config(), resources });
const crossRefs = {
  chapter: t({ en: 'chapter {n}', es: 'capítulo {n}' }), // @sec:array → "chapter 2"
  section: t({ en: 'section {n}', es: 'apartado {n}' }), // @sec:losses → "section 2.2"
  page: t({ en: 'p. {n}', es: 'pág. {n}' }), // :ref{id="sec:losses" style=page} → "p. 7"
};
// Figures and tables count per chapter ({h1}.{n}) and carry on from one document to the
// next. A reference prints the type's shortLabel: @fig:sun → "Fig. 2.1", @Tbl:loads (capital
// T, at the start of a sentence) → "Table 1.1", [-@tbl:loads] → the bare "1.1".
const resourceTypes = defaultResourceTypes(LANG).map((type) => ({ ...type,
  shortLabel: type.id === 'table' ? t({ en: 'table', es: 'tabla' })
    : t({ en: 'fig.', es: 'figura' }),
  ...(type.id === 'table' && { captionStyle: { position: 'above' } }) }));

buildBundle fa proseguire i contatori di figure e tabelle da un capitolo all’altro, così la prima tabella del capitolo 3 è la 3.1 e @tbl:loads nel capitolo 3 stampa ancora table 1.1. Un capitolo il cui testo rimanda a un titolo che non contiene viene impaginato con la struttura dell’intero libro, e reimpaginato (al massimo tre giri) finché le pagine di quella struttura non smettono di spostarsi. È così che il capitolo 1 può stampare section 2.1 … p. 6 prima che il capitolo 2 esista sulla carta.

#3 · Scegli le parole che stampa un rimando

crossRefs imposta chapter, section e p. (in spagnolo capítulo, apartado e pág.). Un rimando a una figura o a una tabella stampa lo shortLabel del suo tipo, qui in minuscolo come li compone pandoc-crossref, fig. 2.1 e table 1.1. Una maiuscola nel prefisso, @Tbl:loads o @Sec:array, rende maiuscola l’etichetta all’inizio di una frase, e [-@tbl:losses] stampa il solo numero per tables 2.1 and 3.1.

#4 · Rimanda in avanti alle sezioni, indietro alle figure

Una figura o una tabella riceve il numero, e si colloca come elemento flottante, dove viene citata per la prima volta. @fig:soc nel capitolo 1 ne farebbe la figura 1.2 e la collocherebbe nel capitolo 1. Per questo il capitolo 1 anticipa @sec:autonomy, e figure e tabelle si citano per la prima volta nel loro capitolo; ogni capitolo successivo vi rimanda liberamente. Una pagina va con la sezione, :ref{id="sec:sun-hours" style=page}: un rimando a una risorsa stampa l’etichetta e il numero, mai la pagina.

#5 · Le aperture e la copertina vengono dalla stessa fascia

script.js · righe 65–85nel codice completo
const BAND = 52; // mm from the trim's top
const opener = { enabled: true, minHeight: mm(54), slot: { elements: [
  { kind: 'box', id: 'band', style: { backgroundColor: col('night') },
    placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: mm(BAND + 3) } } },
  { kind: 'text', id: 'kicker', content: t({ en: 'Chapter', es: 'Capítulo' }), ...caps(8.5),
    color: col('sun'), placement: at('container', 'top-left', 0, 2) },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: COND, fontWeight: 600,
    fontSize: pt(30), lineHeight: 1.05, color: col('paper'), align: 'left', overflow: 'wrap',
    placement: { ...at('#kicker', 'below', 0, 3), size: { width: mm(MEASURE - 26) } } },
  { kind: 'text', id: 'number', content: '{chapterNumber}', fontFamily: COND, fontWeight: 600,
    fontSize: pt(84), lineHeight: 1, color: col('sun'), align: 'right',
    placement: { ...at('container', 'top-right', 0, -6), size: { width: mm(40) } } },
  { kind: 'text', id: 'lead', content: '{attr.lead}', fontFamily: SERIF, italic: true,
    fontSize: pt(11), lineHeight: 1.38, color: col('ink'), align: 'left', overflow: 'wrap',
    placement: { ...at('container', 'top-left', 0, BAND - MARGIN.top + 8),
      size: { width: mm(MEASURE - 10) } } },
] } };
// The contents page wears the same band, with the book's subtitle as its kicker.
const contentsOpener = { ...opener, minHeight: mm(BAND - MARGIN.top + 4), slot: { elements:
  opener.slot.elements.filter((e) => ['band', 'kicker', 'title'].includes(e.id))
    .map((e) => (e.id === 'kicker' ? { ...e, content: '{subtitle}' } : e)) } };

La fascia scende per 55 mm dalla testa del rifilo in ogni capitolo e nella pagina dell’indice, che riusano gli stessi elementi; il numero del capitolo è {chapterNumber}, il sommario un attributo del titolo.

script.js · righe 89–109nel codice completo
const COVER_BAND = 168; // mm
const cover = { enabled: true, slot: { elements: [
  { kind: 'box', id: 'band', style: { backgroundColor: col('night') },
    placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: mm(COVER_BAND) } } },
  { kind: 'image', id: 'art', resourceId: 'cover',
    placement: { ...at('bleed', 'top-left'), size: { width: 'fill' } } },
  // Stacked upwards from the subtitle, so a title of one line or two keeps its distance.
  { kind: 'text', id: 'subtitle', content: '{subtitle}', fontFamily: SERIF, italic: true,
    fontSize: pt(14), color: col('tint'), align: 'left',
    placement: at('page', 'top-left', MARGIN.inner, COVER_BAND - 22) },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: COND, fontWeight: 600,
    fontSize: pt(52), lineHeight: 1, color: col('paper'), align: 'left', overflow: 'wrap',
    placement: { ...at('#subtitle', 'above', 0, -4), size: { width: mm(140) } } },
  { kind: 'text', id: 'kicker', content: '{attr.kicker}', ...caps(8.5), color: col('sun'),
    placement: at('#title', 'above', 0, -4) },
  { kind: 'text', id: 'author', content: '{author}', fontFamily: COND, fontWeight: 600,
    fontSize: pt(13), color: col('ink'), align: 'left',
    placement: at('page', 'top-left', MARGIN.inner, COVER_BAND + 14) },
  { kind: 'text', id: 'edition', content: '{attr.edition}', ...caps(7.5), color: col('muted'),
    placement: at('#author', 'below', 0, 2.5) },
] } };

La ricetta completa

Sandbox
// ═══ Postext Cookbook · Nº 094 · A technical book whose references cross chapters ═══
// https://postext.dev/en/cookbook/technical-book-crossref-chapters
// Code: MIT · Text: original (CC BY 4.0) · Charts: generated in code (CC BY 4.0)
// Fonts: IBM Plex Serif, Sans Condensed and Mono (SIL OFL 1.1) · Needs postext ≥ 1.28.0
// A small handbook in four Markdown documents. The text writes @fig:sun, @tbl:loads and
// @sec:array-size the way pandoc-crossref reads them, and buildBundle resolves each one to
// the right number, title or page wherever in the book its target lies.
import {
  buildBundle, prepareFonts, withLoadedFonts, renderPageToCanvas, registerResourceImage,
  defaultResourceTypes, parseTSV, setAlignment, inlineSvgFonts,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'technical-book-crossref-chapters';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: a night-blue band, one burnt-orange accent, an amber for the charts
const palette = {
  ink: '#1c1f24', // text: a cool near-black
  night: '#1f3247', // openers, the cover, table heads
  accent: '#a8471a', // numbers, kickers, references (5.6:1 on paper)
  sun: '#e9a33a', // the charts and the cover only, never text on paper
  tint: '#f5ede3', // daylight in the charts
  rule: '#cfc7bc', // hairlines
  muted: '#5e636a', // running heads, colophon, chart labels
  paper: '#ffffff',
};
// Each colour names its palette entry and carries its hex.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = Object.entries({ ...palette, 'main-color': palette.accent })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
// #endregion
const SERIF = 'IBM Plex Serif', COND = 'IBM Plex Sans Condensed', MONO = 'IBM Plex Mono';
const TRIM = { w: 178, h: 233 }; // mm: a technical-book trim
const MARGIN = { top: 22, bottom: 22, inner: 20, outer: 32 }; // a 126 mm measure
const LEAD = 13.8; // pt: the body leading
const MEASURE = TRIM.w - MARGIN.inner - MARGIN.outer;
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const caps = (size, extra = {}) => ({ fontFamily: MONO, fontSize: pt(size), fontWeight: 600,
  letterSpacing: pt(size * 0.14), textTransform: 'uppercase', align: 'left', ...extra });

// #region answer: one set of identifiers for the whole book, resolved across chapters
// buildBundle lays the chapters out in order. Each chapter whose text names a target it
// does not hold (`@sec:array-size` in chapter 1, `@tbl:loads` in chapter 3) is laid out
// with the outline of the whole book, so the reference prints "section 2.3" and its page,
// and links to it. Headings carry their ids in the Markdown, `## Sizing the array
// {#sec:array-size}`; figures and tables are resources whose ids are what follows the @.

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

#Stampa «Figure 2.1» nel testo

Un libro che scrive per esteso i suoi rimandi usa il nome completo del tipo invece dell’etichetta breve.

-  shortLabel: type.id === 'table' ? t({ en: 'table', es: 'tabla' })
-    : t({ en: 'fig.', es: 'figura' }),
+  shortLabel: type.id === 'table' ? t({ en: 'Table', es: 'Tabla' })
+    : t({ en: 'Figure', es: 'Figura' }),

#Numera le sezioni con il segno di paragrafo

-  section: t({ en: 'section {n}', es: 'apartado {n}' }), // @sec:losses → "section 2.2"
+  section: '§ {n}',

Errori frequenti

Errore frequente

Una figura viene numerata e collocata dove è citata la prima volta

Il primo rimando :ref o @fig: a una figura o a una tabella le dà il numero e la posizione, quindi un rimando in un capitolo precedente la porta lì. Rimanda in avanti alla sezione che la contiene, e alla figura stessa solo dopo che è stata collocata. Rimandi →

  • Un rimando a un id che nessun capitolo imposta stampa ?. Controlla gli id dopo aver rinominato un titolo in un capitolo: i rimandi a esso vivono negli altri.
  • Impaginare i capitoli uno per uno con buildDocument fa perdere sia i contatori sia la struttura del libro: ogni capitolo numera di nuovo le figure da 1 e un rimando a un altro capitolo stampa ?. Usa buildBundle, oppure concatena continuation e passa tu outline.
  • In Postext le equazioni non hanno una numerazione propria, quindi @eq: trova solo un’ancora impostata da te e ne stampa il testo; questo libro scrive le sue due formule senza numero.
  • Un titolo di sezione che apre una pagina, o che sta sotto una tabella flottante in testa come fa la 3.3 a pagina 9, perde per impostazione predefinita tutto lo spazio sopra, e l’aggancio alla griglia mette allora sotto il titolo la frazione di riga di cui ha bisogno, più lontano dal suo testo dei titoli a metà pagina. headings.columnHeadSpace: 'remainder' tiene quella frazione di riga sopra il titolo (titoli). Si addice a un libro a una colonna, dove nessuna colonna accanto mostra che il titolo comincia un po’ più in basso.

Crediti

Testo
Testo originale, CC BY 4.0
Font
IBM Plex Serif (SIL OFL 1.1) · IBM Plex Sans Condensed (SIL OFL 1.1) · IBM Plex Mono (SIL OFL 1.1)
SandboxPDF