Vai al contenuto principale
Ricetta numero 56

Ricettario · Capitolo 10 · Output e integrazione

Editor dal vivo con l’impaginazione in un Web Worker

Il Markdown accanto a una pagina tascabile: un Web Worker compone il capitolo con i propri font, e ogni tasto premuto annulla la composizione in corso.

In questa pagina
  • Esempio in inglese: non c’è ancora un’edizione italiana
  • Formato 110 × 147 mm
  • 1 colonna
  • Baskervville 9,5/13
  • Baskervville SC
  • Cinzel
  • 9 pagine
  • Livello
  • Postext 1.57.1
  • Impaginato in 111 ms
  • 242 righe di codice

In breve

Un editor dal vivo per una piccola edizione tascabile di The Time Machine. Ogni volta che scrivi, la pagina viene impaginata di nuovo in background, così lo schermo continua a rispondere.

Che cosa comporrai

Componi il capitolo I di The Time Machine di H. G. Wells come un’edizione tascabile di 110 × 147 mm, con il Markdown accanto. La pagina del titolo ha la fotografia di un quadrante d’ottone con quattro piccoli quadranti, generata con modelli di diffusione, su un campo rosso sangue di bue disegnato nel codice, sopra il titolo in Cinzel. Il testo del capitolo comincia sulla nona riga, sotto un numero romano e un filetto d’ottone, e scorre in Baskervville a 9,5 su 13 pt sotto testatine in maiuscoletto. Ogni tasto premuto compone di nuovo l’intero capitolo in un Web Worker, e il canvas a destra va alla pagina che contiene il cursore. Sotto l’editor, una lancetta che il thread principale fa girare a ogni frame si ferma mentre quel thread è occupato, e la riga di stato dà il tempo della composizione, il frame più lungo e quante composizioni ha annullato un tasto più recente. Un menu in alto a destra sposta la composizione nel thread principale per confronto.

Questa ricetta risponde a

  • Come mantengo reattiva la pagina mentre si impagina un libro lungo (Web Worker, annullamento)?
  • Perché cambiano i miei a capo, o le parole si sovrappongono nel PDF, e come carico correttamente i font?
  • Posso generare pagine o PDF su un server o in una CLI (Node)?

La risposta breve

script.js · righe 135–159nel codice completo
async function startLayoutWorker(faces) {
  // No options: from a CDN the engine starts its worker entry, at the page's own version,
  // through a same-origin blob; in a bundle it starts the worker file next to the module.
  const layout = createLayoutWorker();
  // The worker measures with its own FontFaceSet, not the page's. Without the bytes of every
  // face it measures in a fallback font, and the console names each missing family once.
  const payloads = await Promise.all(faces.map(async ({ family, weight, style, url }) => {
    // Check the status: a 404 page sent as a font only logs a warning inside the worker.
    const response = await fetch(url);
    if (!response.ok) throw new Error(`${family} ${weight} ${style}: HTTP ${response.status}`);
    return { family, weight, style, buffer: await response.arrayBuffer() };
  }));
  await layout.registerFonts(payloads); // the buffers move to the worker, not copied
  let inFlight = null;
  return async function typeset(content) {
    inFlight?.abort(); // cancel the build that the previous keystroke asked for
    const build = (inFlight = new AbortController());
    try {
      return await layout.build(content, config(), { signal: build.signal });
    } catch (error) {
      if (error.name === 'AbortError') return null; // superseded: a newer build is on its way
      throw error;
    }
  };
}

Ingredienti

Tipo
Baskervville, Baskervville SC, Cinzel (SIL OFL 1.1)
Risorse
  • dial-1120.jpg
  • The title page’s brass dial, a photograph (Generated With Diffusion Models, originale)
  • The title page’s oxblood cloth and gilt frame, drawn in code in the page’s palette (Ignacio Ferro, MIT)

Preparazione

#1 · Avvia il worker con una sola chiamata

