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
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
- Funzionalità
- Impaginazione in un Web WorkerI font prima dell’impaginazionePagine su un canvasFormato della paginaMargini speculariCarattere del testo correnteCapitoli che si aprono su un rectoAperture progettateTitoli numeratiStili di titoloCapitoli non numeratiTestatine per sezioneTestatine e folioTestatine secondo il ruolo della paginaImmagini nei progetti di paginaFigure e tabelle come risorseStili di paragrafoColore della cartaSpazio verticale esplicito
- Usa anche
- Attributi dei titoli
- 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
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
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
// # 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
// 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
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
// ═══ 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,
/* The editor: the Markdown on the left, the page it sets on the right, on a walnut desk. */
#editor {
--desk: #1c1814; --well: #120f0c; --text: #e4d9c1; --dim: #a39680; --brass: #c9a75e;
display: grid; grid-template-columns: minmax(0, 1fr) auto; grid-template-rows: auto 1fr auto;
gap: 0 30px; box-sizing: border-box; width: min(1152px, 100% - 32px); margin: 24px auto 0;
padding: 0 30px; background: var(--desk); border-radius: 14px;
box-shadow: 0 0 0 1px #2c261f, 0 30px 60px -30px rgb(0 0 0 / .9);
font: 500 12px/1.4 system-ui, sans-serif; color: var(--dim);
}
#editor > header, #editor > footer {
grid-column: 1 / -1; display: flex; align-items: center; gap: 12px; min-height: 58px;
letter-spacing: .12em; text-transform: uppercase;
}
#editor > header { justify-content: space-between; }
#editor select {
margin-left: 8px; padding: 5px 8px; border: 1px solid #3a3229; border-radius: 6px;
background: var(--well); color: var(--text); font: inherit; letter-spacing: .06em;
}
#source {
box-sizing: border-box; width: 100%; height: 100%; min-height: 360px; resize: none;
padding: 20px 22px; border: 0; border-radius: 8px; outline: 1px solid #2c261f;
background: var(--well); color: var(--text); caret-color: var(--brass);
font: 13.5px/1.7 ui-monospace, 'SF Mono', Menlo, Consolas, monospace;
scrollbar-width: thin; scrollbar-color: #3a3229 transparent;
}
#source:focus { outline-color: var(--brass); }
#source::selection { background: rgb(201 167 94 / .35); }
#editor figure { margin: 0; display: flex; flex-direction: column; align-items: center; }
/* The page at 110 × 147 mm, as tall as the desk allows. */
#proof {
display: block; height: min(700px, 100vh - 170px); aspect-ratio: 110 / 147; background: #f2ead8;
box-shadow: 0 1px 2px rgb(0 0 0 / .6), 0 24px 44px -18px rgb(0 0 0 / .9);
}
#editor figcaption { display: flex; align-items: center; gap: 14px; margin-top: 12px; }
#editor figcaption button {
width: 30px; height: 30px; border: 1px solid #3a3229; border-radius: 50%; padding: 0;
background: none; color: var(--text); font: 16px/1 system-ui, sans-serif; cursor: pointer;
}
#editor figcaption button:hover { border-color: var(--brass); color: var(--brass); }
#folio { min-width: 56px; text-align: center; font-variant-numeric: tabular-nums; }
#editor > footer { color: var(--text); font-variant-numeric: tabular-nums; }
/* The heartbeat: a hand the main thread turns every frame. */
#beat { width: 24px; height: 24px; flex: none; }
#beat circle { fill: none; stroke: var(--brass); stroke-width: 1.5; }
#beat path { stroke: var(--brass); stroke-width: 2; stroke-linecap: round; }
@media (max-width: 760px) {
#editor { grid-template-columns: 1fr; padding: 0 16px; gap: 0; }
#editor > header { flex-direction: column; align-items: flex-start; padding: 14px 0; }
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
- Ricetta
- Ignacio Ferro
- Testo
- The Time Machine, chapter I · H. G. Wells · pubblico dominio
- 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)
- Codice
- MIT, come Postext
Modifica questo testo ↗ (si apre in una nuova scheda)Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)


