# Marques en pàgines de dreta a esquerra i en vertical

> Una sola manera d'escriure marques per a una pàgina àrab de dreta a esquerra i una de japonesa en columnes verticals: layoutAnnotations en segueix les línies.

- Versió HTML: https://postext.dev/ca/cookbook/marks-on-rtl-and-vertical-pages
- Recepta Núm. 222 · Integració amb CMS · Nivell 3 (Avançat) · Sortides: Canvas, Controls en viu
- Gèneres: Qualsevol gènere
- Requereix postext ≥ 1.103.0 · provada amb 1.103.1 el 2026-12-04
- Pàgines: [١](https://postext.dev/cookbook/marks-on-rtl-and-vertical-pages/es/p01.webp?v=2e4fd623), [1](https://postext.dev/cookbook/marks-on-rtl-and-vertical-pages/es/p02.webp?v=2e4fd623)
- ![Les mateixes quatre marques en una pàgina àrab composta de dreta a esquerra i en una pàgina japonesa en vertical, cadascuna a la llista amb els seus trossos i el sentit en què corren.](https://postext.dev/cookbook/marks-on-rtl-and-vertical-pages/es/s01.webp?v=2e4fd623)
- Última actualització: 2026-12-04
- Altres idiomes: [en](https://postext.dev/en/cookbook/marks-on-rtl-and-vertical-pages.md), [es](https://postext.dev/es/cookbook/marks-on-rtl-and-vertical-pages.md), [de](https://postext.dev/de/cookbook/marks-on-rtl-and-vertical-pages.md), [el](https://postext.dev/el/cookbook/marks-on-rtl-and-vertical-pages.md), [fr](https://postext.dev/fr/cookbook/marks-on-rtl-and-vertical-pages.md), [it](https://postext.dev/it/cookbook/marks-on-rtl-and-vertical-pages.md), [pt](https://postext.dev/pt/cookbook/marks-on-rtl-and-vertical-pages.md), [ru](https://postext.dev/ru/cookbook/marks-on-rtl-and-vertical-pages.md), [zh](https://postext.dev/zh/cookbook/marks-on-rtl-and-vertical-pages.md), [ja](https://postext.dev/ja/cookbook/marks-on-rtl-and-vertical-pages.md), [ar](https://postext.dev/ar/cookbook/marks-on-rtl-and-vertical-pages.md)

## En poques paraules

Una pàgina en àrab i una altra en japonès, l'una al costat de l'altra, amb les mateixes quatre correccions: un ressaltat, una paraula ratllada, una de substituïda i una nota. A sota, una llista diu com corre cada marca.

## Què compondràs

Dues pàgines, l'una al costat de l'altra, cadascuna en un visor de pàgines: una pàgina àrab sobre el taller d'un enquadernador, composta de dreta a esquerra en Noto Naskh Arabic, i una pàgina japonesa de format bunko sobre un rellotger, en columnes verticals en Noto Serif JP. Totes dues porten les mateixes quatre marques que deixaria una eina de revisió: un ressaltat, una supressió, una substitució i una nota numerada. A la pàgina àrab la substitució es llegeix de dreta a esquerra damunt de les paraules ratllades; a la japonesa el ratllat baixa pel centre de la columna i la substitució s'hi posa dreta al costat. Sota cada pàgina, una llista dona els trossos de cada marca i cap on corre el primer.

**Aquesta recepta respon a:**

- Com marco text en pàgines de dreta a esquerra i en vertical?

## La resposta curta

```js
// script.js, línies 132–145
// layoutAnnotations follows the page's lines: a strike crosses a vertical column down its
// middle, a replacement's text reads right to left on the Arabic page and stands upright on
// the Japanese one, and a note's flag goes to the nearer margin, the foot of a vertical page.
const show = (id, doc, marks, fontFamily) => {
  const shapes = layoutAnnotations(doc, marks, { fontFamily, paper: palette.paper });
  createViewer(document.getElementById(id), {
    document: doc, zoom: 'fit-page', gap: 16, selectable: false, labels: labels.viewer,
    // A layer paints on the page in sheet px, the unit the shapes are in.
    layers: [{ id: 'marks', paint: (ctx, { pageIndex }) =>
      paintAnnotations(ctx, shapes, { pageIndex }) }],
  });
};
show('arabic', arabicDoc, arabicMarks, NASKH);
show('japanese', japaneseDoc, japaneseMarks, MINCHO);
```

## Ingredients

**Ensenya**

- [Marques d'anotació](https://postext.dev/ca/docs/integration-marks.md#marques-danotació): Ressaltats, subratllats, ratllats, substitucions, insercions, notes i requadres col·locats sobre el text de les pàgines, pintats en un canvas o escrits com a SVG sobre imatges de pàgina.
- [Geometria del text (rangs i punts)](https://postext.dev/ca/docs/integration-geometry.md#el-text-a-la-pàgina): rangeRects converteix un rang del Markdown en rectangles sobre les pàgines, i caretAt, wordAt i blockAt converteixen un punt de la pàgina en una posició, una paraula o un bloc de l'original.

**També fa servir**

- [Visor de pàgines (postext-viewer)](https://postext.dev/ca/docs/integration-viewer.md#el-visor-de-pàgines)
- [Text de dreta a esquerra](https://postext.dev/ca/docs/arabic-layout.md#direcció-i-algorisme-bidireccional)
- [L'àrab com a llengua del document](https://postext.dev/ca/docs/arabic-layout.md#començar-un-llibre-en-àrab)
- [Fonts àrabs](https://postext.dev/ca/docs/arabic-layout.md#fonts)
- [Text vertical](https://postext.dev/ca/docs/configuration-page-layout.md#escriptura-vertical)
- [Fonts xineses, japoneses i coreanes](https://postext.dev/ca/docs/configuration-pdf-output.md#fonts-xineses-japoneses-i-coreanes)
- [Fonts abans de compondre](https://postext.dev/ca/docs/configuration-programmatic-usage.md#carregar-les-fonts-abans-de-compondre)
- [Color del paper](https://postext.dev/ca/docs/configuration-page-layout.md#pàgina)
- [Paleta de color semàntica](https://postext.dev/ca/docs/configuration-fonts-colors-viewers.md#paleta-de-colors)
- [Xifres dels números generats](https://postext.dev/ca/docs/configuration-language.md#llengua-del-document)
- [Llibres enquadernats per la dreta](https://postext.dev/ca/docs/configuration-page-layout.md#enquadernació)

**La configuració d'un cop d'ull**

- [`bodyText`](https://postext.dev/ca/docs/configuration-text.md#text-de-cos), [`colorPalette`](https://postext.dev/ca/docs/configuration-fonts-colors-viewers.md#paleta-de-colors), [`footer`](https://postext.dev/ca/docs/configuration-headers-footers.md#capçaleres-i-peus), [`header`](https://postext.dev/ca/docs/configuration-headers-footers.md#capçaleres-i-peus), [`headings`](https://postext.dev/ca/docs/configuration-headings.md#encapçalaments), [`layout`](https://postext.dev/ca/docs/configuration-page-layout.md#disposició), [`locale`](https://postext.dev/ca/docs/configuration-language.md#partició-de-mots), [`page`](https://postext.dev/ca/docs/configuration-page-layout.md#pàgina)

**API**

- [`buildDocument`](https://postext.dev/ca/docs/configuration-programmatic-usage.md#construir-un-document), `createViewer`, `layoutAnnotations`, `loadVerticalAlternates`, `paintAnnotations`, `rangeRects`, [`renderPageToCanvas`](https://postext.dev/ca/docs/configuration-programmatic-usage.md#renderitzar-una-pàgina-en-un-mapa-de-bits), [`withLoadedFonts`](https://postext.dev/ca/docs/configuration-programmatic-usage.md#carregar-les-fonts-abans-de-compondre)

**Tipus de lletra**

- Noto Naskh Arabic (OFL-1.1), Noto Serif JP (OFL-1.1)

## Elaboració

### 1 · Dona a cada pàgina el seu mode d'escriptura

```js
// script.js, línies 39–65
// 'ja' with 'vertical-rl' sets each line top to bottom and the lines from right to left; 'ar'
// sets the text right to left. Nothing in the marks' code changes with either.
const config = { // the Japanese page
  locale: 'ja', // written out, never LANG (gotcha: ja-locale-tag)
  colorPalette, header: none, footer: none,
  page: { sizePreset: 'custom', width: mm(105), height: mm(148), dpi: 200, // 文庫判
    backgroundColor: col('paper'),
    margins: { top: mm(15), bottom: mm(12), left: mm(11), right: mm(11) } },
  layout: { layoutType: 'single', writingMode: 'vertical-rl' },
  bodyText: { fontFamily: MINCHO, fontSize: pt(9.5), lineHeight: pt(16.5), ...ink,
    textAlign: 'justify', firstLineIndent: em(1), indentAfterHeading: true },
  headings: { fontFamily: MINCHO, fontWeight: 600, color: col('vermilion'), levels: [
    { level: 1, fontSize: pt(13), lineSpan: 3, indent: em(2) }, // 3行取り, two characters down
  ] },
};
const arabic = { ...config, // the Arabic page: its own language, trim, face and mode
  locale: 'ar', // written out, never LANG (gotcha: arabic-locale-tag)
  page: { ...config.page, width: mm(120), height: mm(170), dpi: 150,
    margins: { top: mm(18), bottom: mm(18), left: mm(16), right: mm(16) } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: NASKH, fontSize: pt(12.5), lineHeight: pt(21), ...ink,
    textAlign: 'justify', firstLineIndent: em(1.5), indentAfterHeading: false,
    avoidWidows: true, avoidOrphans: true },
  headings: { fontFamily: NASKH, fontWeight: 700, color: col('accent'), levels: [
    { level: 1, fontSize: pt(18), lineHeight: pt(28), marginTop: pt(0), marginBottom: pt(14) },
  ] },
};
```

La pàgina japonesa és la configuració, amb `writingMode: 'vertical-rl'`; l'àrab l'estén i en canvia la llengua, el format i la lletra. `locale: 'ar'` compon el text de dreta a esquerra. El codi de les marques que ve després no pregunta mai en quina pàgina dibuixa.

### 2 · Escriu les marques igual per a totes dues

```js
// script.js, línies 94–105
// A mark is a range of the Markdown. `find` gives the range of a phrase that occurs once.
const find = (text, words) => ({ start: text.indexOf(words),
  end: text.indexOf(words) + words.length });
const marksOn = (text, [lit, cut, [was, now], noted]) => [
  { id: 'h', kind: 'highlight', range: find(text, lit) },
  { id: 's', kind: 'strike', range: find(text, cut) },
  { id: 'r', kind: 'replace', range: find(text, was), text: now },
  { id: 'n', kind: 'note', range: find(text, noted), label: '1' },
];
const arabicMarks = marksOn(arabicText,
  ['أربعين سنة', 'صغيرة', ['خشب الجوز', 'خشب الزان'], 'بورق ياباني رقيق']);
const japaneseMarks = marksOn(markdown, ['七十八歳', '一つずつ', ['丸一日', '二日'], '洗浄液']);
```

Una marca és un interval del Markdown, així que les llistes àrab i japonesa surten de la mateixa funció amb quatre expressions cadascuna. El text de la substitució va en la llengua de la pàgina, i les fonts carreguen també els caràcters d'aquest text; si no, el navegador el posaria en una lletra de reserva.

### 3 · Col·loca les marques i pinta-les sobre cada pàgina

El codi és [la resposta curta](https://postext.dev/ca/cookbook/marks-on-rtl-and-vertical-pages.md#la-resposta-curta) de més amunt. `layoutAnnotations` situa cada marca a partir de les línies de la mateixa pàgina: a la pàgina vertical el ratllat travessa la columna pel centre, un ressaltat que talla un final de columna dona dos trossos i la banderola de la nota va al peu. El visor pinta la pàgina; la seva capa rep un context en px de full, la unitat de les formes, així que `paintAnnotations` les dibuixa tal com arriben. La documentació de les [marques d'anotació](https://postext.dev/ca/docs/integration-marks.md) descriu tots els tipus.

### 4 · Llegeix cap on corre el text

```js
// script.js, línies 149–163
// A quad runs in the line's own order, quad[0] to quad[1]: leftwards on the Arabic page,
// downwards on the Japanese one. A range broken across two lines or columns gives two pieces.
const way = ([a, b]) => (Math.abs(b.x - a.x) > Math.abs(b.y - a.y)
  ? (b.x < a.x ? '←' : '→') : (b.y > a.y ? '↓' : '↑'));
const list = (id, doc, text, marks) => document.getElementById(id).replaceChildren(
  ...marks.map((m) => {
    const pieces = rangeRects(doc, m.range);
    const [li, words] = [document.createElement('li'), document.createElement('bdi')];
    words.textContent = text.slice(m.range.start, m.range.end); // its own direction
    li.append(`${labels.kinds[m.id]} · `, words, ` · ${pieces.length} `
      + `${labels.pieces[pieces.length === 1 ? 0 : 1]} ${way(pieces[0].quad)}`);
    return li;
  }));
list('arabic-pieces', arabicDoc, arabicText, arabicMarks);
list('japanese-pieces', japaneseDoc, markdown, japaneseMarks);
```

`rangeRects` dona un tros per cada tram de línia, i el seu `quad` conserva l'ordre de la línia: de `quad[0]` a `quad[1]` va cap a l'esquerra a la pàgina àrab i cap avall a la japonesa. Un lloc que dibuixa el seu propi subratllat o l'agulla d'un comentari en pren la direcció d'aquí, en lloc de deduir-la de la llengua.

## La recepta completa

Els fitxers d'aquí sota es componen a partir de la carpeta de la recepta, amb el text d'exemple i el kit comú del Receptari ja inclosos. Per executar-los com una sola pàgina, posa l'HTML a `<body>`, el CSS en un element `<style>` i l'script en un `<script type="module">`; o enganxa cadascun al tauler corresponent d'un pen nou de CodePen (el JS com a mòdul). L'script importa postext des d'esm.sh, així que no cal instal·lar ni compilar res.

- Carpeta de la recepta: https://github.com/drnachio/postext/tree/main/cookbook/marks-on-rtl-and-vertical-pages

### index.html

```html
<main id="pages">
  <section id="pair">
    <figure>
      <figcaption id="arabic-label"></figcaption>
      <div id="arabic" class="sheet"></div>
      <ul id="arabic-pieces" class="pieces"></ul>
    </figure>
    <figure>
      <figcaption id="japanese-label"></figcaption>
      <div id="japanese" class="sheet"></div>
      <ul id="japanese-pieces" class="pieces"></ul>
    </figure>
  </section>
</main>
```

### style.css

```css
/* Two viewers side by side, each fitted to its one page, with the host's list under it.
   A viewer fills its container, so each container gets a height. */
#pair {
  display: flex; flex-wrap: wrap; gap: 24px; justify-content: center; align-content: start;
  width: min(880px, 100%); min-height: min(660px, 75vw); /* the card's 4:3 */
}
#pair figure { margin: 0; flex: 1 1 380px; display: grid; gap: 10px; align-content: start; }
#pair figcaption {
  font: 600 12px/1.2 system-ui, sans-serif; letter-spacing: .12em; text-transform: uppercase;
  color: #b9bcc4; text-align: center;
}
.sheet { height: 520px; border-radius: 6px; overflow: hidden; }
.sheet .postext-viewer {
  --pv-background: #16181d;
  --pv-page-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 14px 32px -14px rgb(0 0 0 / .8);
  --pv-focus: #d8a21a;
}
.pieces {
  margin: 0; padding: 0; list-style: none; display: grid; gap: 2px;
  font: 13px/1.45 system-ui, sans-serif; color: #d9dbe0; text-align: center;
  font-variant-numeric: tabular-nums;
}
```

### script.js

```js
// ═══ Postext Cookbook · Nº 222 · The same marks on right-to-left and vertical pages ═════
// https://postext.dev/en/cookbook/marks-on-rtl-and-vertical-pages
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Noto Naskh Arabic, Noto Serif JP (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// An Arabic page set right to left and a Japanese page set in vertical columns, each in
// postext-viewer, each with the same four marks: a highlight, a deletion, a replacement and a
// note. The host writes the marks the same way for both, as ranges of the Markdown; the
// engine turns them to follow each page's lines, and a list under each page says how.
import {
  buildDocument, withLoadedFonts, renderPageToCanvas, loadVerticalAlternates, rangeRects,
} from 'https://esm.sh/postext';
import { layoutAnnotations, paintAnnotations } from 'https://esm.sh/postext/annotate';
import { createViewer } from 'https://esm.sh/postext-viewer';

const LANG = 'es'; // @lang: the language of the labels; both pages are the same in each edition
const RECIPE = 'marks-on-rtl-and-vertical-pages';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: ink on a warm paper, one accent per page, every colour linked by id
const palette = {
  ink: '#1e1b18', // text
  accent: '#2b4766', // the Arabic title's blue
  vermilion: '#a8392b', // 朱: the Japanese title
  paper: '#fbf8f1', // a cream book paper
};
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: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion
const [NASKH, MINCHO] = ['Noto Naskh Arabic', 'Noto Serif JP'];
const ink = { color: col('ink'), boldColor: col('ink'), italicColor: col('ink'),
  referenceColor: col('ink') };
const none = { elements: [] }; // one page each: no running heads

// #region pages: writingMode turns the Japanese lines; the locale sets the Arabic direction
// 'ja' with 'vertical-rl' sets each line top to bottom and the lines from right to left; 'ar'
// sets the text right to left. Nothing in the marks' code changes with either.
const config = { // the Japanese page
  locale: 'ja', // written out, never LANG (gotcha: ja-locale-tag)
  colorPalette, header: none, footer: none,
  page: { sizePreset: 'custom', width: mm(105), height: mm(148), dpi: 200, // 文庫判
    backgroundColor: col('paper'),
    margins: { top: mm(15), bottom: mm(12), left: mm(11), right: mm(11) } },
  layout: { layoutType: 'single', writingMode: 'vertical-rl' },
  bodyText: { fontFamily: MINCHO, fontSize: pt(9.5), lineHeight: pt(16.5), ...ink,
    textAlign: 'justify', firstLineIndent: em(1), indentAfterHeading: true },
  headings: { fontFamily: MINCHO, fontWeight: 600, color: col('vermilion'), levels: [
    { level: 1, fontSize: pt(13), lineSpan: 3, indent: em(2) }, // 3行取り, two characters down
  ] },
};
const arabic = { ...config, // the Arabic page: its own language, trim, face and mode
  locale: 'ar', // written out, never LANG (gotcha: arabic-locale-tag)
  page: { ...config.page, width: mm(120), height: mm(170), dpi: 150,
    margins: { top: mm(18), bottom: mm(18), left: mm(16), right: mm(16) } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: NASKH, fontSize: pt(12.5), lineHeight: pt(21), ...ink,
    textAlign: 'justify', firstLineIndent: em(1.5), indentAfterHeading: false,
    avoidWidows: true, avoidOrphans: true },
  headings: { fontFamily: NASKH, fontWeight: 700, color: col('accent'), levels: [
    { level: 1, fontSize: pt(18), lineHeight: pt(28), marginTop: pt(0), marginBottom: pt(14) },
  ] },
};
// #endregion

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`# 駅前の時計店

駅前の商店街に、間口二間ほどの小さな時計店がある。店主の木村さんは七十八歳で、十五の年からこの店で働いてきた。ガラスの陳列棚には新しい腕時計も並んでいるが、持ち込まれる仕事の大半は修理である。

修理の机は窓際にあり、午後になると西日が差す。木村さんはルーペを片目にはめ、ピンセットで歯車を一つずつ外していく。外した部品は小皿に並べ、洗浄液に浸してから、古い油を筆で落とす。機械式の時計を一個分解して組み直すには、早くても丸一日かかるという。

近ごろは、亡くなった父親の時計を直してほしいという客が増えた。何十年も止まっていた時計でも、部品さえ手に入れば、たいていはまた動き出す。秒針が回り始めると、客は黙って文字盤を見つめている。
`; // content.<lang>.md: the Japanese page, the same in both
const arabicText = String.raw`# ورشة التجليد

في آخر سوق الورّاقين ورشةٌ صغيرة لا تتّسع لأكثر من رجلين وطاولة. يعمل فيها الحاج سليم منذ أربعين سنة، يخيط الكراريس بخيط الكتّان ويشدّ عليها الجلد بعد أن يبلّله بالماء. يقول إن الكتاب الجيّد يُفتح على أي صفحة ويبقى مفتوحًا دون أن تمسكه اليد.

يبدأ يومه بالغراء، فيطبخ النشا بالماء على نار هادئة ويحرّكه حتى يصير كالعسل. ثم يرتّب الكراريس بحسب أرقامها، ويضغطها بين لوحين من خشب الجوز ليلةً كاملة قبل الخياطة. وإذا جاءه كتاب قديم ممزّق الكعب، فكّه ورقةً ورقة، ورمّم أطرافه بورق ياباني رقيق، ثم أعاد خياطته كما خِيط أول مرة.

يقصده طلاب الجامعة بكتبهم المستعملة، والشيوخ بكتب ورثوها عن آبائهم، ولا يرفع السعر على أحد. وحين يسأله الزبائن عن سرّ الصنعة يشير إلى رفّ الأدوات ويقول: الصبر قبل الإبر.
`; // the Arabic page, the same in both

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = {
  'Noto Naskh Arabic': ['400', '700'], // the Arabic text and title, its marks' text
  'Noto Serif JP': ['400', '600'], // the Japanese text and title, its marks' text
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
// #region marks: one list of marks per page, written the same way for both scripts
// A mark is a range of the Markdown. `find` gives the range of a phrase that occurs once.
const find = (text, words) => ({ start: text.indexOf(words),
  end: text.indexOf(words) + words.length });
const marksOn = (text, [lit, cut, [was, now], noted]) => [
  { id: 'h', kind: 'highlight', range: find(text, lit) },
  { id: 's', kind: 'strike', range: find(text, cut) },
  { id: 'r', kind: 'replace', range: find(text, was), text: now },
  { id: 'n', kind: 'note', range: find(text, noted), label: '1' },
];
const arabicMarks = marksOn(arabicText,
  ['أربعين سنة', 'صغيرة', ['خشب الجوز', 'خشب الزان'], 'بورق ياباني رقيق']);
const japaneseMarks = marksOn(markdown, ['七十八歳', '一つずつ', ['丸一日', '二日'], '洗浄液']);
// #endregion

// Each face loads the files of the characters it sets, the marks' own text included.
const withMarks = (text, marks) => text + marks.map((m) => m.text ?? '').join('');
await loadFonts(FONTS, `${arabicText}${markdown}`);
await loadArabicFonts(FONTS, withMarks(arabicText, arabicMarks));
await loadCjkFonts({ [MINCHO]: ['400', '600'] }, withMarks(markdown, japaneseMarks),
  { vertical: true });
const build = (text, settings) => withLoadedFonts(() => buildDocument({ markdown: text }, settings),
  { ...kitFonts(FONTS), text });
const arabicDoc = await build(arabicText, arabic);
const japaneseDoc = await build(markdown, config);
kitStatus(t({ en: 'The same marks, two writing modes', es: 'Las mismas marcas, dos escrituras' }));

// #region labels: what a screen reader hears, and the list's words, in the edition's language
const labels = t({
  en: { viewer: {}, // the viewer speaks English unless told otherwise
    kinds: { h: 'Highlight', s: 'Delete', r: 'Replace', n: 'Note' },
    pieces: ['piece', 'pieces'] },
  es: { viewer: { viewer: 'Páginas del documento', page: 'Página {n} de {count}' },
    kinds: { h: 'Resaltar', s: 'Suprimir', r: 'Sustituir', n: 'Nota' },
    pieces: ['trozo', 'trozos'] },
});
// #endregion

// #region answer: the marks laid out on each page, painted in a layer of the viewer
// layoutAnnotations follows the page's lines: a strike crosses a vertical column down its
// middle, a replacement's text reads right to left on the Arabic page and stands upright on
// the Japanese one, and a note's flag goes to the nearer margin, the foot of a vertical page.
const show = (id, doc, marks, fontFamily) => {
  const shapes = layoutAnnotations(doc, marks, { fontFamily, paper: palette.paper });
  createViewer(document.getElementById(id), {
    document: doc, zoom: 'fit-page', gap: 16, selectable: false, labels: labels.viewer,
    // A layer paints on the page in sheet px, the unit the shapes are in.
    layers: [{ id: 'marks', paint: (ctx, { pageIndex }) =>
      paintAnnotations(ctx, shapes, { pageIndex }) }],
  });
};
show('arabic', arabicDoc, arabicMarks, NASKH);
show('japanese', japaneseDoc, japaneseMarks, MINCHO);
// #endregion

// #region pieces: what rangeRects gives for each mark, and which way its first piece runs
// A quad runs in the line's own order, quad[0] to quad[1]: leftwards on the Arabic page,
// downwards on the Japanese one. A range broken across two lines or columns gives two pieces.
const way = ([a, b]) => (Math.abs(b.x - a.x) > Math.abs(b.y - a.y)
  ? (b.x < a.x ? '←' : '→') : (b.y > a.y ? '↓' : '↑'));
const list = (id, doc, text, marks) => document.getElementById(id).replaceChildren(
  ...marks.map((m) => {
    const pieces = rangeRects(doc, m.range);
    const [li, words] = [document.createElement('li'), document.createElement('bdi')];
    words.textContent = text.slice(m.range.start, m.range.end); // its own direction
    li.append(`${labels.kinds[m.id]} · `, words, ` · ${pieces.length} `
      + `${labels.pieces[pieces.length === 1 ? 0 : 1]} ${way(pieces[0].quad)}`);
    return li;
  }));
list('arabic-pieces', arabicDoc, arabicText, arabicMarks);
list('japanese-pieces', japaneseDoc, markdown, japaneseMarks);
// #endregion

document.getElementById('arabic-label').textContent = t({ en: 'Arabic · right to left',
  es: 'Árabe · de derecha a izquierda' });
document.getElementById('japanese-label').textContent = t({ en: 'Japanese · vertical',
  es: 'Japonés · en vertical' });

// ─── 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 v3 ── the same in every recipe · postext.dev/cookbook
// Postext loads the faces a config asks for before layout and asks the kit
// for Fontsource's files, the ones the PDF embeds too.

/** buildDocumentWithFonts' options: the resolver, and FONTS' faces loaded
 *  with the config's. FONTS = { 'Family Name': ['400', '400i', '700'] }. */
function kitFonts(FONTS = {}) {
  const faces = Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) =>
    ({ family, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' })));
  return { resolve: fontsourceResolver, faces };
}

/** A face's files with their ranges: latin, then latin-ext and greek when
 *  `text` needs them (kitSubsetsFor). Null for a face Fontsource lacks. */
async function fontsourceResolver(family, weight, style, { text = '' } = {}) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  if (meta && !(await fontsourceWeights(family, style)).includes(weight)) return null;
  kitStatus('Loading fonts…');
  const at = await fontsourceAt(id);
  return ['latin', ...kitSubsetsFor(text, meta)].map((subset) => ({
    source: `${at}files/${id}-${subset}-${weight}-${style}.woff2`,
    unicodeRange: kitRanges()[subset],
  }));
}

/** Each file's unicode-range (a function: the kit runs after the pen's code). */
function kitRanges() {
  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',
  };
}

/** For the cjk, arabic and comics blocks: loads `faces` (as FONTS) for the
 *  sample `text`; `optional` skips a face Fontsource lacks. Files are added in
 *  the order asked, the last winning a shared character. Resolves to the count. */
async function loadFonts(faces, text = '', { optional = false } = {}) {
  kitStatus('Loading fonts…');
  const ranges = kitRanges();
  const jobs = [];
  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 at = fontsourceAt(id);
    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 && (await fontsourceWeights(family, style)).includes(weight))) continue;
      for (const subset of subsets) {
        const url = `${await at}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().catch(() => {
          if (subset === 'latin' && !optional) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
        }));
      }
    }
  }
  const ready = await Promise.all(jobs).catch((error) => { kitFail(error); throw error; });
  return ready.filter((face) => face && document.fonts.add(face)).length;
}

/** A loaded FontFace covers this face (fonts.check() says yes to any family). */
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, '-'); }

/** A package's folder at the one version @5 names now (#766). */
function fontsourceAt(id, u = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@`) {
  return (fontsourceAt.c ??= {})[id] ??= fetch(u + '5/package.json').then((r) => r.json())
    .then((p) => p.version || 5, () => 5).then((v) => `${u}${v}/`);
}

/** The family's Fontsource metadata (weights, styles, subsets), or null. */
function fontsourceMeta(family, id = fontsourceId(family)) {
  return (fontsourceMeta.c ??= {})[id] ??= fetch(`https://api.fontsource.org/v1/fonts/${id}`)
    .then((res) => (res.ok ? res.json() : null), () => null);
}

/** The weights the package ships in `style`: the API pairs none (no Libre
 *  Caslon 700 italic file), so italics are read from latin-italic.css. */
function fontsourceWeights(family, style, id = fontsourceId(family)) {
  return (fontsourceWeights.c ??= {})[id + style] ??= fontsourceMeta(family).then(async (m) => {
    if (!m?.styles.includes(style)) return m ? [] : [400, 700];
    const css = style === 'italic' ? await fetch(`${await fontsourceAt(id)}latin-italic.css`).then((r) => (r.ok ? r.text() : ''), () => '') : '';
    const w = [...css.matchAll(/weight: (\d+)/g)].map((x) => +x[1]);
    return w.length ? w : m.weights;
  });
}

// ─── Kit · viewer v2 ── 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. Other options go to renderPageToCanvas. */
function showPages(docs, { title, width = 460, ...render } = {}) {
  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, { ...render, 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 · cjk v2 ── 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 = `${id}/${weight}${style === 'italic' ? '-italic' : ''}.css`;
  if (!cjkSlices.cache.has(css)) {
    let at;
    cjkSlices.cache.set(css, fontsourceAt(id).then((a) => fetch(at = a + css.slice(id.length + 1)))
      .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], at).href, range, ranges };
      }).reverse()));
  }
  return cjkSlices.cache.get(css);
}

/** The file of `slices` the screen sets code point `cp` in, if any: the
 *  last one loadCjkFonts adds whose range holds it. A numbered file that
 *  repeats a letter of latin is added after latin, and wins it. */
function cjkSliceFor(slices, cp) {
  const holds = (slice) => slice.ranges.some(([lo, hi]) => cp >= lo && cp <= hi);
  return slices.reduce((last, slice) => (holds(slice) ? slice : last), undefined);
}

/** 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 the engine's later round
 *  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 the
 *  screen set its pages' characters in (`request.codePoints`), each marked
 *  with its unicode-range and its place in the order loadCjkFonts added
 *  them: postext-pdf sets a character two files hold in the one added
 *  last, as the browser does. 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.map(async (slice, order) => {
    if (!picked.has(slice)) return null;
    const res = await fetch(slice.url);
    if (!res.ok) throw new Error(`Fontsource file ${slice.url} (${res.status})`);
    const bytes = await decompressWoff2(new Uint8Array(await res.arrayBuffer()));
    return Object.assign(bytes, { unicodeRange: slice.range, order });
  })).then((files) => files.filter(Boolean));
}

/** 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, each marked with its unicode-range and its place in that order:
 *  the PDF sets a character in the file the browser took it from. 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 = `${await fontsourceAt(id)}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)]);
  const ranges = kitRanges();
  return ext ? [Object.assign(latin, { unicodeRange: ranges.latin, order: 0 }),
    Object.assign(ext, { unicodeRange: ranges['latin-ext'], order: 1 })] : 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 v2 ── 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. */
async function arabicFileUrl(family, weight, style) {
  const id = fontsourceId(family);
  return `${await fontsourceAt(id)}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 the engine's later round 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(${await 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: ā ḥ ʿ), each marked with its
 *  unicode-range and its place in the order the screen added them (latin
 *  and latin-ext by loadFonts, then arabic): the arabic file also has a
 *  space and brackets, which the browser takes from latin, the file whose
 *  range holds them, and postext-pdf follows it. 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 subsets = !wanted.length || wanted.some(inArabicRange) ? ['arabic', 'latin'] : ['latin'];
  if (meta.subsets.includes('latin-ext') && wanted.some((cp) => /[Ā-˿Ḁ-ỿ]/u.test(String.fromCodePoint(cp)))) {
    subsets.push('latin-ext');
  }
  const at = await fontsourceAt(id);
  return Promise.all(subsets.map(async (subset) => {
    const url = `${at}files/${id}-${subset}-${w}-${s}.woff2`;
    const res = await fetch(url);
    if (!res.ok) throw new Error(`Fontsource file ${url} (${res.status})`);
    const bytes = await decompressWoff2(new Uint8Array(await res.arrayBuffer()));
    return Object.assign(bytes, { unicodeRange: subset === 'arabic' ? arabicRange() : kitRanges()[subset],
      order: ['latin', 'latin-ext', 'greek', 'arabic'].indexOf(subset) });
  }));
}

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

## Variants

### Deixa que el visor col·loqui les marques

L'opció `annotations` del visor fa la mateixa col·locació i la mateixa pintura, i a més anomena cada marca per als lectors de pantalla i la comunica a `annotationclick`.

```diff
-  const shapes = layoutAnnotations(doc, marks, { fontFamily, paper: palette.paper });
   createViewer(document.getElementById(id), {
     document: doc, zoom: 'fit-page', gap: 16, selectable: false, labels: labels.viewer,
-    // A layer paints on the page in sheet px, the unit the shapes are in.
-    layers: [{ id: 'marks', paint: (ctx, { pageIndex }) =>
-      paintAnnotations(ctx, shapes, { pageIndex }) }],
+    annotations: marks, marks: { fontFamily, paper: palette.paper }, // named for readers too
   });
```

### Compon una novel·la vertical sencera

[Una novel·la en format bunko, en vertical i amb furigana](https://postext.dev/ca/cookbook/bunko-novel-furigana.md) compon un llibre japonès en la mateixa pàgina, amb rubí, retícula de caràcters i capçaleres al marge exterior.

## Errors freqüents

- **Etiqueta un llibre àrab 'ar', no amb LANG.** Les edicions d'una recepta són en i es, però una mostra àrab és àrab en totes dues: `locale: LANG` la compondria d'esquerra a dreta, l'enquadernaria per l'esquerra, numeraria les seves pàgines 1 2 3 i anomenaria Figure o Figura les seves figures. Des de postext 1.30 l'etiqueta és a més la llengua en què es compon el text (en què es mesura, es pinta i s'incrusta), de manera que sota una etiqueta anglesa o castellana una font com Markazi Text no dibuixa les formes àrabs de les cometes angulars i dels punts, i les línies es parteixen per un altre lloc. Escriu tu l'etiqueta: 'ar' (xifres aràbigo-índiques, la convenció del Màixriq), una regió com 'ar-EG' o 'ar-SA', o 'ar-MA', 'ar-DZ' o 'ar-TN' per a una edició magribina amb xifres europees. Una pàgina llatina que només cita àrab conserva el seu propi locale.
- **Etiqueta un text japonès 'ja', mai zh-Hans ni LANG.** Les edicions d'una recepta són en i es, però una mostra japonesa és japonesa en totes dues: `locale: LANG` l'etiquetaria com a anglès o castellà, i una etiqueta xinesa la compondria amb les regles xineses (puntuació Kaiming, kana petit lliure de començar línia, 图 en lloc de 図, formes xineses dels caràcters al PDF). Des de postext 1.30 l'etiqueta és a més la llengua en què es compon el text (en què es mesura, es pinta i s'incrusta), de manera que qualsevol etiqueta que no sigui 'ja' dona altres formes de glif que les japoneses (les xineses, amb una etiqueta xinesa) i altres talls de línia. Escriu 'ja': tria la regió del Japó (tall i puntuació de la JLReq, punts de sèsam, repartiment dels furigana, etiquetes 図 i 表) i desactiva la partició de mots. El lint falla un text amb kana sota una etiqueta zh o ko.
- **Les fonts àrabs necessiten el seu fitxer arabic, amb el bloc arabic.** Fontsource serveix Amiri, Noto Naskh Arabic o Scheherazade New en un fitxer per subconjunt, i les lletres àrabs són al fitxer arabic. loadFonts només baixa latin (i latin-ext), de manera que a la pantalla l'àrab surt d'una font del sistema i es mesura malament, i fontsourceProvider lliura al PDF aquell fitxer latin, que imprimeix caixes buides. Afegeix el bloc arabic del kit, crida loadArabicFonts(FONTS, markdown) després de loadFonts, amb tots els pesos que les pàgines fan servir en àrab llistats a FONTS, i passa a renderToPdf fontProvider: arabicPdfProvider.
- **Les fonts xineses es carreguen per fragments, amb el bloc cjk.** Fontsource serveix una família xinesa, japonesa o coreana en un centenar de fitxers per pes, cadascun amb un interval de caràcters. loadFonts només baixa el fitxer latin, així que a la pantalla els caràcters xinesos surten d'una font del sistema i es mesuren malament, i fontsourceProvider lliura al PDF aquest fitxer latin, que els imprimeix com a caixes buides. Afegeix el bloc cjk del kit, crida loadCjkFonts(FONTS, markdown) després de loadFonts (una vegada per veu, amb el text que compon, si el llibre fa servir diverses fonts xineses) i passa a renderToPdf fontProvider: cjkPdfProvider: tots dos agafen els fitxers que contenen els caràcters del text.

## Crèdits

- Recepta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Tipus de lletra: Noto Naskh Arabic (OFL-1.1), Noto Serif JP (OFL-1.1)
- Codi: MIT · Contingut d'exemple: CC-BY-4.0

## Relacionades

- [Núm. 215 · Notes al marge, amb una finestra col·locada des de la pàgina](https://postext.dev/ca/cookbook/margin-notes-with-popovers.md): Les notes tenyeixen les paraules i les assenyalen al marge; en prémer-les, s'obren en una finestra col·locada sota les paraules amb rangeRects i pageToClient. · Nivell 2 (Intermedi) · Catàlegs
- [Núm. 214 · Marques de correcció: ratllar, substituir i inserir](https://postext.dev/ca/cookbook/proofreading-marks-on-pages.md): Les correccions d'un editor sobre una pàgina de conte a postext-viewer: paraules ratllades, substitucions escrites a sobre i signes d'inserció. · Nivell 2 (Intermedi) · Narrativa, teatre i prosa literària
- [Núm. 220 · Marques com a SVG sobre imatges de pàgina, per a un informe](https://postext.dev/ca/cookbook/marks-as-svg-over-pages.md): layoutAnnotations i annotationsSvg posen les marques d'un corrector sobre imatges de pàgina, sense visor: un informe que un CMS envia per correu. · Nivell 2 (Intermedi) · Diaris i butlletins