Il codice di questo passo è nella risposta breve qui sopra. createLayoutWorker() non prende opzioni. Quando il modulo viene da esm.sh, il file del worker sta sull’origine di esm.sh, dove il costruttore Worker lo rifiuta, quindi il motore avvia il suo punto d’ingresso del worker tramite un blob della stessa origine, alla versione importata dalla pagina. In un’app con bundler la stessa chiamata avvia il file del worker che sta accanto al modulo. Il build() dell’handle prende lo stesso contenuto e la stessa configurazione di buildDocument() e si risolve nello stesso tipo di documento (Eseguire l’impaginazione in un Web Worker).

#2 · Carica ogni carattere due volte

script.js · righe 309–321nel codice completo
const FONTS = { // every face the pages use: the page loads them, and so must the worker
  Baskervville: ['400', '400i'], // text, folios, subtitle, colophon
  'Baskervville SC': ['500'], // running heads, the author
  Cinzel: ['700'], // title, numeral, chapter title
};
// The worker gets the same Fontsource files the page loads: identical metrics on both threads.
const faces = Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) => {
  const [id, weight, style] = [family.toLowerCase().replace(/ /g, '-'), parseInt(spec, 10),
    spec.endsWith('i') ? 'italic' : 'normal'];
  const file = `${id}@5/files/${id}-latin-${weight}-${style}.woff2`;
  return { family, weight: String(weight), style,
    url: `https://cdn.jsdelivr.net/npm/@fontsource/${file}` };
}));

Il worker ha un proprio FontFaceSet e non vede i caratteri caricati dalla pagina, quindi la risposta breve scarica gli stessi file di Fontsource e passa i loro byte a registerFonts(), con ogni peso come stringa ('400'). Togli quella chiamata e il worker misura con un font di ripiego: compone questo capitolo in 175 righe invece di 190, la prima riga finisce con «him)» invece che con «of», e la console della pagina indica una volta ogni famiglia mancante. Un file di font che non si scarica è più difficile da notare. Se il worker riceve una pagina 404 al posto del Baskervville tondo, registerFonts() si risolve comunque e il capitolo esce in 186 righe, con un avviso solo nella console del worker. La risposta breve controlla perciò lo stato di ogni risposta prima di mandare qualsiasi byte, e lancia un errore con il carattere e lo stato HTTP. La pagina carica gli stessi caratteri anche con loadFonts(), perché il canvas disegna con i font della pagina.

#3 · Componi a ogni tasto, dipingi nel thread principale

