Pular para o conteúdo principal
Receita número 56

Receitas · Capítulo 10 · Saída e integração

Editor ao vivo com a diagramação num Web Worker

Markdown ao lado de uma página de bolso: um Web Worker compõe com as próprias fontes, e cada tecla cancela a composição em andamento.

Nesta página
Nível
Avançado
Postext
Testada com o Postext 1.65.0
Requer ≥ 1.25.0
Licença
Atualizada em 10 de out. de 2026
Código MIT · Texto MIT
  • Amostra em inglês: ainda sem edição em português
  • Refile 110 × 147 mm
  • 1 coluna
  • Baskervville 9,5/13
  • Baskervville SC
  • Cinzel
  • 9 páginas
  • Nível
  • Postext 1.57.1
  • Diagramado em 111 ms
  • 242 linhas de código

Em poucas palavras

Um editor ao vivo para uma pequena edição de bolso de A Máquina do Tempo. A cada tecla, a página é diagramada de novo em segundo plano, e a tela continua respondendo.

O que você vai compor

Você compõe o capítulo I de A Máquina do Tempo, de H. G. Wells, em inglês, como uma edição de bolso de 110 × 147 mm, com o Markdown ao lado. A folha de rosto traz a fotografia de um mostrador de latão com quatro mostradores pequenos, gerada com modelos de difusão, sobre um campo cor de sangue de boi desenhado em código, acima do título em Cinzel. O texto do capítulo começa na nona linha, sob um numeral romano e um fio de latão, e corre em Baskervville 9,5/13 pt sob cabeços em versaletes. Cada tecla compõe o capítulo inteiro de novo num Web Worker, e o canvas à direita vai para a página onde está o cursor. Sob o editor, um ponteiro que a thread principal gira a cada quadro para enquanto essa thread está ocupada, e a linha de status mostra o tempo da composição, o quadro mais longo e quantas composições uma tecla mais recente cancelou. Um menu no canto superior direito passa a composição para a thread principal, para comparar.

Esta receita responde a

  • Como evito que a página trave enquanto um livro longo é composto (Web Worker, cancelamento)?
  • Por que as minhas quebras de linha mudam ou as palavras se sobrepõem no PDF, e como carrego as fontes corretamente?
  • Posso gerar páginas ou PDFs em um servidor ou pela linha de comando (Node)?

A resposta curta

script.js · linhas 135–159no código 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;
    }
  };
}

Ingredientes

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

Preparo

#1 · Iniciar o worker com uma chamada

O código deste passo é a resposta curta acima. createLayoutWorker() vai sem opções. Quando o módulo vem do esm.sh, o arquivo do worker está na origem do esm.sh, onde o construtor Worker o recusaria, por isso o motor inicia a entrada de worker por um blob da origem da página, na mesma versão que a página importou. Num app empacotado, a mesma chamada inicia o arquivo do worker que fica ao lado do módulo. O build() do objeto retornado aceita o mesmo conteúdo e a mesma configuração que buildDocument() e resolve com o mesmo tipo de documento (Rodar a diagramação num Web Worker).

#2 · Carregar cada fonte duas vezes

script.js · linhas 309–321no código 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}` };
}));

O worker tem o próprio FontFaceSet e não enxerga as fontes que a página carregou, de modo que a resposta curta baixa os mesmos arquivos do Fontsource e passa os bytes para registerFonts(), com cada peso como string ('400'). Sem essa chamada, o worker mede com uma fonte substituta: compõe este capítulo em 175 linhas em vez de 190, a primeira linha termina em “him)” em vez de “of”, e o console da página cita uma vez cada família que falta. Um arquivo de fonte que não baixa é mais difícil de notar. Se o worker recebe uma página 404 no lugar da Baskervville redonda, registerFonts() resolve do mesmo jeito e o capítulo sai em 186 linhas, com um aviso só no console do worker. Por isso a resposta curta confere o status de cada resposta antes de enviar qualquer byte, e lança um erro com a fonte e o status HTTP. A página também carrega as mesmas fontes com loadFonts(), porque o canvas pinta com as fontes da página.

#3 · Compor a cada tecla, pintar na thread principal

script.js · linhas 344–390no código 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() aborta a composição em andamento antes de pedir a seguinte. A promise da composição abortada é rejeitada na hora com um AbortError, que typeset() transforma em null. No worker, uma composição que ainda espera na fila é descartada de imediato, e uma em andamento para no fim da passada de posicionamento atual, porque a composição só verifica o cancelamento entre uma passada e outra. refresh() numera as composições e pinta só a mais recente, por isso uma composição do worker que chega atrasada não pode pintar por cima de uma da thread principal. O documento volta para a thread principal, onde renderPageToCanvas() o pinta com as imagens registradas ali. O worker só precisa do tamanho de cada imagem, que vem na entrada do recurso (1100 × 840). Cada bloco guarda a posição no Markdown (sourceStart), e follow() mostra a última página com um bloco que começa no cursor ou antes dele.

#4 · Uma folha de rosto que é um estilo de título

script.js · linhas 55–77no código 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)),
  ] } },
};

A linha # The Time Machine {style="title"} compõe a página 1 no estilo de título title, cujos header e footer vazios deixam a página sem cabeços nem fólio. numbered: false deixa o título fora da contagem de capítulos, por isso Introduction continua sendo o capítulo I. A ilustração é ancorada no canto superior esquerdo da sangria, e o nome do autor fica abaixo do pé da coluna. Um design mantido na coluna é cortado no pé dela, por isso o estilo define span: 'page'; sem isso, o nome do autor não é pintado.

#5 · Cabeços conforme o papel da página

script.js · linhas 81–97no código 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' tira os cabeços da folha de rosto e da abertura, e parity põe o título do livro nas páginas pares e o do capítulo nas ímpares, com os fólios na margem externa. A abertura recebe um fólio no pé, de um elemento do rodapé com pages: 'opener'. Fólios e cabeços têm todos 8 pt e ficam 8,2 mm abaixo da borda superior, de modo que os algarismos do fólio se apoiam na linha de base dos cabeços.

#6 · A abertura do capítulo

script.js · linhas 101–112no código 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) };

O {number} do design imprime o número do capítulo na forma que numberingTemplate: '{1:I}' lhe dá, um I romano. minHeight reserva pelo menos oito linhas, por isso o texto começa na nona enquanto o título ocupar uma ou duas, e mais abaixo quando um título mais longo precisar de mais espaço. breakBefore com parity: 'any' deixa o capítulo abrir na página 2, de frente para a segunda página dele; o padrão o levaria para a página 3, ímpar.

A receita 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,

O script.js montado funciona como está: cole-o como script de módulo em qualquer página ou abra a receita no CodePen. Pasta da receita no GitHub ↗ (abre em uma nova aba)

Erros comuns

Erro comum

O worker de layout mede com as próprias fontes

Um worker tem o próprio FontFaceSet, então não enxerga as fontes que a página carregou. Envie a ele os bytes de cada fonte com registerFonts() antes da primeira composição; o peso pode ser um texto ('400') ou, desde o postext 1.5, um número. Sem eles, o worker mede com uma fonte substituta, e as quebras de linha e o número de páginas mudam; desde a 1.5 o console avisa, uma vez para cada família ausente. Layout em um Web Worker →

Créditos

Texto
Imagens
  • 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
Fontes
Baskervville (SIL OFL 1.1) · Baskervville SC (SIL OFL 1.1) · Cinzel (SIL OFL 1.1)
Sandbox