# Les mêmes marques sur pages de droite à gauche et verticales

> Une seule façon d'écrire des marques pour une page arabe de droite à gauche et une page japonaise en colonnes verticales : layoutAnnotations suit leurs lignes.

- Version HTML: https://postext.dev/fr/cookbook/marks-on-rtl-and-vertical-pages
- Recette Nº 222 · Intégration dans un CMS · Niveau 3 (Avancé) · Sorties: Canvas, Contrôles en direct
- Genres: Tous genres
- Nécessite postext ≥ 1.103.0 · testée avec 1.103.1 le 2026-12-04
- Pages: [١](https://postext.dev/cookbook/marks-on-rtl-and-vertical-pages/en/p01.webp?v=3cfd2386), [1](https://postext.dev/cookbook/marks-on-rtl-and-vertical-pages/en/p02.webp?v=3cfd2386)
- ![Les quatre mêmes marques sur une page arabe composée de droite à gauche et sur une page japonaise composée verticalement, chacune listée avec ses morceaux et le sens dans lequel ils courent.](https://postext.dev/cookbook/marks-on-rtl-and-vertical-pages/en/s01.webp?v=3cfd2386)
- Dernière mise à jour: 2026-12-04
- Autres langues: [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), [ca](https://postext.dev/ca/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), [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 bref

Une page en arabe et une page en japonais côte à côte, chacune avec les quatre mêmes corrections : un surlignage, un mot barré, un mot remplacé et une note. Une liste sous chaque page dit comment court chaque marque.

## Ce que vous allez composer

Deux pages côte à côte, chacune dans une visionneuse : une page arabe sur l'atelier d'un relieur, composée de droite à gauche en Noto Naskh Arabic, et une page japonaise au format bunko sur un horloger, en colonnes verticales en Noto Serif JP. Chacune porte les quatre mêmes marques qu'un outil de relecture laisserait : un surlignage, une suppression, un remplacement et une note numérotée. Sur la page arabe, le remplacement se lit de droite à gauche au-dessus des mots barrés ; sur la page japonaise, le trait descend au milieu de la colonne et le remplacement se tient debout à côté. Sous chaque page, une liste donne les morceaux de chaque marque et le sens du premier.

**Cette recette répond à:**

- Comment marquer du texte sur des pages de droite à gauche et verticales ?

## La réponse courte

```js
// script.js, lignes 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);
```

## Ingrédients

**Enseigne**

- [Marques d’annotation](https://postext.dev/fr/docs/integration-marks.md#marques-dannotation): Surlignages, soulignements, biffures, remplacements, insertions, notes et cadres placés sur le texte des pages, peints sur un canvas ou écrits en SVG par-dessus des images de pages.
- [Géométrie du texte (plages et points)](https://postext.dev/fr/docs/integration-geometry.md#le-texte-sur-la-page): rangeRects transforme une plage du Markdown en rectangles sur les pages ; caretAt, wordAt et blockAt ramènent un point de la page à une position, un mot ou un bloc de la source.

**Utilise aussi**

- [Visionneuse de pages (postext-viewer)](https://postext.dev/fr/docs/integration-viewer.md#la-visionneuse-de-pages)
- [Texte de droite à gauche](https://postext.dev/fr/docs/arabic-layout.md#sens-décriture-et-algorithme-bidirectionnel)
- [L’arabe comme langue du document](https://postext.dev/fr/docs/arabic-layout.md#commencer-un-livre-en-arabe)
- [Polices arabes](https://postext.dev/fr/docs/arabic-layout.md#polices)
- [Texte vertical](https://postext.dev/fr/docs/configuration-page-layout.md#écriture-verticale)
- [Polices chinoises, japonaises et coréennes](https://postext.dev/fr/docs/configuration-pdf-output.md#polices-chinoises-japonaises-et-coréennes)
- [Les polices avant la mise en page](https://postext.dev/fr/docs/configuration-programmatic-usage.md#charger-les-polices-avant-la-mise-en-page)
- [Couleur du papier](https://postext.dev/fr/docs/configuration-page-layout.md#page)
- [Palette de couleurs sémantique](https://postext.dev/fr/docs/configuration-fonts-colors-viewers.md#palette-de-couleurs)
- [Chiffres des nombres générés](https://postext.dev/fr/docs/configuration-language.md#langue-du-document)
- [Livres reliés à droite](https://postext.dev/fr/docs/configuration-page-layout.md#reliure)

**La configuration en un coup d’œil**

- [`bodyText`](https://postext.dev/fr/docs/configuration-text.md#texte-courant), [`colorPalette`](https://postext.dev/fr/docs/configuration-fonts-colors-viewers.md#palette-de-couleurs), [`footer`](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page), [`header`](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page), [`headings`](https://postext.dev/fr/docs/configuration-headings.md#titres), [`layout`](https://postext.dev/fr/docs/configuration-page-layout.md#mise-en-page), [`locale`](https://postext.dev/fr/docs/configuration-language.md#césure), [`page`](https://postext.dev/fr/docs/configuration-page-layout.md#page)

**API**

- [`buildDocument`](https://postext.dev/fr/docs/configuration-programmatic-usage.md#construire-un-document), `createViewer`, `layoutAnnotations`, `loadVerticalAlternates`, `paintAnnotations`, `rangeRects`, [`renderPageToCanvas`](https://postext.dev/fr/docs/configuration-programmatic-usage.md#rendre-une-page-en-bitmap), [`withLoadedFonts`](https://postext.dev/fr/docs/configuration-programmatic-usage.md#charger-les-polices-avant-la-mise-en-page)

**Caractères**

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

## Préparation

### 1 · Donner à chaque page son mode d'écriture

```js
// script.js, lignes 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 page japonaise est la configuration, avec `writingMode: 'vertical-rl'` ; la page arabe la reprend et change la langue, le format et le caractère. `locale: 'ar'` compose le texte de droite à gauche. Le code des marques qui suit ne demande jamais sur quelle page il dessine.

### 2 · Écrire les marques de la même façon pour les deux

```js
// script.js, lignes 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, ['七十八歳', '一つずつ', ['丸一日', '二日'], '洗浄液']);
```

Une marque est une plage du Markdown : les listes arabe et japonaise sortent donc de la même fonction, avec quatre expressions chacune. Le texte du remplacement est dans la langue de la page, et les polices chargent aussi ses caractères ; sinon le navigateur le composerait dans une police de secours.

### 3 · Placer les marques et les peindre sur chaque page

Le code est [la réponse courte](https://postext.dev/fr/cookbook/marks-on-rtl-and-vertical-pages.md#la-réponse-courte) plus haut. `layoutAnnotations` place chaque marque d'après les lignes de la page : sur la page verticale, le trait barre la colonne en son milieu, un surlignage coupé par une fin de colonne donne deux morceaux et le drapeau de la note va au pied. La visionneuse peint la page ; sa couche reçoit un contexte en px de feuille, l'unité des formes, donc `paintAnnotations` les dessine telles quelles. La documentation des [marques d'annotation](https://postext.dev/fr/docs/integration-marks.md) décrit chaque type.

### 4 · Lire dans quel sens court le texte

```js
// script.js, lignes 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` donne un morceau par tronçon de ligne, et son `quad` garde l'ordre de la ligne : de `quad[0]` à `quad[1]`, il va vers la gauche sur la page arabe et vers le bas sur la page japonaise. Un site qui dessine son propre soulignement ou l'épingle d'un commentaire prend le sens là, au lieu de le deviner d'après la langue.

## La recette complète

Les fichiers ci-dessous sont composés à partir du dossier de la recette, avec le texte d’exemple et le kit commun des Recettes déjà inclus. Pour les exécuter comme une seule page, placez le HTML dans `<body>`, le CSS dans un élément `<style>` et le script dans un `<script type="module">` ; ou collez chacun dans le panneau correspondant d’un nouveau pen CodePen (le JS en tant que module). Le script importe postext depuis esm.sh : il n’y a rien à installer ni à compiler.

- Dossier de la recette: 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 = 'en'; // @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 ───────────────────────────────────────────────────────────────────────
```

## Variantes

### Laisser la visionneuse placer les marques

L'option `annotations` de la visionneuse fait le même placement et la même peinture, nomme en plus chaque marque pour les lecteurs d'écran et la signale par `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
   });
```

### Composer tout un roman vertical

[Un roman bunko composé à la verticale, avec furigana](https://postext.dev/fr/cookbook/bunko-novel-furigana.md) compose un livre japonais sur la même page, avec ruby, grille de caractères et titres courants le long de la marge extérieure.

## Erreurs fréquentes

- **Balisez un livre arabe 'ar', pas avec LANG.** Les éditions d’une recette sont en et es, mais un exemple arabe est en arabe dans les deux : `locale: LANG` le composerait de gauche à droite, le relierait à gauche, numéroterait ses pages 1 2 3 et légenderait ses figures Figure ou Figura. Depuis postext 1.30, la balise est aussi la langue dans laquelle le texte est mis en forme (mesuré, peint et incorporé) : sous une balise anglaise ou espagnole, une police comme Markazi Text ne dessine pas les formes arabes de ses guillemets et de ses points, et les lignes se coupent ailleurs. Écrivez la balise vous-même : 'ar' (chiffres arabes orientaux, convention du Machrek), une région comme 'ar-EG' ou 'ar-SA', ou 'ar-MA', 'ar-DZ' ou 'ar-TN' pour une édition maghrébine avec chiffres européens. Une page latine qui ne fait que citer de l’arabe garde sa propre langue.
- **Balisez un texte japonais 'ja', jamais zh-Hans ni LANG.** Les éditions d’une recette sont en et es, mais un exemple japonais est en japonais dans les deux : `locale: LANG` le baliserait en anglais ou en espagnol, et une balise chinoise le composerait selon les règles chinoises (ponctuation Kaiming, petits kana libres de commencer une ligne, 图 pour 図, formes de glyphes chinoises dans le PDF). Depuis postext 1.30, la balise est aussi la langue dans laquelle le texte est mis en forme (mesuré, peint et incorporé) : toute balise autre que 'ja' donne d’autres formes de glyphes que les japonaises (les chinoises sous une balise chinoise) et d’autres coupures de ligne. Écrivez 'ja' : elle choisit la région Japon (coupure des lignes et ponctuation JLReq, points d’emphase sésame, espacement des furigana, étiquettes 図 et 表) et désactive la césure. Le lint fait échouer un texte contenant des kana sous une balise zh ou ko.
- **Les polices arabes ont besoin de leur fichier arabic, avec le bloc arabic.** Fontsource sert Amiri, Noto Naskh Arabic ou Scheherazade New sous la forme d’un fichier par sous-ensemble, et les lettres arabes se trouvent dans le fichier arabic. loadFonts ne récupère que latin (et latin-ext) : à l’écran, l’arabe vient d’une police système et est mal mesuré, et fontsourceProvider remet ce fichier latin au PDF, qui imprime des cases vides. Listez le bloc arabic du kit, appelez loadArabicFonts(FONTS, markdown) après loadFonts, avec dans FONTS chaque graisse que les pages composent en arabe, et donnez à renderToPdf fontProvider: arabicPdfProvider.
- **Les polices chinoises se chargent par tranches, avec le bloc cjk.** Fontsource sert une famille chinoise, japonaise ou coréenne sous la forme d’une centaine de fichiers par graisse, chacun couvrant une plage de caractères. loadFonts ne récupère que le fichier latin : à l’écran, les caractères han viennent d’une police système et sont mal mesurés, et fontsourceProvider remet ce fichier latin au PDF, qui les imprime en cases vides. Listez le bloc cjk du kit, appelez loadCjkFonts(FONTS, markdown) après loadFonts (une fois par voix, avec le texte qu’elle compose, quand le livre utilise plusieurs polices CJK) et donnez à renderToPdf fontProvider: cjkPdfProvider : les deux prennent les fichiers qui contiennent les caractères du texte.

## Crédits

- Recette: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Caractères: Noto Naskh Arabic (OFL-1.1), Noto Serif JP (OFL-1.1)
- Code: MIT · Contenu d’exemple: CC-BY-4.0

## Recettes liées

- [Nº 215 · Notes en marge, avec une bulle placée depuis la page](https://postext.dev/fr/cookbook/margin-notes-with-popovers.md): Les notes teintent leurs mots et les signalent dans la marge ; un clic ouvre la note dans une bulle placée sous les mots avec rangeRects et pageToClient. · Niveau 2 (Intermédiaire) · Catalogues
- [Nº 214 · Signes de correction : barrer, remplacer et insérer](https://postext.dev/fr/cookbook/proofreading-marks-on-pages.md): Les corrections d'un éditeur sur une page de nouvelle dans postext-viewer : mots barrés, remplacements écrits au-dessus et signes d'insertion. · Niveau 2 (Intermédiaire) · Fiction, théâtre et prose littéraire
- [Nº 220 · Des marques en SVG sur des images de page, pour un rapport](https://postext.dev/fr/cookbook/marks-as-svg-over-pages.md): layoutAnnotations et annotationsSvg posent les marques d'un correcteur sur des images de page, sans visionneuse : un rapport qu'un CMS envoie par courriel. · Niveau 2 (Intermédiaire) · Journaux et lettres d’information