script.js · righe 344–390nel codice completo
let [doc, shown, builds, cancelled] = [null, 0, 0, 0];
// For the comparison, the main thread keeps a measurement cache between keystrokes, as the
// worker does: both threads then time a build that measures only what changed.
const mainCache = createMeasurementCache();
function paint(n = shown) { // the canvas is sized to its box, in device pixels
  shown = Math.max(0, Math.min(doc.pages.length - 1, n));
  const vdtPage = doc.pages[shown]; // a laid-out page, not the page config above
  const height = ($('proof').clientHeight || 640) * Math.min(devicePixelRatio || 1, 2);
  renderPageToCanvas(vdtPage, doc, $('proof'), { scale: height / vdtPage.height });
  $('proof').setAttribute('aria-label', `Page ${vdtPage.pageLabel}`);
  $('folio').value = `${shown + 1} / ${doc.pages.length}`;
}
function follow() { // turn to the page that holds the caret: every block keeps its source offset
  const caret = $('source').selectionStart;
  paint(doc.pages.findLastIndex((vdtPage) => vdtPage.columns.some((column) =>
    column.blocks.some((block) => block.sourceStart <= caret))));
}
async function refresh() {
  const [ticket, onMain, started] = [++builds, $('thread').value === 'main', performance.now()];
  frames.worst = 0;
  const content = { markdown: $('source').value, resources };
  const next = onMain ? buildDocument(content, config(), mainCache) : await typeset(content);
  await new Promise(requestAnimationFrame); // the first frame after the build shows any stall
  if (!next || ticket !== builds) { cancelled++; return; } // a newer build has been asked for
  doc = next;
  if (document.activeElement === $('source')) follow(); else paint();
  showPages(doc, { title: 'The Time Machine · chapter I, set in a Web Worker' });
  $('clock').value = `${onMain ? 'Main thread' : 'Worker'} · ${doc.pages.length} pages in `
    + `${Math.round(performance.now() - started)} ms · longest frame ${Math.round(frames.worst)}`
    + ` ms · ${builds} ${builds === 1 ? 'build' : 'builds'}, ${cancelled} cancelled`;
}
$('source').addEventListener('input', refresh);
for (const type of ['click', 'keyup']) $('source').addEventListener(type, () => doc && follow());
$('thread').addEventListener('change', refresh);
$('prev').addEventListener('click', () => paint(shown - 1));
$('next').addEventListener('click', () => paint(shown + 1));
// A dial the main thread turns on every frame: it stops while that thread is busy.
const frames = { last: 0, worst: 0 };
requestAnimationFrame(function turn() { // the clock, not the frame's timestamp: a late frame
  const now = performance.now(); // keeps the time it was due, which hides the stall
  frames.worst = Math.max(frames.worst, now - (frames.last || now));
  frames.last = now;
  const deg = ((now * 0.06) % 360).toFixed(1); // a turn in 6 s
  $('hand').setAttribute('transform', `rotate(${deg})`);
  requestAnimationFrame(turn);
});
await refresh();

typeset() interrompe la composizione in corso prima di chiedere la successiva. La promise della composizione interrotta viene subito rifiutata con un AbortError, che typeset() trasforma in null. Nel worker, una composizione ancora in coda viene scartata subito, e una in esecuzione si ferma alla fine della passata di collocazione corrente, perché la composizione controlla un annullamento solo tra una passata e l’altra. refresh() numera le sue composizioni e disegna solo la più recente, così una composizione del worker che arriva in ritardo non può disegnare sopra una del thread principale. Il documento torna al thread principale, dove renderPageToCanvas() lo disegna con le immagini registrate lì. Al worker serve solo la misura di ogni immagine, che la voce della risorsa contiene (1100 × 840). Ogni blocco conserva la propria posizione nel Markdown (sourceStart), e follow() mostra l’ultima pagina con un blocco che comincia al cursore o prima.

#4 · Una pagina del titolo che è uno stile di titolo

script.js · righe 55–77nel codice completo
// # The Time Machine {style="title"}: numbered false, so the Introduction is still chapter I.
const PLATE = TRIM.width * (840 / 1100); // mm: the plate's depth at full width (84 mm)
const DIAL = { x: 20, y: 7, size: 70 }; // mm: the dial's photograph, centred on the plate
const titlePage = {
  id: 'title', numbered: false,
  span: 'page', // the author's name stands below the column's foot, which would cut it
  header: { elements: [] }, footer: { elements: [] }, // no running head, no folio
  advancedDesign: { enabled: true, slot: { elements: [
    { kind: 'image', id: 'plate', resourceId: 'plate',
      placement: { anchor: { to: 'bleed', edge: 'top-left' }, size: { width: 'fill' } } },
    { kind: 'image', id: 'dial', resourceId: 'dial', placement: { anchor: { to: 'bleed',
      edge: 'top-left' }, offset: { x: mm(DIAL.x), y: mm(DIAL.y) },
      size: { width: mm(DIAL.size), height: mm(DIAL.size) } } },
    text('title', '{titleText}', DISPLAY, 28, { fontWeight: 700, lineHeight: 1.04,
      overflow: 'wrap' }, // the title takes two lines
    onPage(PLATE + 11)),
    text('subtitle', '{subtitle}', TEXT, 12, { italic: true, color: col('oxblood') },
      onPage(PLATE + 34.5)),
    brassRule('rule', onPage(PLATE + 43), 12),
    text('author', '{author}', LABEL, 10, { fontWeight: 500, letterSpacing: pt(2) },
      onPage(PLATE + 46.5)),
  ] } },
};

