# 从右往左读、竖排嵌字的漫画

> 两页按从右往左阅读绘制的漫画：artDirection rtl让每个版本都保留原来的分格顺序，日文对话框按竖列排。

- HTML版本: https://postext.dev/zh/cookbook/manga-right-to-left
- 食谱 No. 149 · 漫画与连环画 · 难度 2 (中级) · 输出: Canvas, PDF
- 体裁: 漫画
- 需要 postext ≥ 1.21.0, postext-pdf ≥ 1.21.0 · 已用 1.21.0, postext-pdf 1.21.0 测试，日期 2026-10-07
- 页面: [1](https://postext.dev/cookbook/manga-right-to-left/zh/p01.webp?v=e7b562d1), [2](https://postext.dev/cookbook/manga-right-to-left/zh/p02.webp?v=e7b562d1), [1](https://postext.dev/cookbook/manga-right-to-left/zh/p03.webp?v=e7b562d1), [2](https://postext.dev/cookbook/manga-right-to-left/zh/p04.webp?v=e7b562d1)
- PDF: https://postext.dev/cookbook/manga-right-to-left/zh/manga-right-to-left.pdf?v=e7b562d1
- 在沙盒中打开: https://postext.dev/zh/sandbox#recipe=manga-right-to-left&lang=zh (.postext: https://postext.dev/cookbook/manga-right-to-left/zh/manga-right-to-left.postext)
- 最后更新: 2026-10-07
- 其他语言: [en](https://postext.dev/en/cookbook/manga-right-to-left.md), [es](https://postext.dev/es/cookbook/manga-right-to-left.md), [ca](https://postext.dev/ca/cookbook/manga-right-to-left.md), [pt](https://postext.dev/pt/cookbook/manga-right-to-left.md), [ja](https://postext.dev/ja/cookbook/manga-right-to-left.md), [ar](https://postext.dev/ar/cookbook/manga-right-to-left.md)

## 简单来说

一部日本漫画的两页。日文版在窄窄的竖列里从上往下写字；其他语言的版本也保留日文版的分格顺序，从右上角那一格读起。

## 成品一览

这是为本示例编写、用黑白绘制的剑道漫画《前の晩》（前一晚）的开头两页：县大赛前一天，花独自练习挥剑，空给她送来神社的护身符，森老师把两人打发回家。先放日文原版，按周刊漫画的方式嵌字：古董体（假名是明朝体，汉字是黑体），对话框窄而高，句末不加句号。对页是同样两页的本页语言版本（日文页上是英文版），同样从右上角那一格读起，正如本世纪初以来的正版译本。开本是B6，128 × 182 mm，日本单行本的尺寸。

**这份食谱回答的问题:**

- 怎样排一部从右往左读的漫画，让对话框里的日文竖排？
- 怎样在对话框里竖排日文？

## 简短回答

```js
// script.js, 行 44–60
const comics = (lang) => ({
  // The pages were drawn for right-to-left reading: panel 1 sits top right. The
  // reading direction stays 'auto', which follows the art in a left-to-right
  // language too: the English page keeps the Japanese panel order.
  artDirection: 'rtl',
  mirrorArt: false, // never flop the art: Hana's grip on the sword, the kimono's fold
  gutter: { horizontal: mm(4.5), vertical: mm(2) }, // a tier gap twice the panel gap
  panel: { borderWidth: pt(0.9), borderColor: col('ink'), background: col('paper') },
  lettering: {
    fontFamily: EDITIONS[lang].faces[0], color: col('ink'),
    fontSize: pt(['ja', 'zh'].includes(lang) ? 8.5 : 7.5), // one size per edition
    // 'auto' sets Japanese in columns of 8 characters at most and drops the final 。.
    // Chinese goes in columns too: a book bound on the right never mixes the two.
    writingMode: lang === 'zh' ? 'vertical' : 'auto',
  },
  balloonStyles: balloons(),
});
```

## 用料

**讲解**

- [阅读方向与日本漫画的顺序](https://postext.dev/zh/docs/comics.md#阅读方向): 各格按阅读顺序填入格子：从左到右；日本漫画和从右往左书写的语言则从右到左；comics.artDirection和mirrorArt决定何时把画面左右翻转以与之相配。
- [漫画嵌字](https://postext.dev/zh/docs/comics.md#嵌字): 格下面的每一行就是一个对话框，写作“说话人: 文字”。先排文字，全书只用一个嵌字字号，再围绕文字画出对话框。字体随语言而定：Comic Neue，日语用Zen Antique。

**还用到**

- [多语言重新嵌字](https://postext.dev/zh/docs/comics.md#嵌字)
- [竖排](https://postext.dev/zh/docs/configuration.md#竖排)
- [中日韩字体](https://postext.dev/zh/docs/configuration.md#中文日文和韩文字体)
- [右翻书](https://postext.dev/zh/docs/configuration.md#装订)
- [分格](https://postext.dev/zh/docs/comics.md#分割页面)
- [格内画面与裁切](https://postext.dev/zh/docs/comics.md#分格与画面)
- [说话人与锚点](https://postext.dev/zh/docs/comics.md#说话人与锚点)
- [漫画页](https://postext.dev/zh/docs/comics.md#漫画页)
- [对话框样式](https://postext.dev/zh/docs/comics.md#对话框样式)
- [拟声字](https://postext.dev/zh/docs/comics.md#对话框样式)
- [语义调色板](https://postext.dev/zh/docs/configuration.md#调色板)
- [在Canvas上绘制页面](https://postext.dev/zh/docs/configuration.md#把页面渲染为位图)
- [导出PDF](https://postext.dev/zh/docs/configuration.md#生成pdf)
- [中文断行](https://postext.dev/zh/docs/configuration.md#东亚排版)
- [格框与格间距](https://postext.dev/zh/docs/comics.md#分格与画面)
- [振假名：汉字上的假名注音](https://postext.dev/zh/docs/japanese-layout.md#振假名)
- [纸张颜色](https://postext.dev/zh/docs/configuration.md#页面)
- [嵌入PDF的字体](https://postext.dev/zh/docs/configuration.md#为什么需要字体提供函数)
- [作为资源的图和表](https://postext.dev/zh/docs/document-format.md#资源)
- [注音：拼音与注音符号](https://postext.dev/zh/docs/document-format.md#中文标记注音和双行夹注)
- [竖排中的横排数字](https://postext.dev/zh/docs/configuration.md#竖排中的数字)

**配置一览**

- [`bodyText`](https://postext.dev/zh/docs/configuration.md#正文), [`colorPalette`](https://postext.dev/zh/docs/configuration.md#调色板), [`comics`](https://postext.dev/zh/docs/comics.md#漫画页), [`footer`](https://postext.dev/zh/docs/configuration.md#页眉与页脚), [`header`](https://postext.dev/zh/docs/configuration.md#页眉与页脚), [`headings`](https://postext.dev/zh/docs/configuration.md#标题), [`locale`](https://postext.dev/zh/docs/configuration.md#断词), [`page`](https://postext.dev/zh/docs/configuration.md#页面)

**API**

- [`buildDocument`](https://postext.dev/zh/docs/configuration.md#构建文档), [`clearMeasurementCache`](https://postext.dev/zh/docs/configuration.md#测量缓存), [`decompressWoff2`](https://postext.dev/zh/docs/configuration.md#浏览器字体提供函数fontsource--woff2), `loadVerticalAlternates`, [`registerResourceImage`](https://postext.dev/zh/docs/architecture.md#api接口), [`renderPageToCanvas`](https://postext.dev/zh/docs/configuration.md#把页面渲染为位图), [`renderToPdf`](https://postext.dev/zh/docs/configuration.md#生成pdf)

**字体**

- Zen Antique (OFL-1.1), Dela Gothic One (OFL-1.1), Comic Neue (OFL-1.1), Bangers (OFL-1.1), Noto Sans SC (OFL-1.1), ZCOOL KuaiLe (OFL-1.1), Playpen Sans Arabic (OFL-1.1), Lalezar (OFL-1.1)

## 做法

### 1 · 按绘制的方向阅读

代码见上方的[简短回答](https://postext.dev/zh/cookbook/manga-right-to-left.md#简短回答)。漫画家从右上角开始安排每一页：第一格、第一个开口的人物、视线扫过每一层的路线，都从那里出发。`artDirection: 'rtl'`把这一点告诉引擎，阅读方向保持`'auto'`时，每个版本都跟随画面；阿拉伯文版本来就从右往左读。画面从不镜像。西方出版社直到2002年前后还把漫画左右翻转出版，读者看到每个剑士都变成左撇子，和服的衣襟也反了过来：保留原样只要读者改一个习惯，翻转却要牺牲画面。每个`:::page`带着自己的分格`30 / 34 [46 | *] / * [44 | *]`，每一层的第一格排在右边（[阅读方向](https://postext.dev/zh/docs/comics.md#阅读方向)）。

### 2 · 在画面上标一次人物位置

```js
// script.js, 行 235–355
const ART = { // fractions of the picture: the same in every language
  dojo: {
    alt: t({ en: 'The old wooden kendo dojo at dusk, its doors open and lit.',
      es: 'El viejo dojo de madera al anochecer, con las puertas abiertas e iluminadas.',
      ca: 'L’antic dojo de fusta al capvespre, amb les portes obertes i il·luminades.',
      pt: 'O velho dojô de madeira ao anoitecer, com as portas abertas e iluminadas.',
      zh: '黄昏时分的老木造剑道场，门敞开着，里面亮着灯。',
      ar: 'قاعة الكندو الخشبية القديمة عند الغسق، أبوابها مفتوحة ومضاءة.',
      ja: '夕暮れの古い木造の剣道場。戸が開いて、中に明かりがともっている。' }),
  safeArea: { x: 0.45, y: 0.32, width: 0.5, height: 0.51 },
  anchors: [{ id: 'dojo', x: 0.66, y: 0.63 }] },
  swing: {
    alt: t({ en: 'Hana, alone in the dojo, swings her bamboo sword overhead.',
      es: 'Hana, sola en el dojo, alza la espada de bambú sobre la cabeza.',
      ca: 'La Hana, sola al dojo, aixeca l’espasa de bambú per sobre del cap.',
      pt: 'Hana, sozinha no dojô, ergue a espada de bambu acima da cabeça.',
      zh: '花独自在道场里，把竹剑高举过头。',
      ar: 'هانا وحدها في القاعة ترفع سيف الخيزران فوق رأسها.',
      ja: 'ひとり道場で、竹刀を頭上に振りかぶる花。' }),
  safeArea: { x: 0.36, y: 0, width: 0.31, height: 0.5 },
  avoid: [{ x: 0.43, y: 0, width: 0.17, height: 0.12 }],
  anchors: [{ id: 'hana', x: 0.535, y: 0.28, head: { x: 0.53, y: 0.22 },
    face: { x: 0.49, y: 0.14, width: 0.11, height: 0.17 } }] },
  doorway: {
    alt: t({ en: 'Sora peeks round the sliding door, holding a shrine charm.',
      es: 'Sora se asoma por la puerta corredera con un amuleto en la mano.',
      ca: 'En Sora treu el cap per la porta corredissa amb un amulet a la mà.',
      pt: 'Sora espia pela porta de correr com um amuleto na mão.',
      zh: '空从拉门后探出头，手里攥着护身符。',
      ar: 'سورا يطلّ من وراء الباب المنزلق وفي يده تميمة.',
      ja: 'お守りを手に、引き戸の陰からのぞく空。' }),
  safeArea: { x: 0.37, y: 0.09, width: 0.34, height: 0.5 },
  avoid: [{ x: 0.49, y: 0.41, width: 0.08, height: 0.1 }],
  anchors: [{ id: 'sora', x: 0.545, y: 0.31, head: { x: 0.55, y: 0.22 },
    face: { x: 0.47, y: 0.16, width: 0.2, height: 0.18 } }] },
  closeup: {
    alt: t({ en: "Close-up of Hana's sweating, startled face.",
      es: 'Primer plano del rostro sudoroso y sobresaltado de Hana.',
      ca: 'Primer pla de la cara suada i sobresaltada de la Hana.',
      pt: 'Primeiro plano do rosto suado e assustado de Hana.',
      zh: '花满脸是汗、吃了一惊的特写。',
      ar: 'لقطة قريبة لوجه هانا المتعرّق المذعور.',
      ja: '汗をかき、はっとした花の顔のアップ。' }),
  safeArea: { x: 0.27, y: 0.28, width: 0.43, height: 0.51 },
  anchors: [{ id: 'hana', x: 0.475, y: 0.665, head: { x: 0.45, y: 0.35 },
    face: { x: 0.3, y: 0.3, width: 0.4, height: 0.45 } }] },
  charm: {
    alt: t({ en: 'Sora holds out the charm; Hana looks at it, sword on her shoulder.',
      es: 'Sora le tiende el amuleto; Hana lo mira con la espada al hombro.',
      ca: 'En Sora li allarga l’amulet; la Hana el mira amb l’espasa a l’espatlla.',
      pt: 'Sora estende o amuleto; Hana olha para ele com a espada no ombro.',
      zh: '空递出护身符，花扛着竹剑看着它。',
      ar: 'سورا يمدّ التميمة، وهانا تنظر إليها والسيف على كتفها.',
      ja: '空がお守りを差し出し、竹刀を肩にかついだ花がそれを見る。' }),
  safeArea: { x: 0.21, y: 0.09, width: 0.56, height: 0.53 },
  avoid: [{ x: 0.43, y: 0.47, width: 0.06, height: 0.09 }],
  anchors: [{ id: 'sora', x: 0.325, y: 0.335, head: { x: 0.29, y: 0.22 },
    face: { x: 0.26, y: 0.17, width: 0.11, height: 0.2 } },
  { id: 'hana', x: 0.675, y: 0.335, head: { x: 0.665, y: 0.22 },
    face: { x: 0.62, y: 0.17, width: 0.11, height: 0.2 } }] },
  coach: {
    alt: t({ en: 'Coach Mori in the doorway, backlit, arms crossed.',
      es: 'El entrenador Mori en la puerta, a contraluz, de brazos cruzados.',
      ca: 'L’entrenador Mori a la porta, a contrallum, de braços plegats.',
      pt: 'O treinador Mori na porta, contra a luz, de braços cruzados.',
      zh: '森老师站在门口，背着光，双臂抱在胸前。',
      ar: 'المدرّب موري عند الباب، والضوء خلفه، عاقدًا ذراعيه.',
      ja: '逆光の戸口で腕を組んで立つ森先生。' }),
  safeArea: { x: 0.33, y: 0.13, width: 0.3, height: 0.32 },
  anchors: [{ id: 'mori', x: 0.425, y: 0.215, head: { x: 0.42, y: 0.17 },
    face: { x: 0.37, y: 0.13, width: 0.1, height: 0.11 } }] },
  smile: {
    alt: t({ en: "Close-up of Mori's stern face breaking into a small smile.",
      es: 'Primer plano del rostro severo de Mori, que esboza una sonrisa.',
      ca: 'Primer pla de la cara severa d’en Mori, que esbossa un somriure.',
      pt: 'Primeiro plano do rosto severo de Mori, que esboça um sorriso.',
      zh: '森老师严肃的脸上露出一丝笑意的特写。',
      ar: 'لقطة قريبة لوجه موري الصارم وقد ارتسمت عليه ابتسامة.',
      ja: '厳しい顔がふっとゆるむ森先生のアップ。' }),
  safeArea: { x: 0.43, y: 0.21, width: 0.51, height: 0.53 },
  anchors: [{ id: 'mori', x: 0.69, y: 0.52, head: { x: 0.6, y: 0.25 },
    face: { x: 0.45, y: 0.28, width: 0.45, height: 0.32 } }] },
  kneel: {
    alt: t({ en: 'Kneeling, Hana ties the charm to her armour; Sora scratches his head.',
      es: 'De rodillas, Hana se ata el amuleto a la armadura; Sora se rasca la cabeza.',
      ca: 'De genolls, la Hana es lliga l’amulet a l’armadura; en Sora es grata el cap.',
      pt: 'De joelhos, Hana amarra o amuleto na armadura; Sora coça a cabeça.',
      zh: '花跪坐着把护身符系在护具上，空挠着头。',
      ar: 'هانا جاثية تربط التميمة بدرعها، وسورا يحكّ رأسه.',
      ja: '正座してお守りを防具に結ぶ花と、頭をかく空。' }),
  safeArea: { x: 0.21, y: 0.08, width: 0.61, height: 0.48 },
  avoid: [{ x: 0.27, y: 0.43, width: 0.06, height: 0.12 }],
  anchors: [{ id: 'hana', x: 0.305, y: 0.245, head: { x: 0.3, y: 0.17 },
    face: { x: 0.25, y: 0.1, width: 0.11, height: 0.17 } },
  { id: 'sora', x: 0.7, y: 0.25, head: { x: 0.71, y: 0.15 },
    face: { x: 0.64, y: 0.1, width: 0.13, height: 0.18 } }] },
  roof: {
    alt: t({ en: 'Seen from behind, Hana and Sora sit on the school roof at sunset.',
      es: 'De espaldas, Hana y Sora sentados en la azotea del instituto al atardecer.',
      ca: 'D’esquena, la Hana i en Sora asseguts al terrat de l’institut a la posta.',
      pt: 'De costas, Hana e Sora sentados no terraço da escola ao pôr do sol.',
      zh: '夕阳下，花和空坐在学校楼顶的背影。',
      ar: 'هانا وسورا جالسان على سطح المدرسة عند الغروب، من الخلف.',
      ja: '夕焼けの屋上に並んで座る花と空の後ろ姿。' }),
  safeArea: { x: 0.24, y: 0.41, width: 0.47, height: 0.31 },
  anchors: [{ id: 'hana', x: 0.36, y: 0.52, head: { x: 0.36, y: 0.48 },
    face: { x: 0.31, y: 0.43, width: 0.11, height: 0.14 } },
  { id: 'sora', x: 0.63, y: 0.52, head: { x: 0.625, y: 0.47 },
    face: { x: 0.58, y: 0.41, width: 0.1, height: 0.15 } }] },
};
const panels = () => Promise.all([
  comicPanel('dojo', asset('kendo-dojo.jpg'), ART.dojo),
  comicPanel('swing', asset('kendo-swing.jpg'), ART.swing),
  comicPanel('doorway', asset('kendo-doorway.jpg'), ART.doorway),
  comicPanel('closeup', asset('kendo-closeup.jpg'), ART.closeup),
  comicPanel('charm', asset('kendo-charm.jpg'), ART.charm),
  comicPanel('coach', asset('kendo-coach.jpg'), ART.coach),
  comicPanel('smile', asset('kendo-smile.jpg'), ART.smile),
  comicPanel('kneel', asset('kendo-kneel.jpg'), ART.kneel),
  comicPanel('roof', asset('kendo-roof.jpg'), ART.roof),
]);
```

文字随语言而变，画面不变。每幅画都有一块任何裁切都会保留的安全区；每个人物标出嘴（对话框尾巴的指向）、头部（思考泡用）和不能被对话框遮住的脸，全部用画面的比例表示。脚本每一行写明说话人（`sora: …`），引擎在任何语言里都把对话框放在那个人物旁边。说话人不在画面里时，比如森老师出现在门口那一格里的空，尾巴就指向格子的边缘：`sora{tail=bottom}`。

### 3 · 对话框的内容交给各个语言

```js
// script.js, 行 64–71
const balloons = () => [
  { id: 'speech', fill: col('paper'), stroke: col('ink'), strokeWidth: pt(0.6), roundness: 2 },
  { id: 'whisper', fill: col('paper'), stroke: col('ink'), roundness: 2 },
  { id: 'thought', fill: col('paper'), stroke: col('ink') },
  { id: 'inner', fill: col('tone'), stroke: col('tone'), strokeWidth: pt(0), italic: false },
  { id: 'caption', fill: col('paper'), stroke: col('ink'), strokeWidth: pt(0.5) },
  { id: 'sfx', color: col('ink'), haloColor: col('paper') },
];
```

样式决定的是声音的种类：普通对白用椭圆，耳语用虚线，心里话用云朵，花的内心独白用灰色方框。框里的字怎么排，由各个版本决定。日文中，引擎按每列最多八个字竖排，去掉对话框末尾的「。」而保留「、」，把第42回的两位数字纵中横排进一个字的位置（`:tcy[42]`），并把`!?`并排放进一格。脚本在名字第一次出现时标上读音（`{一ノ瀬|いちのせ}`），就像漫画给人名注假名。英文中，同样的对话框变成横排的椭圆，顺序仍从右边开始。

### 4 · 用各版本自己的文字载入字体

```js
// script.js, 行 359–371
const SFX = /^sfx[^:：\n]*[:：](.*)$/gm; // sound-effect lines: the second face sets them
async function loadEdition(lang) {
  const text = TEXT[lang];
  const [face, sfx] = EDITIONS[lang].faces;
  const faces = { [face]: FONTS[face], [sfx]: FONTS[sfx] };
  if (['ja', 'zh'].includes(lang)) { // CJK: only the files that hold these characters
    const effects = [...text.matchAll(SFX)].map((m) => m[1]).join('');
    await loadCjkFonts({ [face]: FONTS[face] }, text.replace(SFX, ''), { vertical: true });
    await loadCjkFonts({ [sfx]: FONTS[sfx] }, effects, { vertical: true });
  }
  if (lang === 'ar') await loadArabicFonts(faces, text);
  await loadComicFonts(faces, text); // the bold and italic the faces do not ship
}
```

Zen Antique和Dela Gothic One按字符范围各拆成约一百个文件。每种字体只用它要排的文字来载入（前者排对话框，后者排拟声字），页面只下载需要的文件。`loadComicFonts`根据这些字体实际提供的文件声明喊叫用的粗体和内心独白用的斜体，屏幕和PDF画出的是同样的字形。

### 5 · 把原版放在每个版本旁边

```js
// script.js, 行 376–385
const FACING = LANG === 'ja' ? 'en' : LANG; // Japanese readers see the English edition
const TEXT = { ja: original, [FACING]: LANG === 'ja' ? english : markdown };
await loadFonts(FONTS, Object.values(TEXT).join('\n'));
const resources = await panels();
const build = async (lang) => { // the same pictures and page; this language's lettering
  await loadEdition(lang);
  return buildWithFonts(() => buildDocument({ markdown: TEXT[lang], resources,
    continuation: { pageIndexOffset: 1 } }, edition(lang)), TEXT[lang]);
};
const docs = [await build('ja'), await build(FACING)];
```

本站的每种语言都有这两页的独立版本，写在各自的`content.<lang>.md`里，每个版本都和日文原版相对：`/* @content@ja */`把`content.ja.md`放进每个版本，日文页则让原版对着英文嵌字。中文版同样竖排，因为从右边翻开的书不混用竖排和横排对话框；阿拉伯文版则按它本身的方向从右往左读。

## 完整食谱

一个文件，由食谱文件夹合成，示例文本和排版食谱的公共工具包都已内联；它自己排出页面。要运行它，把它放进空白页面的`<script type="module">`，或粘贴到新建CodePen的JS面板里（设为模块）。它从esm.sh导入postext，不需要安装或构建。

- 食谱文件夹: https://github.com/drnachio/postext/tree/main/cookbook/manga-right-to-left

### script.js

```js
// ═══ Postext Cookbook · Nº 149 · Manga read right to left, lettered vertically ══════
// https://postext.dev/en/cookbook/manga-right-to-left
// Code: MIT · Story: written for the recipe (CC BY 4.0) · Pictures: generated with diffusion models
// Fonts: Zen Antique, Comic Neue and six more (SIL OFL 1.1) · Needs postext ≥ 1.21.0
// Two pages of a kendo manga: the Japanese original, then the same pages lettered again.
import {
  buildDocument, renderPageToCanvas, clearMeasurementCache, registerResourceImage,
  loadVerticalAlternates,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'zh'; // @lang: this edition's language; the Japanese original faces it
const RECIPE = 'manga-right-to-left';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: black ink on a warm white, one screen-tone grey
const palette = {
  ink: '#151413', // panel borders, balloon outlines, the lettering
  paper: '#fdfcf9', // the page and the balloons
  tone: '#e8e6e1', // the inner-voice box, a light screen tone
  muted: '#6f6b64',
  accent: '#a8322b', // the cover red (the Folio case in recipe.json)
};
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' } })),
  { id: 'main-color', name: 'ink (defaults)', value: { hex: palette.ink, model: 'hex' } },
];
// #endregion

// The engine's lettering and sound-effect faces per language (defaultComicFont and
// defaultComicSfxFont), written out so FONTS and the PDF know them.
const EDITIONS = {
  ja: { locale: 'ja', faces: ['Zen Antique', 'Dela Gothic One'] },
  en: { locale: 'en-us', faces: ['Comic Neue', 'Bangers'] },
  es: { locale: 'es', faces: ['Comic Neue', 'Bangers'] },
  ca: { locale: 'ca', faces: ['Comic Neue', 'Bangers'] },
  pt: { locale: 'pt-BR', faces: ['Comic Neue', 'Bangers'] },
  zh: { locale: 'zh-Hans', faces: ['Noto Sans SC', 'ZCOOL KuaiLe'] },
  ar: { locale: 'ar', faces: ['Playpen Sans Arabic', 'Lalezar'] },
};

// #region answer: the art reads right to left, so every edition does
const comics = (lang) => ({
  // The pages were drawn for right-to-left reading: panel 1 sits top right. The
  // reading direction stays 'auto', which follows the art in a left-to-right
  // language too: the English page keeps the Japanese panel order.
  artDirection: 'rtl',
  mirrorArt: false, // never flop the art: Hana's grip on the sword, the kimono's fold
  gutter: { horizontal: mm(4.5), vertical: mm(2) }, // a tier gap twice the panel gap
  panel: { borderWidth: pt(0.9), borderColor: col('ink'), background: col('paper') },
  lettering: {
    fontFamily: EDITIONS[lang].faces[0], color: col('ink'),
    fontSize: pt(['ja', 'zh'].includes(lang) ? 8.5 : 7.5), // one size per edition
    // 'auto' sets Japanese in columns of 8 characters at most and drops the final 。.
    // Chinese goes in columns too: a book bound on the right never mixes the two.
    writingMode: lang === 'zh' ? 'vertical' : 'auto',
  },
  balloonStyles: balloons(),
});
// #endregion

// #region balloons: oval speech, a dashed whisper, a grey box for the inner voice
const balloons = () => [
  { id: 'speech', fill: col('paper'), stroke: col('ink'), strokeWidth: pt(0.6), roundness: 2 },
  { id: 'whisper', fill: col('paper'), stroke: col('ink'), roundness: 2 },
  { id: 'thought', fill: col('paper'), stroke: col('ink') },
  { id: 'inner', fill: col('tone'), stroke: col('tone'), strokeWidth: pt(0), italic: false },
  { id: 'caption', fill: col('paper'), stroke: col('ink'), strokeWidth: pt(0.5) },
  { id: 'sfx', color: col('ink'), haloColor: col('paper') },
];
// #endregion

const config = () => ({ // a factory: the engine caches resolved configs per object
  // Each edition's language, written out (gotcha: ja-locale-tag); the original is built
  // with 'ja' in every edition (edition('ja') below).
  locale: t({ ja: 'ja', en: 'en-us', es: 'es', ca: 'ca', zh: 'zh-Hans', ar: 'ar', pt: 'pt-BR' }),
  colorPalette,
  page: {
    sizePreset: 'custom', width: mm(128), height: mm(182), dpi: 150, // B6, a tankōbon
    binding: 'right', backgroundColor: col('paper'), // manga open from the right, in any language
    margins: { top: mm(13), bottom: mm(15), left: mm(11), right: mm(11), mirror: true },
  },
  bodyText: {
    fontFamily: 'Zen Antique', fontSize: pt(9), lineHeight: pt(15), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  },
  headings: { fontFamily: 'Zen Antique', color: col('ink'),
    levels: [{ level: 1, breakBefore: { enabled: true, parity: 'any' } }] }, // the H1 break
  header: { elements: [] }, // comic pages are all panels: no running heads, no folios
  footer: { elements: [] },
  comics: comics(LANG),
});
// Another edition changes the language, and with it the faces, the writing mode and the
// house rules of the lettering. Nothing else: not the page, not the panels.
const edition = (lang) => ({ ...config(), locale: EDITIONS[lang].locale, comics: comics(lang) });

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "前一晚"
author: "Postext Cookbook"
---

:::page{split="30 / 34 [46 | *] / * [44 | *]"}
::panel{art=dojo}
caption: 第:tcy[42]届县大赛前一天。
dojo: ……呀啊！
::panel{art=swing}
sfx: 呼
hana{inner}: 还有:tcy[50]下……！
::panel{art=doorway}
sora{whisper}: 哇，一之濑同学还在练……
sora{thought}: 真不好意思打扰她
::panel{art=closeup}
hana: ……谁!?
::panel{art=charm}
hana: ……相泽？
sora: 对、对不起！这是我奶奶那边神社的护身符
sora: 明天带上吧
:::

:::page{split="38 [44 | *] / 34 / *"}
::panel{art=coach}
sfx: 哗啦
mori: 喂。
mori: 放学时间早就过了。
sora{tail=bottom}: 森、森老师……
::panel{art=smile}
mori: 比赛前一晚，休息也是练习。
mori: ……明天，我很期待。
hana{tail=bottom}: 是！
::panel{art=kneel}
sora{thought}: 居然没挨骂……
hana: 谢谢你，相泽。我会戴着的
::panel{art=roof}
hana: ……其实，我有点害怕
sora: 我也是。明明我又不上场
hana: 噗，你在说什么呀
:::
`; // content.<lang>.md: this edition's lettering
const original = String.raw`---
title: "前の晩"
author: "Postext Cookbook"
---

:::page{split="30 / 34 [46 | *] / * [44 | *]"}
::panel{art=dojo}
caption: 第:tcy[42]回県大会の前日。
dojo: ……ヤアッ！
::panel{art=swing}
sfx: ブンッ
hana{inner}: あと:tcy[50]本……！
::panel{art=doorway}
sora{whisper}: うわ、{一ノ瀬|いちのせ}さん、まだやってる……
sora{thought}: 声、かけづらいなあ
::panel{art=closeup}
hana: ……誰!?
::panel{art=charm}
hana: ……{相沢|あいざわ}くん？
sora: ご、ごめん！　これ、うちのばあちゃんの神社のお守り
sora: 明日、持ってって
:::

:::page{split="38 [44 | *] / 34 / *"}
::panel{art=coach}
sfx: ガラッ
mori: こら。
mori: 下校時刻、とっくに過ぎてるぞ。
sora{tail=bottom}: も、森先生……
::panel{art=smile}
mori: 試合の前の晩は、休むのも稽古だ。
mori: ……明日、期待してるぞ。
hana{tail=bottom}: はい！
::panel{art=kneel}
sora{thought}: 怒られなかった……
hana: ありがとう、相沢くん。つけていくね
::panel{art=roof}
hana: ……ほんとはね、ちょっと怖いんだ
sora: 僕も。試合に出ないのに
hana: ふふっ、なにそれ
:::
`; // content.ja.md, the original, in every edition
const english = String.raw`---
title: "The Night Before"
author: "Postext Cookbook"
---

:::page{split="30 / 34 [46 | *] / * [44 | *]"}
::panel{art=dojo}
caption: The day before the 42nd Prefectural Tournament.
dojo: …Yaaah!
::panel{art=swing}
sfx: FWOOSH
hana{inner}: Fifty more…!
::panel{art=doorway}
sora{whisper}: Wow, Ichinose's still at it…
sora{thought}: I can't just barge in.
::panel{art=closeup}
hana: …Who's there!?
::panel{art=charm}
hana: …Aizawa?
sora: S-sorry! It's a charm from my grandma's shrine.
sora: Take it tomorrow.
:::

:::page{split="38 [44 | *] / 34 / *"}
::panel{art=coach}
sfx: SLIDE
mori: Hey.
mori: School closed an hour ago.
sora{tail=bottom}: M-Mori-sensei…
::panel{art=smile}
mori: Rest is training too.
mori: …I'm expecting a lot tomorrow.
hana{tail=bottom}: Yes, sensei!
::panel{art=kneel}
sora{thought}: He didn't yell at us…
hana: Thanks, Aizawa. I'll wear it.
::panel{art=roof}
hana: …Honestly? I'm a little scared.
sora: Me too. And I'm not even competing.
hana: Heh. What's that got to do with it?
:::
`; // the Japanese edition faces the original with it
// The same panels and speaker ids in every file; only the words change.

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = {
  'Zen Antique': ['400'], 'Dela Gothic One': ['400'], 'Comic Neue': ['400', '700', '400i', '700i'],
  Bangers: ['400'], 'Noto Sans SC': ['400', '700'], 'ZCOOL KuaiLe': ['400'],
  'Playpen Sans Arabic': ['400', '700'], Lalezar: ['400'],
};

// #region art: nine panels, with each speaker's mouth, head and face marked once
const ART = { // fractions of the picture: the same in every language
  dojo: {
    alt: t({ en: 'The old wooden kendo dojo at dusk, its doors open and lit.',
      es: 'El viejo dojo de madera al anochecer, con las puertas abiertas e iluminadas.',
      ca: 'L’antic dojo de fusta al capvespre, amb les portes obertes i il·luminades.',
      pt: 'O velho dojô de madeira ao anoitecer, com as portas abertas e iluminadas.',
      zh: '黄昏时分的老木造剑道场，门敞开着，里面亮着灯。',
      ar: 'قاعة الكندو الخشبية القديمة عند الغسق، أبوابها مفتوحة ومضاءة.',
      ja: '夕暮れの古い木造の剣道場。戸が開いて、中に明かりがともっている。' }),
  safeArea: { x: 0.45, y: 0.32, width: 0.5, height: 0.51 },
  anchors: [{ id: 'dojo', x: 0.66, y: 0.63 }] },
  swing: {
    alt: t({ en: 'Hana, alone in the dojo, swings her bamboo sword overhead.',
      es: 'Hana, sola en el dojo, alza la espada de bambú sobre la cabeza.',
      ca: 'La Hana, sola al dojo, aixeca l’espasa de bambú per sobre del cap.',
      pt: 'Hana, sozinha no dojô, ergue a espada de bambu acima da cabeça.',
      zh: '花独自在道场里，把竹剑高举过头。',
      ar: 'هانا وحدها في القاعة ترفع سيف الخيزران فوق رأسها.',
      ja: 'ひとり道場で、竹刀を頭上に振りかぶる花。' }),
  safeArea: { x: 0.36, y: 0, width: 0.31, height: 0.5 },
  avoid: [{ x: 0.43, y: 0, width: 0.17, height: 0.12 }],
  anchors: [{ id: 'hana', x: 0.535, y: 0.28, head: { x: 0.53, y: 0.22 },
    face: { x: 0.49, y: 0.14, width: 0.11, height: 0.17 } }] },
  doorway: {
    alt: t({ en: 'Sora peeks round the sliding door, holding a shrine charm.',
      es: 'Sora se asoma por la puerta corredera con un amuleto en la mano.',
      ca: 'En Sora treu el cap per la porta corredissa amb un amulet a la mà.',
      pt: 'Sora espia pela porta de correr com um amuleto na mão.',
      zh: '空从拉门后探出头，手里攥着护身符。',
      ar: 'سورا يطلّ من وراء الباب المنزلق وفي يده تميمة.',
      ja: 'お守りを手に、引き戸の陰からのぞく空。' }),
  safeArea: { x: 0.37, y: 0.09, width: 0.34, height: 0.5 },
  avoid: [{ x: 0.49, y: 0.41, width: 0.08, height: 0.1 }],
  anchors: [{ id: 'sora', x: 0.545, y: 0.31, head: { x: 0.55, y: 0.22 },
    face: { x: 0.47, y: 0.16, width: 0.2, height: 0.18 } }] },
  closeup: {
    alt: t({ en: "Close-up of Hana's sweating, startled face.",
      es: 'Primer plano del rostro sudoroso y sobresaltado de Hana.',
      ca: 'Primer pla de la cara suada i sobresaltada de la Hana.',
      pt: 'Primeiro plano do rosto suado e assustado de Hana.',
      zh: '花满脸是汗、吃了一惊的特写。',
      ar: 'لقطة قريبة لوجه هانا المتعرّق المذعور.',
      ja: '汗をかき、はっとした花の顔のアップ。' }),
  safeArea: { x: 0.27, y: 0.28, width: 0.43, height: 0.51 },
  anchors: [{ id: 'hana', x: 0.475, y: 0.665, head: { x: 0.45, y: 0.35 },
    face: { x: 0.3, y: 0.3, width: 0.4, height: 0.45 } }] },
  charm: {
    alt: t({ en: 'Sora holds out the charm; Hana looks at it, sword on her shoulder.',
      es: 'Sora le tiende el amuleto; Hana lo mira con la espada al hombro.',
      ca: 'En Sora li allarga l’amulet; la Hana el mira amb l’espasa a l’espatlla.',
      pt: 'Sora estende o amuleto; Hana olha para ele com a espada no ombro.',
      zh: '空递出护身符，花扛着竹剑看着它。',
      ar: 'سورا يمدّ التميمة، وهانا تنظر إليها والسيف على كتفها.',
      ja: '空がお守りを差し出し、竹刀を肩にかついだ花がそれを見る。' }),
  safeArea: { x: 0.21, y: 0.09, width: 0.56, height: 0.53 },
  avoid: [{ x: 0.43, y: 0.47, width: 0.06, height: 0.09 }],
  anchors: [{ id: 'sora', x: 0.325, y: 0.335, head: { x: 0.29, y: 0.22 },
    face: { x: 0.26, y: 0.17, width: 0.11, height: 0.2 } },
  { id: 'hana', x: 0.675, y: 0.335, head: { x: 0.665, y: 0.22 },
    face: { x: 0.62, y: 0.17, width: 0.11, height: 0.2 } }] },
  coach: {
    alt: t({ en: 'Coach Mori in the doorway, backlit, arms crossed.',
      es: 'El entrenador Mori en la puerta, a contraluz, de brazos cruzados.',
      ca: 'L’entrenador Mori a la porta, a contrallum, de braços plegats.',
      pt: 'O treinador Mori na porta, contra a luz, de braços cruzados.',
      zh: '森老师站在门口，背着光，双臂抱在胸前。',
      ar: 'المدرّب موري عند الباب، والضوء خلفه، عاقدًا ذراعيه.',
      ja: '逆光の戸口で腕を組んで立つ森先生。' }),
  safeArea: { x: 0.33, y: 0.13, width: 0.3, height: 0.32 },
  anchors: [{ id: 'mori', x: 0.425, y: 0.215, head: { x: 0.42, y: 0.17 },
    face: { x: 0.37, y: 0.13, width: 0.1, height: 0.11 } }] },
  smile: {
    alt: t({ en: "Close-up of Mori's stern face breaking into a small smile.",
      es: 'Primer plano del rostro severo de Mori, que esboza una sonrisa.',
      ca: 'Primer pla de la cara severa d’en Mori, que esbossa un somriure.',
      pt: 'Primeiro plano do rosto severo de Mori, que esboça um sorriso.',
      zh: '森老师严肃的脸上露出一丝笑意的特写。',
      ar: 'لقطة قريبة لوجه موري الصارم وقد ارتسمت عليه ابتسامة.',
      ja: '厳しい顔がふっとゆるむ森先生のアップ。' }),
  safeArea: { x: 0.43, y: 0.21, width: 0.51, height: 0.53 },
  anchors: [{ id: 'mori', x: 0.69, y: 0.52, head: { x: 0.6, y: 0.25 },
    face: { x: 0.45, y: 0.28, width: 0.45, height: 0.32 } }] },
  kneel: {
    alt: t({ en: 'Kneeling, Hana ties the charm to her armour; Sora scratches his head.',
      es: 'De rodillas, Hana se ata el amuleto a la armadura; Sora se rasca la cabeza.',
      ca: 'De genolls, la Hana es lliga l’amulet a l’armadura; en Sora es grata el cap.',
      pt: 'De joelhos, Hana amarra o amuleto na armadura; Sora coça a cabeça.',
      zh: '花跪坐着把护身符系在护具上，空挠着头。',
      ar: 'هانا جاثية تربط التميمة بدرعها، وسورا يحكّ رأسه.',
      ja: '正座してお守りを防具に結ぶ花と、頭をかく空。' }),
  safeArea: { x: 0.21, y: 0.08, width: 0.61, height: 0.48 },
  avoid: [{ x: 0.27, y: 0.43, width: 0.06, height: 0.12 }],
  anchors: [{ id: 'hana', x: 0.305, y: 0.245, head: { x: 0.3, y: 0.17 },
    face: { x: 0.25, y: 0.1, width: 0.11, height: 0.17 } },
  { id: 'sora', x: 0.7, y: 0.25, head: { x: 0.71, y: 0.15 },
    face: { x: 0.64, y: 0.1, width: 0.13, height: 0.18 } }] },
  roof: {
    alt: t({ en: 'Seen from behind, Hana and Sora sit on the school roof at sunset.',
      es: 'De espaldas, Hana y Sora sentados en la azotea del instituto al atardecer.',
      ca: 'D’esquena, la Hana i en Sora asseguts al terrat de l’institut a la posta.',
      pt: 'De costas, Hana e Sora sentados no terraço da escola ao pôr do sol.',
      zh: '夕阳下，花和空坐在学校楼顶的背影。',
      ar: 'هانا وسورا جالسان على سطح المدرسة عند الغروب، من الخلف.',
      ja: '夕焼けの屋上に並んで座る花と空の後ろ姿。' }),
  safeArea: { x: 0.24, y: 0.41, width: 0.47, height: 0.31 },
  anchors: [{ id: 'hana', x: 0.36, y: 0.52, head: { x: 0.36, y: 0.48 },
    face: { x: 0.31, y: 0.43, width: 0.11, height: 0.14 } },
  { id: 'sora', x: 0.63, y: 0.52, head: { x: 0.625, y: 0.47 },
    face: { x: 0.58, y: 0.41, width: 0.1, height: 0.15 } }] },
};
const panels = () => Promise.all([
  comicPanel('dojo', asset('kendo-dojo.jpg'), ART.dojo),
  comicPanel('swing', asset('kendo-swing.jpg'), ART.swing),
  comicPanel('doorway', asset('kendo-doorway.jpg'), ART.doorway),
  comicPanel('closeup', asset('kendo-closeup.jpg'), ART.closeup),
  comicPanel('charm', asset('kendo-charm.jpg'), ART.charm),
  comicPanel('coach', asset('kendo-coach.jpg'), ART.coach),
  comicPanel('smile', asset('kendo-smile.jpg'), ART.smile),
  comicPanel('kneel', asset('kendo-kneel.jpg'), ART.kneel),
  comicPanel('roof', asset('kendo-roof.jpg'), ART.roof),
]);
// #endregion

// #region fonts: each edition loads its two faces with the words they set
const SFX = /^sfx[^:：\n]*[:：](.*)$/gm; // sound-effect lines: the second face sets them
async function loadEdition(lang) {
  const text = TEXT[lang];
  const [face, sfx] = EDITIONS[lang].faces;
  const faces = { [face]: FONTS[face], [sfx]: FONTS[sfx] };
  if (['ja', 'zh'].includes(lang)) { // CJK: only the files that hold these characters
    const effects = [...text.matchAll(SFX)].map((m) => m[1]).join('');
    await loadCjkFonts({ [face]: FONTS[face] }, text.replace(SFX, ''), { vertical: true });
    await loadCjkFonts({ [sfx]: FONTS[sfx] }, effects, { vertical: true });
  }
  if (lang === 'ar') await loadArabicFonts(faces, text);
  await loadComicFonts(faces, text); // the bold and italic the faces do not ship
}
// #endregion

// ─── 4 · Build & show ───────────────────────────────────────────────────────
// #region editions: the original on the right-hand page, this edition's lettering facing it
const FACING = LANG === 'ja' ? 'en' : LANG; // Japanese readers see the English edition
const TEXT = { ja: original, [FACING]: LANG === 'ja' ? english : markdown };
await loadFonts(FONTS, Object.values(TEXT).join('\n'));
const resources = await panels();
const build = async (lang) => { // the same pictures and page; this language's lettering
  await loadEdition(lang);
  return buildWithFonts(() => buildDocument({ markdown: TEXT[lang], resources,
    continuation: { pageIndexOffset: 1 } }, edition(lang)), TEXT[lang]);
};
const docs = [await build('ja'), await build(FACING)];
// #endregion
const TITLE = t({
  en: 'A manga read right to left', es: 'Un manga que se lee de derecha a izquierda',
  ca: 'Un manga que es llegeix de dreta a esquerra', zh: '从右往左读的漫画',
  pt: 'Um mangá lido da direita para a esquerda',
  ar: 'مانغا تُقرأ من اليمين إلى اليسار', ja: '右から左へ読む漫画' });
showBook(docs, { title: TITLE });
offerPdf(() => renderToPdf(docs, { fontProvider: comicPdfProvider, resourceBytes: imageBytes }),
  `${RECIPE}.pdf`);

// ─── Kit ── helpers shared by every Cookbook recipe · postext.dev/cookbook ─────

// ─── Kit · core v1 ── the same in every recipe · postext.dev/cookbook
function mm(value) { return { value, unit: 'mm' }; }
function pt(value) { return { value, unit: 'pt' }; }
function em(value) { return { value, unit: 'em' }; }
/** The sample language's string: t({ en: 'Figure', es: 'Figura' }). */
function t(strings) { return strings[LANG] ?? Object.values(strings)[0]; }
/** A file in this recipe's assets folder, served from the Postext repo by jsDelivr. */
function asset(file) { return `https://cdn.jsdelivr.net/gh/drnachio/postext@main/cookbook/${RECIPE}/assets/${file}`; }

// ─── Kit · fonts v2 ── the same in every recipe · postext.dev/cookbook
// Postext measures with the loaded faces and caches the widths: load every face
// before the first build, from Fontsource, the files the PDF embeds too.

/** faces = { 'Family Name': ['400', '400i', '700'] }. `text` is the sample:
 *  č ł † α χ also load latin-ext and greek files (kitSubsetsFor). With
 *  `optional`, a face Fontsource does not ship is skipped instead of failing.
 *  Resolves to the number of faces added. */
async function loadFonts(faces, text = '', { optional = false } = {}) {
  kitStatus('Loading fonts…');
  const ranges = {
    latin: 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,'
      + 'U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD',
    'latin-ext': 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,'
      + 'U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF',
    greek: 'U+0370-03FF',
  };
  const jobs = [];
  let added = 0;
  for (const [family, specs] of Object.entries(faces)) {
    const id = fontsourceId(family);
    const todo = [...new Set(specs)].map((spec) => [parseInt(spec, 10), spec.endsWith('i') ? 'italic' : 'normal'])
      .filter(([weight, style]) => !hasFace(family, weight, style)); // before any await
    const meta = optional || /[^\0-ÿ]/u.test(text) ? await fontsourceMeta(family) : null;
    const subsets = ['latin', ...kitSubsetsFor(text, meta)];
    for (const [weight, style] of todo) {
      if (optional && !(meta?.weights.includes(weight) && meta.styles.includes(style))) continue;
      for (const subset of subsets) {
        const url = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${id}-${subset}-${weight}-${style}.woff2`;
        const face = new FontFace(family, `url(${url}) format('woff2')`,
          { weight: String(weight), style, unicodeRange: ranges[subset] });
        jobs.push(face.load().then((ready) => { document.fonts.add(ready); added++; }, () => {
          if (subset === 'latin' && !optional) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
        }));
      }
    }
  }
  await Promise.all(jobs).catch((error) => { kitFail(error); throw error; });
  return added;
}

/** Runs `build` and loads any face the pages use that FONTS missed (a regular
 *  one with a warning), then clears the measurement cache and builds again. */
async function buildWithFonts(build, text = '') {
  const tried = new Set();
  for (let round = 0; round < 3; round++) {
    kitStatus('Laying out…');
    await new Promise(requestAnimationFrame);          // let the status paint first
    const result = await Promise.resolve().then(build).catch((error) => { kitFail(error); throw error; });
    const wanted = { base: {}, variants: {} };
    for (const { font, base } of [result].flat().flatMap(fontStringsOf)) {
      const { family, weight, style } = parseFont(font);
      const key = `${family}|${weight}|${style}`;
      if (tried.has(key) || hasFace(family, weight, style)) continue;
      tried.add(key);
      (wanted[base ? 'base' : 'variants'][family] ??= []).push(`${weight}${style === 'italic' ? 'i' : ''}`);
    }
    if (Object.keys(wanted.base).length) {
      console.warn(`[cookbook] FONTS does not list ${JSON.stringify(wanted.base)}: loading them.`);
    }
    const added = await loadFonts(wanted.base, text) + await loadFonts(wanted.variants, text, { optional: true });
    if (added === 0) return result;
    clearMeasurementCache();
  }
  throw new Error('The fonts did not settle after three builds.');
}

/** Every font string of the layout; `base` marks a block's own face. */
function fontStringsOf(doc) {
  const found = new Map();
  const walk = (node) => {
    if (!node || typeof node !== 'object') return;
    if (Array.isArray(node)) { node.forEach(walk); return; }
    for (const [key, value] of Object.entries(node)) {
      if (typeof value === 'string' && /fontString$/i.test(key)) {
        found.set(value, found.get(value) || key === 'fontString');
      } else if (value && typeof value === 'object') walk(value);
    }
  };
  walk(doc.pages);
  walk(doc.blocks);
  return [...found].map(([font, base]) => ({ font, base }));
}

/** '700 37.5px Open Sans' / 'italic 400 13px "Source Serif 4"' → { family, weight, style }.
 *  A string with no weight ('95.8px Young Serif', from a design text) is 400. */
function parseFont(font) {
  const m = /^(?:(italic|oblique)\s+)?(?:small-caps\s+)?(?:(\d+|bold|normal)\s+)?[\d.]+px\s+(.+)$/.exec(font.trim());
  if (!m) throw new Error(`Unexpected font string: ${font}`);
  const weight = m[2] === 'bold' ? 700 : !m[2] || m[2] === 'normal' ? 400 : Number(m[2]);
  return { family: m[3].replace(/^["']|["']$/g, ''), weight, style: m[1] ? 'italic' : 'normal' };
}

/** A loaded FontFace covers this family, weight and style (fonts.check() would
 *  also say yes for families nobody declared). */
function hasFace(family, weight, style) {
  for (const face of document.fonts) {
    if (face.status !== 'loaded' || face.style !== style) continue;
    if (face.family.replace(/^["']|["']$/g, '') !== family) continue;
    const [low, high = low] = face.weight.split(' ').map(Number);
    if (weight >= low && weight <= high) return true;
  }
  return false;
}

/** The files beyond latin `text` needs that `meta`'s family ships. */
function kitSubsetsFor(text, meta) {
  return [[/[Ā-˿ᴀ-ᶿḀ-ỿ†ℓⱠ-Ɀ꜠-ꟿ]/u, 'latin-ext'], [/[Ͱ-Ͽ]/u, 'greek']]
    .filter(([re, x]) => re.test(text) && meta?.subsets?.includes(x)).map(([, x]) => x);
}

/** Fontsource's id for a family: 'Source Serif 4' → 'source-serif-4'. */
function fontsourceId(family) { return family.toLowerCase().replace(/\s+/g, '-'); }

/** The family's Fontsource metadata (weights, styles, subsets), or null. */
function fontsourceMeta(family) {
  fontsourceMeta.cache ??= new Map();
  const id = fontsourceId(family);
  if (!fontsourceMeta.cache.has(id)) {
    fontsourceMeta.cache.set(id, fetch(`https://api.fontsource.org/v1/fonts/${id}`)
      .then((res) => (res.ok ? res.json() : null), () => null));
  }
  return fontsourceMeta.cache.get(id);
}

// ─── Kit · viewer v1 ── the same in every recipe · postext.dev/cookbook
/** The pages as spreads on a dark desk, page 1 alone, then verso | recto,
 *  each painted when it scrolls near. */
function showPages(docs, { title, width = 460 } = {}) {
  const root = viewer(title);
  const pages = [docs].flat().flatMap((doc) =>
    doc.pages.map((page) => ({ doc, page, n: (doc.pageIndexOffset ?? 0) + page.index })));
  const spreads = [];
  let verso = null;
  for (const p of pages) {
    if (p.n % 2 === 1) { if (verso) spreads.push([verso, null]); verso = p; }
    else { spreads.push([verso, p]); verso = null; }
  }
  if (verso) spreads.push([verso, null]);
  const density = Math.min(window.devicePixelRatio || 1, 2);
  showPages.painter?.disconnect();
  const painter = new IntersectionObserver((entries) => {
    for (const { isIntersecting, target } of entries) {
      if (!isIntersecting) continue;
      painter.unobserve(target);
      const { doc, page } = target.postext;
      renderPageToCanvas(page, doc, target, { scale: (width * density) / page.width });
    }
  }, { rootMargin: '800px' });
  showPages.painter = painter;
  root.replaceChildren(...spreads.map((pair) => {
    const spread = document.createElement('div');
    spread.className = 'pt-spread';
    for (const p of pair) {
      const figure = document.createElement('figure');
      if (p) {
        const label = p.page.pageLabel || String(p.n + 1);
        const canvas = document.createElement('canvas');
        canvas.postext = p;
        canvas.style.aspectRatio = `${p.page.width} / ${p.page.height}`;
        canvas.setAttribute('role', 'img');
        canvas.setAttribute('aria-label', `Page ${label}`);
        const folio = document.createElement('figcaption');
        folio.textContent = label;
        figure.append(canvas, folio);
        painter.observe(canvas);
      } else figure.className = 'pt-blank';
      spread.append(figure);
    }
    return spread;
  }));
  kitStatus(`${pages.length} ${pages.length === 1 ? 'page' : 'pages'}`);
  document.documentElement.dataset.postext = 'ready';
  return pages.length;
}

/** The desk, the bar and the error reporting, created once. */
function viewer(title) {
  if (!document.getElementById('pt-kit')) {
    document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit">
      :root { color-scheme: dark; }
      body { margin: 0; background: #0e1014; color: #b9bcc4; font: 13px/1.45 system-ui, sans-serif; }
      #pt-bar { position: sticky; top: 0; z-index: 1; display: flex; flex-wrap: wrap; align-items: center;
        gap: 6px 16px; padding: 10px 16px; background: rgb(14 16 20 / .92); backdrop-filter: blur(6px);
        border-bottom: 1px solid #23262d; }
      #pt-bar strong { color: #f4f1ea; font-weight: 600; }
      #pt-actions { display: flex; gap: 12px; margin-left: auto; }
      #pt-actions a, #pt-actions button { color: #d8a21a; font: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
      #pages { display: grid; justify-items: center; gap: 48px; padding: 32px 16px 72px; }
      .pt-spread { display: flex; }
      .pt-spread figure { margin: 0; width: min(460px, 44vw); }
      .pt-spread canvas { display: block; width: 100%; background: #fff;
        box-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figure:first-child canvas { box-shadow: inset -14px 0 14px -14px rgb(0 0 0 / .18), 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figcaption { margin-top: 10px; text-align: center; font: 600 10px/1 system-ui, sans-serif;
        letter-spacing: .18em; text-transform: uppercase; color: #6c7079; }
      .pt-blank { visibility: hidden; }
      @media (max-width: 760px) {
        .pt-spread { flex-direction: column; gap: 32px; }
        .pt-spread figure { width: min(460px, 92vw); }
        .pt-blank { display: none; }
      }
    </style>`);
    document.body.insertAdjacentHTML('afterbegin',
      '<header id="pt-bar"><strong id="pt-title"></strong><span id="pt-status" role="status"></span><span id="pt-actions"></span></header>');
    document.getElementById('pt-title').textContent = document.title || 'Postext';
    addEventListener('error', (event) => kitFail(event.error ?? event.message));
    addEventListener('unhandledrejection', (event) => kitFail(event.reason));
  }
  if (title) document.getElementById('pt-title').textContent = title;
  return document.getElementById('pages')
    ?? document.body.appendChild(Object.assign(document.createElement('main'), { id: 'pages' }));
}

function kitStatus(text) {
  viewer();
  document.getElementById('pt-status').textContent = text;
}

function kitFail(error) {
  document.documentElement.dataset.postext = 'error';
  kitStatus(`Error: ${error?.message ?? error}`);
}

// ─── Kit · pdf v2 ── the same in every recipe that exports a PDF
/** The Fontsource files the screen used, as TrueType: the nearest weight the
 *  family ships, upright if it has no italic; latin, then what the face's
 *  letters need (kitSubsetsFor). */
async function fontsourceProvider(family, weight, style, request) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  const weights = meta?.weights?.length ? meta.weights : [400, 700];
  const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const s = style === 'italic' && meta && !meta.styles.includes('italic') ? 'normal' : style;
  const text = String.fromCodePoint(...(request?.codePoints ?? []));
  const more = kitSubsetsFor(text, meta);
  const files = await Promise.all(['latin', ...more].map(async (subset) => {
    const res = await fetch(`https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${id}-${subset}-${w}-${s}.woff2`);
    if (!res.ok) throw new Error(`Fontsource has no ${family} ${w} ${s} ${subset}`);
    return decompressWoff2(new Uint8Array(await res.arrayBuffer()));
  }));
  return files.length === 1 ? files[0] : files;
}

/** A "Build the PDF" button; then "Open the PDF" (a new tab: CodePen's frame
 *  shows no PDFs) and a download link. */
function offerPdf(makePdf, filename) {
  viewer();
  const button = Object.assign(document.createElement('button'), { type: 'button', textContent: 'Build the PDF' });
  button.dataset.postextPdf = filename;
  button.addEventListener('click', async () => {
    button.disabled = true;
    button.textContent = 'Building the PDF…';
    try {
      const bytes = await makePdf();
      const url = URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }));
      const size = `${Math.max(1, Math.round(bytes.length / 1024))} KB`;
      button.replaceWith(
        Object.assign(document.createElement('a'), { href: url, target: '_blank', rel: 'noopener', textContent: 'Open the PDF ↗' }),
        Object.assign(document.createElement('a'), { href: url, download: filename, textContent: `Download ${filename} · ${size}` }));
    } catch (error) {
      button.disabled = false;
      button.textContent = 'Build the PDF';
      kitFail(error);
    }
  });
  document.getElementById('pt-actions').append(button);
}

// ─── Kit · images v1 ── recipes with pictures · postext.dev/cookbook
/** Registers a photo or PNG for the canvas and keeps its bytes for the PDF.
 *  fetch → ImageBitmap never taints the canvas (a plain cross-origin <img> would). */
async function loadImage(fileId, url) {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`Image not found (${res.status}): ${url}`);
  const bytes = new Uint8Array(await res.arrayBuffer());
  registerResourceImage(fileId, await createImageBitmap(new Blob([bytes])));
  (loadImage.bytes ??= new Map()).set(fileId, bytes);
}

/** Registers SVG markup (drawn in code, or fetched) as a vector image. */
async function loadSvg(fileId, svg) {
  const img = new Image();
  img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
  await img.decode();
  registerResourceImage(fileId, img);
  (loadImage.bytes ??= new Map()).set(fileId, new TextEncoder().encode(svg));
}

/** renderToPdf({ resourceBytes: imageBytes }) */
function imageBytes(fileId) { return loadImage.bytes?.get(fileId); }

/** renderToHtml({ resourceImageUrl: imageUrl }) */
function imageUrl(fileId) {
  const bytes = imageBytes(fileId);
  if (!bytes) return undefined;
  imageUrl.urls ??= new Map();
  if (!imageUrl.urls.has(fileId)) {
    const type = /\.svg$/i.test(fileId) ? 'image/svg+xml' : /\.png$/i.test(fileId) ? 'image/png' : 'image/jpeg';
    imageUrl.urls.set(fileId, URL.createObjectURL(new Blob([bytes], { type })));
  }
  return imageUrl.urls.get(fileId);
}

// ─── Kit · cjk v1 ── Chinese, Japanese and Korean books · postext.dev/cookbook
// Fontsource ships a CJK family as about a hundred files per weight, each
// declared in its stylesheet with the unicode-range it covers. The screen
// loads the files the sample touches; the PDF gets the same files for the
// characters its pages set in each face, and embeds each as a subset.
// A book bound on the right (vertical text) is shown with its spreads
// mirrored: page 1 alone on the left of the spine, then [3 | 2].

/** The files of a Fontsource face, read from its stylesheet: { url, range,
 *  ranges }, the last declared first (the order the browser tries them in). */
function cjkSlices(family, weight, style) {
  cjkSlices.cache ??= new Map();
  const id = fontsourceId(family);
  const css = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/${weight}${style === 'italic' ? '-italic' : ''}.css`;
  if (!cjkSlices.cache.has(css)) {
    cjkSlices.cache.set(css, fetch(css)
      .then((res) => {
        if (!res.ok) throw new Error(`Fontsource has no ${family} ${weight} ${style} (${res.status})`);
        return res.text();
      })
      .then((text) => [...text.matchAll(/@font-face\s*{([^}]*)}/g)].map(([, rule]) => {
        const range = /unicode-range:\s*([^;]+);/.exec(rule)?.[1].trim() ?? 'U+0-10FFFF';
        const ranges = range.split(',').map((part) => {
          const [lo, hi = lo] = part.trim().slice(2).split('-');
          return [parseInt(lo, 16), parseInt(hi, 16)];
        });
        return { url: new URL(/url\(([^)]+?\.woff2)\)/.exec(rule)[1], css).href, range, ranges };
      }).reverse()));
  }
  return cjkSlices.cache.get(css);
}

/** The file of `slices` that holds code point `cp`, if any. */
function cjkSliceFor(slices, cp) {
  return slices.find((slice) => slice.ranges.some(([lo, hi]) => cp >= lo && cp <= hi));
}

/** Whether Fontsource serves `family` as a Chinese, Japanese or Korean
 *  family (its subsets name the script). Fails when the API does not
 *  answer: a CJK face taken for a Latin one would paint in a system face. */
async function isCjkFamily(family) {
  const meta = await fontsourceMeta(family);
  if (!meta) throw new Error(`api.fontsource.org did not describe ${family}: reload to try again`);
  return !!meta.subsets?.some((subset) => /^(chinese|japanese|korean)/.test(subset));
}

/** faces = { 'Noto Serif TC': ['400', '700'] }, as for loadFonts: the
 *  whole FONTS object may be passed, its other families are left to
 *  loadFonts. Adds one FontFace per file of each CJK face with its
 *  unicodeRange, then loads the files `text` touches. `text` is what the
 *  faces set: the sample for the text face; a book in several voices calls
 *  it once per voice (loadCjkFonts({ 'LXGW WenKai TC': ['400'] }, quotes)),
 *  so the heading and quotation faces fetch and check only their own
 *  characters. Fails when a character of `text` is in no file of a face.
 *  List every weight the pages use: a weight left to buildWithFonts gets
 *  the latin file only. With { vertical: true } it also loads each
 *  family's vertical forms (brackets, quotes, pause marks) for the canvas,
 *  which needs loadVerticalAlternates imported from postext. Resolves to
 *  the number of files loaded. */
async function loadCjkFonts(faces, text, { vertical = false } = {}) {
  kitStatus('Loading fonts…');
  let loaded = 0;
  try {
    if (vertical && typeof loadVerticalAlternates !== 'function') {
      throw new Error('loadCjkFonts(…, { vertical: true }) needs loadVerticalAlternates imported from postext');
    }
    for (const [family, specs] of Object.entries(faces)) {
      if (!(await isCjkFamily(family))) continue;
      const twin = [];
      for (const spec of new Set(specs)) {
        const weight = parseInt(spec, 10);
        const style = spec.endsWith('i') ? 'italic' : 'normal';
        const slices = await cjkSlices(family, weight, style);
        const missing = [...new Set(text)].filter((ch) => /\S/.test(ch) && !cjkSliceFor(slices, ch.codePointAt(0)));
        if (missing.length) {
          throw new Error(`${family} ${spec} has no file for ${missing.slice(0, 12).join(' ')}: `
            + `give each face the text it sets (loadCjkFonts({ '${family}': ['${spec}'] }, text))`);
        }
        for (const slice of slices) {
          document.fonts.add(new FontFace(family, `url(${slice.url}) format('woff2')`,
            { weight: String(weight), style, unicodeRange: slice.range }));
          twin.push({ source: slice.url, weight: String(weight), style, unicodeRange: slice.range });
        }
        const font = `${style === 'italic' ? 'italic ' : ''}${weight} 16px "${family}"`;
        loaded += (await document.fonts.load(font, text)).length;
        if (!document.fonts.check(font, text)) throw new Error(`${family} ${spec} did not load for the sample`);
      }
      // The same files under a twin name with the `vert` feature on: the
      // canvas paints the punctuation of vertical lines with it.
      if (vertical && twin.length) await loadVerticalAlternates(family, twin);
    }
  } catch (error) {
    kitFail(error);
    throw error;
  }
  return loaded;
}

/** The PDF font provider for recipes with CJK faces: a family whose
 *  Fontsource subsets are Chinese, Japanese or Korean gets the files that
 *  hold the characters its pages set (`request.codePoints`); any other
 *  family gets the latin file fontsourceProvider fetches (the "pdf" block)
 *  and, when the face sets letters only latin-ext has, that file too. */
async function cjkPdfProvider(family, weight, style, request) {
  if (!(await isCjkFamily(family))) return cjkLatinPdfFiles(family, weight, style, request);
  const meta = await fontsourceMeta(family);
  const weights = meta.weights?.length ? meta.weights : [400, 700];
  const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const s = style === 'italic' && !meta.styles.includes('italic') ? 'normal' : style;
  const slices = await cjkSlices(family, w, s);
  const picked = new Set();
  for (const cp of request?.codePoints ?? []) {
    const slice = cjkSliceFor(slices, cp);
    if (slice) picked.add(slice);
  }
  if (!picked.size) picked.add(slices[0]);
  return Promise.all(slices.filter((slice) => picked.has(slice)).map(async (slice) => {
    const res = await fetch(slice.url);
    if (!res.ok) throw new Error(`Fontsource file ${slice.url} (${res.status})`);
    return decompressWoff2(new Uint8Array(await res.arrayBuffer()));
  }));
}

/** A Latin family set next to the CJK faces: its latin file, then its
 *  latin-ext file when the face sets letters only latin-ext has (ō ū in
 *  Hepburn rōmaji, ǎ in pinyin), the file loadFonts adds on screen for
 *  them. Latin comes first: postext-pdf draws a character from the first
 *  file that has it, as the browser takes a character both files hold from
 *  latin. A face Fontsource ships without latin-ext, or whose file does
 *  not come, gets latin alone, and the PDF names the letters it lacks. */
async function cjkLatinPdfFiles(family, weight, style, request) {
  const meta = await fontsourceMeta(family);
  const beyond = [...(request?.codePoints ?? [])].some(cjkLatinExtOnly);
  if (!beyond || !meta?.subsets?.includes('latin-ext')) return fontsourceProvider(family, weight, style);
  const weights = meta.weights?.length ? meta.weights : [400, 700];
  const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const s = style === 'italic' && !meta.styles.includes('italic') ? 'normal' : style;
  const id = fontsourceId(family);
  const url = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${id}-latin-ext-${w}-${s}.woff2`;
  const [latin, ext] = await Promise.all([fontsourceProvider(family, weight, style), fetch(url)
    .then(async (res) => (res.ok ? decompressWoff2(new Uint8Array(await res.arrayBuffer())) : null), () => null)]);
  return ext ? [latin, ext] : latin;
}

/** Whether code point `cp` is in Fontsource's latin-ext file and not in
 *  its latin file: Latin Extended-A and -B, IPA, the spacing modifiers and
 *  Latin Extended Additional (loadFonts's test for latin-ext), less the
 *  few latin holds too (ı Œ œ ʻ ʼ ˆ ˚ ˜). */
function cjkLatinExtOnly(cp) {
  if (!((cp >= 0x100 && cp <= 0x2ff) || (cp >= 0x1e00 && cp <= 0x1eff))) return false;
  return ![0x131, 0x152, 0x153, 0x2bb, 0x2bc, 0x2c6, 0x2da, 0x2dc].includes(cp);
}

/** showPages for a book bound on either edge. A right-bound book (the
 *  document says so: doc.binding is 'right' for page.binding 'right' and
 *  for vertical text) lies on the desk as it opens: page 1 alone on the
 *  left of the spine, then [3 | 2], the spine shade on each page's inner
 *  edge. `binding` ('left' | 'right') overrides the document's. */
function showBook(docs, { binding, ...options } = {}) {
  const count = showPages(docs, options);
  const right = (binding ?? [docs].flat()[0]?.binding) === 'right';
  if (!document.getElementById('pt-kit-cjk')) {
    // The pages keep direction ltr: a canvas draws text in the direction its
    // element inherits, and under rtl each run would end where the engine
    // starts it, its brackets mirrored.
    document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit-cjk">
      .pt-spread[dir="rtl"] canvas { direction: ltr; }
      .pt-spread[dir="rtl"] figure:first-child canvas { box-shadow: inset 14px 0 14px -14px rgb(0 0 0 / .18),
        0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
    </style>`);
  }
  // Each pair stays [verso, recto] in the page; right to left, the verso
  // sits on the right. Phones stack the pages in reading order either way.
  for (const spread of document.querySelectorAll('#pages > .pt-spread')) spread.dir = right ? 'rtl' : 'ltr';
  document.getElementById('pages').dataset.binding = right ? 'right' : 'left';
  return count;
}

// ─── Kit · arabic v1 ── Arabic-script faces · postext.dev/cookbook
// Fontsource ships an Arabic family as one file per subset and weight: the
// `arabic` file holds the letters, the harakat, the Arabic-Indic digits, the
// Arabic punctuation and the presentation forms; `latin` and `latin-ext`
// hold the rest. loadFonts loads the latin files; this block adds the arabic
// file of every Arabic family, for the canvas and for the PDF, which shapes
// the letters with HarfBuzz from the same bytes.

/** The code points of Fontsource's `arabic` subset, as its stylesheets
 *  declare them (the same unicode-range the browser picks the file by). A
 *  function, not a const: the kit is inlined after the recipe's top-level
 *  awaits, and a const read before its line throws, where a function
 *  declaration is hoisted. */
function arabicRange() {
  return 'U+0600-06FF,U+0750-077F,U+0870-088E,U+0890-0891,U+0897-08E1,U+08E3-08FF,'
    + 'U+200C-200E,U+2010-2011,U+204F,U+2E41,U+FB50-FDFF,U+FE70-FE74,U+FE76-FEFC,U+102E0-102FB,'
    + 'U+10E60-10E7E,U+10EC2-10EC4,U+10EFC-10EFF,U+1EE00-1EEFF';
}

/** Whether code point `cp` is in the arabic file. */
function inArabicRange(cp) {
  inArabicRange.ranges ??= arabicRange().split(',').map((part) => {
    const [lo, hi = lo] = part.slice(2).split('-');
    return [parseInt(lo, 16), parseInt(hi, 16)];
  });
  return inArabicRange.ranges.some(([lo, hi]) => cp >= lo && cp <= hi);
}

/** Whether Fontsource serves `family` with an `arabic` subset. Fails when
 *  the API does not answer: an Arabic face taken for a Latin one would set
 *  its letters in a system face. */
async function isArabicFamily(family) {
  const meta = await fontsourceMeta(family);
  if (!meta) throw new Error(`api.fontsource.org did not describe ${family}: reload to try again`);
  return !!meta.subsets?.includes('arabic');
}

/** The arabic file of a face. */
function arabicFileUrl(family, weight, style) {
  const id = fontsourceId(family);
  return `https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${id}-arabic-${weight}-${style}.woff2`;
}

/** faces = { Amiri: ['400', '700'] }, as for loadFonts, after it: the whole
 *  FONTS object may be passed, its families without an arabic subset are
 *  left alone. Adds the arabic file of every listed weight of each Arabic
 *  family (the latin files come from loadFonts) and loads it. `text` is
 *  the sample: fails when it holds an Arabic-script character the arabic
 *  file does not cover. List every weight the pages set in Arabic: a weight
 *  left to buildWithFonts gets the latin file only, and its Arabic letters
 *  fall back to a system face. Resolves to the number of files loaded. */
async function loadArabicFonts(faces, text = '') {
  kitStatus('Loading fonts…');
  let loaded = 0;
  try {
    const outside = [...new Set(text)].filter((ch) => /\p{Script=Arabic}/u.test(ch) && !inArabicRange(ch.codePointAt(0)));
    if (outside.length) throw new Error(`Fontsource's arabic files have no ${outside.slice(0, 12).join(' ')}`);
    for (const [family, specs] of Object.entries(faces)) {
      if (!(await isArabicFamily(family))) continue;
      for (const spec of new Set(specs)) {
        const weight = parseInt(spec, 10);
        const style = spec.endsWith('i') ? 'italic' : 'normal';
        const face = new FontFace(family, `url(${arabicFileUrl(family, weight, style)}) format('woff2')`,
          { weight: String(weight), style, unicodeRange: arabicRange() });
        document.fonts.add(await face.load().catch(() => {
          throw new Error(`Fontsource has no arabic file for ${family} ${weight} ${style}`);
        }));
        loaded++;
      }
    }
  } catch (error) {
    kitFail(error);
    throw error;
  }
  return loaded;
}

/** The PDF font provider for recipes with Arabic faces: a family with an
 *  arabic subset gets its arabic file when its pages set Arabic letters
 *  (`request.codePoints`), then its latin file, and its latin-ext file for
 *  the letters beyond latin (transliteration: ā ḥ ʿ). The arabic file comes
 *  first: it also holds the space and the brackets, so a line of Arabic is
 *  shaped as one run and not cut at every space. Any other family goes to
 *  fontsourceProvider (the "pdf" block). */
async function arabicPdfProvider(family, weight, style, request) {
  if (!(await isArabicFamily(family))) return fontsourceProvider(family, weight, style, request);
  const meta = await fontsourceMeta(family);
  const weights = meta.weights?.length ? meta.weights : [400, 700];
  const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const s = style === 'italic' && !meta.styles.includes('italic') ? 'normal' : style;
  const wanted = [...(request?.codePoints ?? [])];
  const id = fontsourceId(family);
  const urls = [];
  if (!wanted.length || wanted.some(inArabicRange)) urls.push(arabicFileUrl(family, w, s));
  urls.push(`https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${id}-latin-${w}-${s}.woff2`);
  if (meta.subsets.includes('latin-ext') && wanted.some((cp) => /[Ā-˿Ḁ-ỿ]/u.test(String.fromCodePoint(cp)))) {
    urls.push(`https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${id}-latin-ext-${w}-${s}.woff2`);
  }
  return Promise.all(urls.map(async (url) => {
    const res = await fetch(url);
    if (!res.ok) throw new Error(`Fontsource file ${url} (${res.status})`);
    return decompressWoff2(new Uint8Array(await res.arrayBuffer()));
  }));
}

// ─── Kit · comics v1 ── comic pages · postext.dev/cookbook
// The engine letters a comic in a face per language (defaultComicFont:
// Comic Neue, Zen Antique for Japanese, Noto Sans SC, LXGW WenKai TC,
// Playpen Sans Arabic; defaultComicSfxFont: Bangers, Dela Gothic One,
// ZCOOL KuaiLe, Lalezar) and asks for the bold of a shout or a sound effect
// and the italic of an inner voice. Most of these faces ship one weight and
// no italic: this block declares the file Fontsource does ship for those
// variants, so the canvas measures and paints the letters the PDF embeds
// (the providers snap to the shipped file) and not a bold or a slant the
// browser makes up. It also turns the art manifest into panel resources.

/** faces = { 'Comic Neue': ['400', '700'], Bangers: ['400'] }, as for
 *  loadFonts, after it (and after loadCjkFonts or loadArabicFonts for the
 *  faces of those scripts); the whole FONTS object may be passed. List in
 *  FONTS only what Fontsource ships (Bangers: ['400']): loadFonts fails on
 *  the rest. For each family, the regular, bold, italic and bold italic it
 *  lacks are declared with its nearest file (the regular for the bold, the
 *  upright for the italic) and loaded for `text`. A CJK face needs the cjk
 *  block; an Arabic face setting Arabic, the arabic block. Resolves to the
 *  number of variants added. */
async function loadComicFonts(faces, text = '') {
  kitStatus('Loading fonts…');
  let added = 0;
  try {
    for (const family of Object.keys(faces)) {
      const meta = await fontsourceMeta(family);
      if (!meta) throw new Error(`api.fontsource.org did not describe ${family}: reload to try again`);
      const weights = meta.weights?.length ? meta.weights : [400, 700];
      const styles = meta.styles?.length ? meta.styles : ['normal'];
      for (const [weight, style] of [[400, 'normal'], [700, 'normal'], [400, 'italic'], [700, 'italic']]) {
        if ((weights.includes(weight) && styles.includes(style)) || hasFace(family, weight, style)) continue;
        const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
        const s = style === 'italic' && styles.includes('italic') ? 'italic' : 'normal';
        for (const { url, range } of await comicFaceFiles(family, w, s, meta, text)) {
          document.fonts.add(new FontFace(family, `url(${url}) format('woff2')`,
            { weight: String(weight), style, unicodeRange: range }));
        }
        await document.fonts.load(`${style === 'italic' ? 'italic ' : ''}${weight} 16px "${family}"`, text || 'A');
        added++;
      }
    }
  } catch (error) {
    kitFail(error);
    throw error;
  }
  return added;
}

/** The files of a shipped face ({ url, range }): a CJK face's slices (the
 *  cjk block reads them from its stylesheet), else latin, the latin-ext
 *  and greek files `text` needs, and the arabic file when `text` holds
 *  Arabic. */
async function comicFaceFiles(family, weight, style, meta, text) {
  if (meta.subsets?.some((subset) => /^(chinese|japanese|korean)/.test(subset))) {
    if (typeof cjkSlices !== 'function') throw new Error(`${family} is a CJK face: list the cjk kit block`);
    return (await cjkSlices(family, weight, style)).map(({ url, range }) => ({ url, range }));
  }
  const id = fontsourceId(family);
  const file = (subset) => `https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${id}-${subset}-${weight}-${style}.woff2`;
  const files = ['latin', ...kitSubsetsFor(text, meta)].map((subset) => ({ url: file(subset), range: comicRange(subset) }));
  if (meta.subsets?.includes('arabic') && /\p{Script=Arabic}/u.test(text)) {
    if (typeof arabicRange !== 'function') throw new Error(`${family} sets Arabic: list the arabic kit block`);
    files.unshift({ url: file('arabic'), range: arabicRange() });
  }
  return files;
}

/** The unicode-range loadFonts gives a Fontsource file. A function, not a
 *  const: the kit is inlined after the recipe's top-level awaits. */
function comicRange(subset) {
  return {
    latin: 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,'
      + 'U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD',
    'latin-ext': 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,'
      + 'U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF',
    greek: 'U+0370-03FF',
  }[subset];
}

/** The PDF font provider of a comic in any script: a CJK face goes to
 *  cjkPdfProvider, an Arabic face to arabicPdfProvider, any other to
 *  fontsourceProvider (the "pdf" block). Each embeds the shipped weight
 *  and style nearest to the one asked for, the file loadComicFonts
 *  declared for the canvas. */
async function comicPdfProvider(family, weight, style, request) {
  const subsets = (await fontsourceMeta(family))?.subsets ?? [];
  if (subsets.some((subset) => /^(chinese|japanese|korean)/.test(subset))) {
    if (typeof cjkPdfProvider !== 'function') throw new Error(`${family} is a CJK face: list the cjk kit block`);
    return cjkPdfProvider(family, weight, style, request);
  }
  if (subsets.includes('arabic') && typeof arabicPdfProvider === 'function') {
    return arabicPdfProvider(family, weight, style, request);
  }
  return fontsourceProvider(family, weight, style, request);
}

/** A panel picture as a resource for art= (and pop=): loads `url`
 *  (write asset('lh-arrive.jpg') in the call, so the lint checks the file)
 *  and declares it with `meta`, its entry in the art manifest:
 *  { width, height, alt, safeArea, anchors, avoid }. The safe area is what
 *  every crop keeps, the anchors the speakers' mouths, heads and faces,
 *  the avoid zones what no balloon covers; all in fractions of the picture,
 *  the same in every language. Without width and height, the picture's own
 *  size. Needs the images block. Resolves to the resource. */
async function comicPanel(id, url, meta = {}) {
  const fileId = decodeURIComponent(url.split('/').pop());
  await loadImage(fileId, url);
  let { width, height } = meta;
  if (!width || !height) {
    const bitmap = await createImageBitmap(new Blob([imageBytes(fileId)]));
    ({ width, height } = bitmap);
    bitmap.close();
  }
  return {
    id, typeId: meta.typeId ?? 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0,
    bitmap: { fileId, format: /\.png$/i.test(fileId) ? 'png' : 'jpeg', width, height },
    ...(meta.alt && { altText: meta.alt }),
    ...(meta.safeArea && { safeArea: meta.safeArea }),
    ...(meta.anchors?.length && { anchors: meta.anchors }),
    ...(meta.avoid?.length && { avoid: meta.avoid }),
  };
}

// ─── /Kit ───────────────────────────────────────────────────────────────────────
```

## 常见问题

- **日文文本标记为'ja'，不要用zh-Hans或LANG.** 食谱的版本是en和es，但日文示例在两个版本里都是日文：`locale: LANG`会把它标记为英文或西班牙文，中文标记则会按中文规则排它（开明式标点、小假名可以出现在行首、图代替図、PDF中用中文字形）。写'ja'：它选用日本地区（JLReq断行和标点、芝麻着重号、振假名的分布、図和表标签），并关闭断词。lint会让带假名却标记为zh或ko的文本失败。
- **中文字体通过cjk块分片加载.** Fontsource把一个中文、日文或韩文字体家族按每个字重约一百个文件提供，每个文件覆盖一段字符范围。loadFonts只获取latin文件，所以屏幕上的汉字来自系统字体，测量不准；fontsourceProvider交给PDF的也是这个latin文件，汉字印出来是空框。列出kit中的cjk块，在loadFonts之后调用loadCjkFonts(FONTS, markdown)（书中用到几种CJK字体时，每种字体调用一次，并传入它所排的文字），并给renderToPdf传fontProvider: cjkPdfProvider：两者都会取用包含文中字符的那些文件。
- **配置按对象身份缓存：每次新建一个对象.** 引擎按对象身份缓存解析后的配置，所以就地修改配置再构建，会复用旧的结果。每次构建都新建一个对象，这也是食谱的配置写成工厂函数config()的原因。
- **排版前加载所有字体.** 排版用浏览器已加载的字体测量文字，并缓存宽度，所以首次构建之后才到的字体会造成断行错误，PDF也不再与屏幕一致。先加载所有字重和样式；有字体迟到时，重新构建前调用clearMeasurementCache()。

- 每一格里第一个说话的人物要放在右边。对话框按阅读顺序排列，所以在空递护身符的那一格，脚本让站在右边的花先开口。如果空先说，他的对话框会留在他那一侧，但日文竖排的对话框下面没有地方放花的回答，回答只能并排放在右边，反而先被读到。
- 格子里放不下的对话框可能越出边框，引擎会给出警告（`comicBalloonOverflow`）。删减对白之前，先在分格里给那一格更多空间。

## 致谢

- 食谱: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- 文字: 前の晩 (The Night Before), a two-page kendo manga written for this recipe, with its English, Spanish, Catalan, Chinese and Arabic letterings: Postext Cookbook, CC-BY-4.0
- 图片: The school's old wooden kendo dojo at dusk, its doors open and lit: Generated With Diffusion Models, 原创
- 图片: Hana alone in the dojo, swinging her bamboo sword overhead: Generated With Diffusion Models, 原创
- 图片: Sora peeking round the sliding door with a shrine charm: Generated With Diffusion Models, 原创
- 图片: Close-up of Hana's sweating face: Generated With Diffusion Models, 原创
- 图片: Sora holding out the charm to Hana: Generated With Diffusion Models, 原创
- 图片: Coach Mori in the doorway, backlit, arms crossed: Generated With Diffusion Models, 原创
- 图片: Close-up of Coach Mori's small smile: Generated With Diffusion Models, 原创
- 图片: Hana tying the charm to her armour while Sora scratches his head: Generated With Diffusion Models, 原创
- 图片: Hana and Sora on the school roof at sunset, seen from behind: Generated With Diffusion Models, 原创
- 字体: Zen Antique (OFL-1.1), Dela Gothic One (OFL-1.1), Comic Neue (OFL-1.1), Bangers (OFL-1.1), Noto Sans SC (OFL-1.1), ZCOOL KuaiLe (OFL-1.1), Playpen Sans Arabic (OFL-1.1), Lalezar (OFL-1.1)
- 代码: MIT · 示例内容: CC-BY-4.0

## 相关食谱

- [No. 151 · 一页并排两篇四格漫画](https://postext.dev/zh/cookbook/yonkoma.md): 一页四格漫画：两列各四格，先读右边一篇，每篇的标题放在第一格的黑色方框里。 · 难度 2 (中级) · 漫画
- [No. 075 · 右翻的竖排中文小说](https://postext.dev/zh/cookbook/vertical-novel-right-bound.md): 把《三國演義》第一回排在台湾25開页面上：每行40字、共16行，加线框的回目章首页，切口书眉，中文数字页码，跨页从右向左阅读。 · 难度 3 (高级) · 小说、戏剧与文学散文
- [No. 153 · 用六种语言嵌字的一页漫画](https://postext.dev/zh/cookbook/one-page-six-languages.md): 分格和画面不变，每种语言一份台词：locale 决定字体，日文竖排，日文和阿拉伯文从右往左读。 · 难度 3 (高级) · 漫画
