简单来说
《时间机器》袖珍本的实时编辑器。每打一个字,页面都在后台重新排版,屏幕不会因此卡住。
成品一览
你把H. G. Wells的The Time Machine第I章排成110 × 147 mm的口袋版,Markdown就在旁边。书名页上,用代码绘制的牛血红色块里是一张由扩散模型生成的照片,拍的是一个带四个小表盘的黄铜表盘,下方是Cinzel书名。本章正文从第九行开始,上方是罗马数字和一条黄铜线,用9.5/13 pt的Baskervville排,书眉用小型大写字母。每次按键,整章都在一个Web Worker里重新排一遍,右边的Canvas翻到光标所在的那一页。编辑器下方有一根指针,主线程每一帧都转动它,主线程忙时它就停下;状态行给出构建耗时、最长的一帧,以及有多少次构建被更新的按键取消。右上角的菜单可以把构建移到主线程上,以便比较。
这道食谱解答
- 长书排版时,怎样让页面保持响应(Web Worker、取消)?
- 为什么断行会变,或者PDF中的字互相重叠?怎样正确加载字体?
- 能在服务器上或命令行(Node)中生成页面或PDF吗?
简短回答
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;
}
};
}
用料
- 功能
- 在Web Worker中排版排版前加载字体在Canvas上绘制页面成品尺寸对称页边距正文字体从右页开始的章设计过的章首页编号标题标题样式不编号的章分节书眉书眉与页码按页面角色显示书眉页面设计中的图片作为资源的图和表段落样式纸张颜色显式竖向间距
- 还用到
- 标题属性
- 类型
- Baskervville, Baskervville SC, Cinzel(SIL OFL 1.1)
- 素材
dial-1120.jpg- The title page’s brass dial, a photograph (Generated With Diffusion Models, 原创)
- The title page’s oxblood cloth and gilt frame, drawn in code in the page’s palette (Ignacio Ferro, MIT)
做法
#1 · 一次调用启动工作线程
这一步的代码见上文的简短回答。createLayoutWorker()不带选项。模块来自esm.sh时,worker文件位于esm.sh的源上,Worker构造函数不会接受它,所以引擎通过一个与页面同源的blob启动自己的worker入口,版本与页面导入的相同。在打包的应用里,同一个调用启动模块旁边的那个worker文件。句柄的build()接收与buildDocument()相同的内容和配置,返回的也是同一种文档(在Web Worker中运行排版)。
#2 · 每种字体加载两次
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}` };
}));
工作线程有自己的FontFaceSet,看不到页面已经加载的字体,所以简短回答去取同样的Fontsource文件,把它们的字节传给registerFonts(),每个字重写成字符串('400')。省掉这一步,工作线程会用后备字体测量:本章会排成175行而不是190行,第一行结束在“him)”而不是“of”,页面的控制台会把每个缺失的字体族报告一次。字体文件下载失败则更难发现。如果工作线程拿到的是一个404页面而不是Baskervville正体,registerFonts()照样完成,本章排成186行,警告只出现在工作线程的控制台里。所以简短回答在发送任何字节之前先检查每个响应的状态,并抛出带字体名和HTTP状态的错误。页面也用loadFonts()加载同样的字体,因为Canvas用页面的字体绘制。
#3 · 每次按键都构建,在主线程上绘制
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()在请求下一次构建之前,先中止正在进行的构建。被中止构建的promise会立即以AbortError拒绝,typeset()把它转成null。在工作线程里,仍在队列中等待的构建会被立即丢弃,正在运行的构建则在当前这一轮放置结束时停止,因为构建只在两轮之间检查是否取消。refresh()给各次构建编号,只绘制最新的一次,所以迟到的工作线程构建不会覆盖主线程构建的结果。文档回到主线程,由renderPageToCanvas()用在主线程注册的图片绘制。工作线程只需要每张图片的尺寸,由资源条目提供(1100 × 840)。每个块都保留自己在Markdown中的偏移量(sourceStart),follow()显示最后一个起始位置不晚于光标的块所在的页面。
#4 · 用标题样式做书名页
// # 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 Time Machine {style="title"}这一行用title标题样式排第1页,这个样式的header和footer都为空,所以这一页没有书眉和页码。numbered: false把书名排除在章节计数之外,所以Introduction仍是第I章。插图锚定在出血的左上角,作者名排在栏底下方。留在栏内的设计会在栏底被裁掉,所以样式设了span: 'page';不设它,作者名就不会绘制出来。
#5 · 按页面角色放书眉
// 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'让书眉不出现在书名页和章首页上,parity在左页排书名、在右页排章名,页码位于外侧边缘。章首页改用页脚页码,来自一个设了pages: 'opener'的页脚元素。页码和书眉都是8 pt,悬挂在距上边缘8.2 mm处,所以页码数字与书眉位于同一条基线上。
#6 · 章首页
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) };
设计中的{number}按numberingTemplate: '{1:I}'给出的形式印出章序号,即罗马数字I。minHeight至少预留八行,所以标题占一两行时,正文从第九行开始;标题较长、需要更多空间时,正文再往下移。breakBefore设了parity: 'any',让本章从第2页开始,与它的第二页相对;按默认值,它会被排到第3页(右页)。
完整食谱
// ═══ 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; }
组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)
常见问题
易错点
排版工作线程用它自己的字体测量
工作线程有自己的FontFaceSet,所以页面已加载的字型对它不可见。第一次构建前,用registerFonts()把每个字型的字节发给它;字重可以写成字符串('400'),从postext 1.5起也可以写成数字。没有这些字节,工作线程会用后备字体测量,断行和页数都会改变;从1.5起,控制台会就此给出提示,每个缺失的字族一次。 在Web Worker中排版 →
致谢
- 文本
- The Time Machine, chapter I · H. G. Wells · 公有领域
- 图片
- The title page’s brass dial, a photograph · Generated With Diffusion Models · 原创
- The title page’s oxblood cloth and gilt frame, drawn in code in the page’s palette · Ignacio Ferro · MIT
- 字体
- Baskervville (SIL OFL 1.1) · Baskervville SC (SIL OFL 1.1) · Cinzel (SIL OFL 1.1)