La riga # The Time Machine {style="title"} compone la pagina 1 nello stile di titolo title, i cui header e footer vuoti lasciano la pagina senza testatine né numero di pagina. numbered: false tiene il titolo fuori dal conteggio dei capitoli, così Introduction resta il capitolo I. La tavola è ancorata all’angolo in alto a sinistra dell’abbondanza, e il nome dell’autore è composto sotto il piede della colonna. Una grafica tenuta nella sua colonna viene tagliata al piede della colonna, quindi lo stile imposta span: 'page'; senza, il nome dell’autore non viene disegnato.

#5 · Testatine secondo il ruolo della pagina

script.js · righe 81–97nel codice completo
// pages: 'body' keeps the heads off the title page and the opener; parity puts the book's
// title on the verso and the chapter on the recto, folios on the outer edge.
const HEAD_Y = 8.2; // mm from the top edge to the top of the running heads
const SHIFT = (INNER - OUTER) / 2; // mm: the text block's centre is off the page's centre
const head = (id, content, parity, edge, x, style) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontSize: pt(8), color: col('oxblood'), ...style,
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(HEAD_Y) } } });
const smallCaps = { fontFamily: LABEL, fontWeight: 500, letterSpacing: pt(1.2) };
const folio = { fontFamily: TEXT, color: col('ink') }; // the heads' size: the same baseline
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-title', '{title}', 'even', 'top', -SHIFT, smallCaps),
  head('recto-chapter', '{chapterTitle}', 'odd', 'top', SHIFT, smallCaps),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };
const footer = { elements: [{ ...text('drop-folio', '{pageNumber}', TEXT, 8,
  { color: col('muted') }, inColumn(6.5)), pages: 'opener' }] };

pages: 'body' tiene le testatine lontane dalla pagina del titolo e dall’apertura, e parity compone il titolo del libro sui versi e quello del capitolo sui recti, con i numeri di pagina sul margine esterno. L’apertura riceve invece un numero di pagina al piede, da un elemento del piè di pagina con pages: 'opener'. Numeri di pagina e testatine sono tutti a 8 pt e stanno 8,2 mm sotto il bordo superiore, così le cifre dei numeri di pagina poggiano sulla linea di base delle testatine.

#6 · L’apertura del capitolo

script.js · righe 101–112nel codice completo
const chapter = { level: 1, numberingTemplate: '{1:I}', // {number} prints 'I'
  breakBefore: { enabled: true, parity: 'any' }, // the next page, on either side
  marginTop: pt(0), marginBottom: pt(0),
  advancedDesign: { enabled: true, minHeight: line(8), slot: { elements: [
    text('numeral', '{number}', DISPLAY, 24, { fontWeight: 700, color: col('oxblood') },
      inColumn(5)),
    brassRule('rule', inColumn(18.5), 10),
    text('chapter', '{titleText}', DISPLAY, 12, { fontWeight: 700, letterSpacing: pt(1.8),
      textTransform: 'uppercase', overflow: 'wrap' }, inColumn(22.5)), // a longer title wraps
  ] } } };
const colophon = { id: 'colophon', fontSize: pt(7.5), lineHeight: pt(10.5), color: col('muted'),
  textAlign: 'center', firstLineIndent: pt(0) };

Il {number} della grafica stampa il numero del capitolo nella forma che gli dà numberingTemplate: '{1:I}', un I romano. minHeight riserva almeno otto righe, così il testo comincia sulla nona mentre il titolo occupa una o due righe, e più in basso quando un titolo più lungo richiede più spazio. breakBefore con parity: 'any' lascia aprire il capitolo a pagina 2, di fronte alla sua seconda pagina; il valore predefinito lo manderebbe a pagina 3, un recto.

