Skip to main content
Recipe number 56

Cookbook · Chapter 10 · Output & integration

Live editor with layout in a Web Worker

Markdown beside a pocket page: a Web Worker sets the chapter with its own fonts, and each keystroke cancels the build in flight.

  • Trim 110 × 147 mm
  • 1 column
  • Baskervville 9.5/13
  • Baskervville SC
  • Cinzel
  • 9 pages
  • Level
  • Postext 1.57.1
  • Laid out in 111 ms
  • 242 lines of code

In short

A live editor for a small pocket edition of The Time Machine. Each time you type, the page is laid out again in the background, so the screen keeps responding.

What you'll build

You set chapter I of H. G. Wells's The Time Machine as a 110 × 147 mm pocket edition, with the Markdown beside it. The title page has a photograph of a brass dial with four small dials, generated with diffusion models, on an oxblood field drawn in code, over the title in Cinzel. The chapter's text starts on the ninth line, under a roman numeral and a brass rule, and runs in Baskervville at 9.5 on 13 pt under small-capital running heads. Every keystroke sets the whole chapter again in a Web Worker, and the canvas on the right turns to the page that holds the caret. Under the editor, a hand that the main thread turns every frame stops while that thread is busy, and the status line gives the build's time, the longest frame and how many builds a newer keystroke cancelled. A menu at the top right moves the build to the main thread for comparison.

This recipe answers

  • How do I keep the page responsive while a long book lays out (Web Worker, cancellation)?
  • Why do my line breaks change, or PDF words overlap, and how do I load fonts correctly?
  • Can I generate pages or PDFs on a server or in a CLI (Node)?

The short answer

script.js · lines 135–159in full code
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;
    }
  };
}

Layout in a module worker, with its own fonts

Ingredients

Type
Baskervville, Baskervville SC, Cinzel (SIL OFL 1.1)
Assets
  • 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)

Method

#1 · Start the worker with one call

This step's code is the short answer above. createLayoutWorker() takes no options. When the module comes from esm.sh, the worker file is on esm.sh's origin, where the Worker constructor refuses it, so the engine starts its worker entry through a same-origin blob, at the version the page imported. In a bundled app the same call starts the worker file next to the module. The handle's build() takes the same content and config as buildDocument() and resolves to the same kind of document (Running layout in a Web Worker).

#2 · Load every face twice

script.js · lines 309–321in full code
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}` };
}));

The worker has a FontFaceSet of its own and cannot see the faces the page has loaded, so the short answer fetches the same Fontsource files and passes their bytes to registerFonts(), with each weight as a string ('400'). Leave that call out and the worker measures in a fallback font: it sets this chapter in 175 lines instead of 190, the first line ends on “him)” instead of “of”, and the page's console names each missing family once. A font file that fails to download is harder to see. If the worker receives a 404 page in place of the roman Baskervville, registerFonts() still resolves and the chapter comes out in 186 lines, with a warning only in the worker's console. The short answer therefore checks each response's status before it sends any bytes, and throws with the face and the HTTP status. The page loads the same faces with loadFonts() as well, because the canvas paints with the page's fonts.

#3 · Build on every keystroke, paint on the main thread

script.js · lines 344–390in full code
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() aborts the build in flight before it asks for the next. The aborted build's promise rejects at once with an AbortError, which typeset() turns into null. In the worker, a build still waiting in the queue is dropped straight away, and a running one stops at the end of its current placement pass, because the build checks for a cancel only between passes. refresh() numbers its builds and paints only the newest, so a worker build that arrives late cannot paint over a main-thread one. The document comes back to the main thread, where renderPageToCanvas() paints it with the images registered there. The worker needs only each picture's size, which the resource entry carries (1100 × 840). Every block keeps its offset in the Markdown (sourceStart), and follow() shows the last page with a block that starts at or before the caret.

#4 · A title page that is a heading style

script.js · lines 55–77in full code
// # 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)),
  ] } },
};

The line # The Time Machine {style="title"} sets page 1 in the title heading style, whose empty header and footer leave the page without running heads or folio. numbered: false keeps the title out of the chapter count, so Introduction is still chapter I. The plate is anchored to the top-left corner of the bleed, and the author's name is set below the foot of the column. A design kept in its column is cut at the column's foot, so the style sets span: 'page'; without it the author's name is not painted.

#5 · Running heads by page role

script.js · lines 81–97in full code
// 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' keeps the running heads off the title page and the opener, and parity sets the book's title on versos and the chapter's on rectos, with folios at the outer edge. The opener gets a drop folio instead, from a footer element with pages: 'opener'. Folios and heads are all 8 pt and hang 8.2 mm below the top edge, so the folio's figures stand on the heads' baseline.

#6 · The chapter opener

script.js · lines 101–112in full code
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) };

The design's {number} prints the chapter number in the form numberingTemplate: '{1:I}' gives it, a roman I. minHeight reserves at least eight lines, so the text starts on the ninth while the title takes one or two lines, and further down when a longer title needs more room. breakBefore with parity: 'any' lets the chapter open on page 2, facing its second page; the default would send it to page 3, a recto.

The whole recipe

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,

The composed script.js runs as it is: paste it into any page’s module script, or open the recipe on CodePen. Recipe folder on GitHub ↗ (opens in a new tab)

Pitfalls

Pitfall

The layout worker measures with its own fonts

A worker has a FontFaceSet of its own, so the faces the page has loaded are invisible to it. Send it the bytes of every face with registerFonts() before the first build; the weight may be a string ('400') or, since postext 1.5, a number. Without them the worker measures in a fallback font and the line breaks and the page count change; since 1.5 the console says so, once for each missing family. Layout in a Web Worker →

Credits

Text
Images
  • 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)
Sandbox