En poques paraules
Un editor en directe per a una edició de butxaca de La màquina del temps. Cada vegada que escrius, la pàgina es torna a compondre en segon pla, i la pantalla continua responent.
Què compondràs
Compons el capítol I de La màquina del temps, de H. G. Wells, en anglès, com a llibre de butxaca de 110 × 147 mm, al costat del seu Markdown. La portada porta la fotografia d'un quadrant de llautó amb quatre esferes, generada amb models de difusió, sobre un camp bordeus dibuixat en codi i, a sota, el títol en Cinzel. El text del capítol comença a la novena línia, sota un número romà i un filet de llautó, i va en Baskervville de 9,5/13 pt, amb capçaleres en versaletes. Cada pulsació torna a compondre el capítol en un Web Worker, i a la dreta apareix la pàgina on és el cursor. Sota l'editor, una agulla que el fil principal fa girar a cada fotograma s'atura mentre aquest fil està ocupat, i la línia d'estat dona la durada, el fotograma més llarg i les composicions que va cancel·lar una pulsació posterior. Un desplegable a dalt a la dreta passa la composició al fil principal, per comparar.
Aquesta recepta respon a
- Com evito que la pàgina es bloquegi mentre es compon un llibre llarg (Web Worker, cancel·lació)?
- Per què canvien els meus talls de línia o se solapen les paraules al PDF, i com carrego bé les fonts?
- Puc generar pàgines o PDF en un servidor o des de la línia d'ordres (Node)?
La resposta curta
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;
}
};
}
Ingredients
- Funcions
- Composició en un Web WorkerFonts abans de compondrePàgines en un canvasFormat de pàginaMarges simètricsTipografia del textCapítols que obren en pàgina senarObertures dissenyadesTítols numeratsEstils de títolCapítols sense númeroCapçaleres per seccióCapçaleres i folisCapçaleres segons el tipus de pàginaImatges als dissenys de pàginaFigures i taules com a recursosEstils de paràgrafColor del paperEspai vertical explícit
- També fa servir
- Atributs de títol
- Tipografia
- Baskervville, Baskervville SC, Cinzel (SIL OFL 1.1)
- Recursos
dial-1120.jpg- The title page’s brass dial, a photograph (Generated With Diffusion Models, original)
- The title page’s oxblood cloth and gilt frame, drawn in code in the page’s palette (Ignacio Ferro, MIT)
Elaboració
#1 · Arrenca el worker amb una crida
El codi d'aquest pas és la resposta curta. createLayoutWorker() va sense opcions. Si el mòdul ve d'esm.sh, el fitxer del worker és d'un altre origen i el constructor Worker el rebutjaria, així que el motor arrenca la seva entrada de worker a través d'un blob de l'origen de la pàgina, en la mateixa versió que ha importat la pàgina. En una aplicació empaquetada, la mateixa crida arrenca el fitxer del worker que hi ha al costat del mòdul. L'objecte que retorna té un build() que accepta el mateix contingut i la mateixa configuració que buildDocument() i es resol amb el mateix tipus de document (Executar la composició en un Web Worker).
#2 · Carrega cada font dues vegades
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}` };
}));
El worker té el seu propi FontFaceSet i no veu les fonts que ha carregat la pàgina, així que la resposta curta baixa els mateixos fitxers de Fontsource i passa els seus bytes a registerFonts(), amb el gruix com a cadena ('400'). Si treus aquesta crida, el worker mesura amb una font de reserva: compon aquest capítol en 175 línies en lloc de 190, ja la primera línia acaba en «him)» en lloc d'en «of», i la consola de la pàgina anomena una vegada cada família que falta. Un fitxer que no es baixa es veu pitjor. Si al worker li arriba una pàgina 404 en lloc de la Baskervville rodona, registerFonts() es resol igualment i el capítol surt en 186 línies, amb un avís només a la consola del worker. Per això la resposta curta comprova el codi HTTP de cada baixada abans d'enviar cap byte, i si alguna falla llança un error amb la font i el codi. La pàgina carrega a més les mateixes fonts amb loadFonts(), perquè el canvas pinta amb les de la pàgina.
#3 · Compon a cada pulsació, pinta al fil principal
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() cancel·la la composició en curs abans de demanar la següent. La promesa de la composició cancel·lada es rebutja a l'acte amb un AbortError, que typeset() converteix en null. Al worker, una composició que encara espera a la cua es descarta de seguida, i la que està en marxa s'atura en acabar la seva passada de col·locació, perquè la cancel·lació només es comprova entre una passada i la següent. refresh() numera les seves composicions i només pinta l'última, així que una composició del worker que arriba tard no pot pintar a sobre d'una del fil principal. El document torna al fil principal, on renderPageToCanvas() el pinta amb les imatges registrades allà. Al worker només li cal la mida de cada imatge, que va al recurs (1100 × 840). Cada bloc guarda la seva posició al Markdown (sourceStart), i follow() mostra l'última pàgina amb un bloc que comença al cursor o abans.
#4 · Una portada que és un estil d'encapçalament
// # 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 línia # The Time Machine {style="title"} compon la pàgina 1 amb l'estil d'encapçalament title, amb un header i un footer buits que la deixen sense capçaleres ni foli. numbered: false deixa el títol fora del compte de capítols, així que Introduction continua sent el capítol I. La làmina s'ancora a la cantonada superior esquerra de la sang, i el nom de l'autor queda per sota del peu de la columna. Un disseny que es queda a la seva columna es talla al peu de la columna, així que l'estil porta span: 'page'; sense aquesta opció, el nom de l'autor no es pinta.
#5 · Capçaleres segons el tipus de pàgina
// 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' deixa sense capçaleres la portada i l'obertura, i parity posa el títol del llibre a les pàgines parelles i el del capítol a les senars, amb els folis al marge exterior. L'obertura porta en canvi un foli al peu, un element del footer amb pages: 'opener'. Folis i capçaleres van en cos 8 i a 8,2 mm de la vora superior, així que les xifres del foli es recolzen a la mateixa línia de base que la capçalera.
#6 · L'obertura del capítol
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) };
El {number} del disseny imprimeix el número del capítol amb la forma que li dona numberingTemplate: '{1:I}', una I romana. minHeight reserva almenys vuit línies, així que el text comença a la novena mentre el títol n'ocupi una o dues, i més avall si un títol més llarg necessita més espai. breakBefore amb parity: 'any' deixa que el capítol obri a la pàgina 2, davant de la seva segona pàgina; el valor per defecte el portaria a la 3, una pàgina senar.
La recepta 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; }
L'script.js compost funciona tal com és: enganxa'l com a script de mòdul en qualsevol pàgina o obre la recepta a CodePen. Carpeta de la recepta a GitHub ↗ (s'obre en una pestanya nova)
Errors freqüents
Error freqüent
El worker de composició mesura amb les seves pròpies fonts
Un worker té el seu propi FontFaceSet, així que no veu les fonts que ha carregat la pàgina. Envia-li els bytes de cada font amb registerFonts() abans de la primera composició; el pes pot ser un text ('400') o, des de postext 1.5, un nombre. Sense aquests bytes el worker mesura amb una font de reserva i canvien els salts de línia i el nombre de pàgines; des de la 1.5 la consola n'avisa, una vegada per cada família que falta. Composició en un Web Worker →
Crèdits
- Recepta
- Ignacio Ferro
- Text
- The Time Machine, chapter I · H. G. Wells · domini públic
- Imatges
- The title page’s brass dial, a photograph · Generated With Diffusion Models · original
- The title page’s oxblood cloth and gilt frame, drawn in code in the page’s palette · Ignacio Ferro · MIT
- Fonts
- Baskervville (SIL OFL 1.1) · Baskervville SC (SIL OFL 1.1) · Cinzel (SIL OFL 1.1)
- Codi
- MIT, com Postext
Editar aquest text ↗ (s'obre en una pestanya nova)Carpeta de la recepta a GitHub ↗ (s'obre en una pestanya nova)