La ricetta completa

Sandbox
// ═══ Postext Cookbook · Nº 056 · Live editor with layout in a Web Worker ═══════════
// https://postext.dev/en/cookbook/web-worker-live-editor
// Code: MIT · Text: H. G. Wells, The Time Machine, 1895 (PD, Gutenberg #35) · Dial: generated
// Fonts: Baskervville, Baskervville SC, Cinzel (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import {
  buildDocument, createMeasurementCache, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
import { createLayoutWorker } from 'https://esm.sh/postext/worker';

const LANG = 'en'; // @lang: the language of the sample document (this recipe is English only)
const RECIPE = 'web-worker-live-editor';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { // every colour in the config links to one of these
  ink: '#231f1a', // the text: a warm near-black
  oxblood: '#7a1f1f', // the accent: running heads, the numeral, the subtitle, the plate's cloth
  brass: '#a88a4a', // rules (never text: 2.7:1 on the paper)
  gilt: '#d8bd7c', // the plate's frame, on the oxblood
  muted: '#6b5d4b', // the drop folio and the colophon (5.3:1 on the paper)
  paper: '#f2ead8', // a cream pocket-book paper
};
// 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).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  // The engine's defaults link to 'main-color'. The editor takes any Markdown, and without this
  // entry a list typed into it gets the default blue markers.
  { id: 'main-color', name: 'oxblood (defaults)', value: { hex: palette.oxblood, model: 'hex' } },
];
const [TEXT, LABEL, DISPLAY] = ['Baskervville', 'Baskervville SC', 'Cinzel'];

// The page: 110 × 147 mm, a text block of 25 whole lines.
const TRIM = { width: 110, height: 147 }; // mm: a Victorian pocket size, close to A6
const [BODY, LEAD, LINES] = [9.5, 13, 25]; // pt, pt, lines: the text block is LINES leads deep
const [TOP, INNER, OUTER] = [15, 11, 9]; // mm; mirrored, so INNER is the spine side
const MM_PER_PT = 25.4 / 72;
const MEASURE = TRIM.width - INNER - OUTER; // 90 mm: about 60 characters of Baskervville
const line = (n) => pt(n * LEAD); // n grid lines
const page = {
  sizePreset: 'custom', width: mm(TRIM.width), height: mm(TRIM.height), dpi: 150,
  backgroundColor: col('paper'),
  margins: { top: mm(TOP), bottom: mm(TRIM.height - TOP - LINES * LEAD * MM_PER_PT),
    left: mm(INNER), right: mm(OUTER), mirror: true },
};

const onPage = (y) => ({ anchor: { to: 'page', edge: 'top' }, offset: { y: mm(y) } }); // centred
const inColumn = (y) => ({ anchor: { to: 'container', edge: 'top' }, offset: { y: mm(y) } });
const text = (id, content, fontFamily, fontSize, style, placement) => ({ kind: 'text', id,

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)

Errori frequenti

Errore frequente

Il worker di impaginazione misura con i propri font

Un worker ha un FontFaceSet tutto suo, quindi le varianti caricate dalla pagina gli sono invisibili. Mandagli i byte di ogni variante con registerFonts() prima della prima build; il peso può essere una stringa ('400') o, da postext 1.5, un numero. Senza di essi il worker misura con un font di ripiego e cambiano gli a capo e il numero di pagine; dalla 1.5 la console lo segnala, una volta per ogni famiglia mancante. Impaginazione in un Web Worker →

Crediti

Testo
Immagini
  • The title page’s brass dial, a photograph · Generated With Diffusion Models · originale
  • The title page’s oxblood cloth and gilt frame, drawn in code in the page’s palette · Ignacio Ferro · MIT
Font
Baskervville (SIL OFL 1.1) · Baskervville SC (SIL OFL 1.1) · Cinzel (SIL OFL 1.1)
Sandbox