# 右から左のページと縦組みのページに同じ印

> 右から左に組むアラビア語のページと縦組みの日本語のページに、同じ書き方で印を付ける。layoutAnnotations が各ページの行に沿わせる。

- HTML版: https://postext.dev/ja/cookbook/marks-on-rtl-and-vertical-pages
- レシピ No. 222 · CMSへの組み込み · 難易度 3 (上級) · 出力: Canvas, ライブ操作
- ジャンル: すべてのジャンル
- 必要なもの postext ≥ 1.103.0 · テスト環境 1.103.1 ／テスト日 2026-12-04
- ページ: [١](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)
- ![右から左に組んだアラビア語のページと縦組みの日本語のページに付けた同じ四つの印。それぞれの断片と、その進む向きが一覧になっている。](https://postext.dev/cookbook/marks-on-rtl-and-vertical-pages/en/s01.webp?v=3cfd2386)
- 最終更新: 2026-12-04
- 他の言語: [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), [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), [ar](https://postext.dev/ar/cookbook/marks-on-rtl-and-vertical-pages.md)

## かんたんな説明

アラビア語のページと日本語のページを並べ、どちらにも同じ四つの直しを入れます。強調、消した語、差し替えた語、メモです。各ページの下のリストは、印がいくつの片に分かれ、どちらへ向かうかを示します。

## できあがり

2ページを並べ、それぞれページビューアーに載せます。製本工房についてのアラビア語のページは Noto Naskh Arabic で右から左に、時計の修理職人についての文庫判の日本語のページは Noto Serif JP で縦組みにします。どちらのページにも、校閲ツールが残すのと同じ四つの印があります。強調、削除、差し替え、番号付きのメモです。アラビア語のページでは、差し替えの文字列が消した語の上に右から左へ読めるように置かれます。日本語のページでは、消し線が行の中央を縦に通り、差し替えの文字列はその横に縦に立ちます。各ページの下のリストは、印ごとの片の数と、最初の片の向きを示します。

**このレシピが答える問い:**

- 右から左に書くページや縦組みのページで、テキストに印を付けるには？

## 手短な答え

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

## 材料

**学べること**

- [注釈の印](https://postext.dev/ja/docs/integration-marks.md#注釈のマーク): ハイライト、下線、取り消し線、置換、挿入、メモ、囲みを、ページのテキストに合わせて配置し、canvasに描くか、ページ画像に重ねるSVGとして書き出します。
- [テキストの位置（範囲と点）](https://postext.dev/ja/docs/integration-geometry.md#ページ上のテキスト): rangeRectsはMarkdownの範囲をページ上の矩形に変え、caretAt、wordAt、blockAtはページ上の点を原稿の位置、単語、ブロックに戻します。

**ほかに使うもの**

- [ページビューアー（postext-viewer）](https://postext.dev/ja/docs/integration-viewer.md#ページビューアー)
- [右から左のテキスト](https://postext.dev/ja/docs/arabic-layout.md#書字方向と双方向アルゴリズム)
- [文書の言語としてのアラビア語](https://postext.dev/ja/docs/arabic-layout.md#アラビア語の本の始め方)
- [アラビア語のフォント](https://postext.dev/ja/docs/arabic-layout.md#フォント)
- [縦組み](https://postext.dev/ja/docs/configuration-page-layout.md#縦組み)
- [中国語・日本語・韓国語のフォント](https://postext.dev/ja/docs/configuration-pdf-output.md#中国語日本語韓国語のフォント)
- [レイアウト前のフォント読み込み](https://postext.dev/ja/docs/configuration-programmatic-usage.md#レイアウトの前にフォントを読み込む)
- [用紙の色](https://postext.dev/ja/docs/configuration-page-layout.md#ページ)
- [セマンティックカラーパレット](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット)
- [生成される番号の数字](https://postext.dev/ja/docs/configuration-language.md#文書の言語)
- [右綴じの本](https://postext.dev/ja/docs/configuration-page-layout.md#綴じ)

**設定の一覧**

- [`bodyText`](https://postext.dev/ja/docs/configuration-text.md#本文), [`colorPalette`](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット), [`footer`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`header`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`headings`](https://postext.dev/ja/docs/configuration-headings.md#見出し), [`layout`](https://postext.dev/ja/docs/configuration-page-layout.md#レイアウト), [`locale`](https://postext.dev/ja/docs/configuration-language.md#ハイフネーション), [`page`](https://postext.dev/ja/docs/configuration-page-layout.md#ページ)

**API**

- [`buildDocument`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#文書のビルド), `createViewer`, `layoutAnnotations`, `loadVerticalAlternates`, `paintAnnotations`, `rangeRects`, [`renderPageToCanvas`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#ページをビットマップに描画する), [`withLoadedFonts`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#レイアウトの前にフォントを読み込む)

**書体**

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

## 作り方

### 1 · ページごとに書字方向を決める

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

日本語のページが設定そのもので、`writingMode: 'vertical-rl'` を持ちます。アラビア語のページはそれを広げ、言語と判型と書体を変えます。`locale: 'ar'` で本文は右から左に組まれます。この後の印のコードは、どちらのページに描いているかを一度も尋ねません。

### 2 · 両方のページの印を同じ形で書く

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

印は Markdown の範囲なので、アラビア語と日本語のリストは、それぞれ四つの語句から同じ関数で作れます。差し替えの文字列はそのページの言語で書き、フォントはその文字も読み込みます。読み込まないと、ブラウザーは代替フォントで表示してしまいます。

### 3 · 印を配置し、各ページの上に描く

コードは上の[手短な答え](https://postext.dev/ja/cookbook/marks-on-rtl-and-vertical-pages.md#手短な答え)です。`layoutAnnotations` はページ自身の行から各印の位置を決めます。縦組みのページでは消し線が行の中央を通り、行末をまたぐ強調は二つの片になり、メモの旗は地の側へ行きます。ビューアーはページを描き、そのレイヤーは用紙 px 単位のコンテキストを受け取ります。形と同じ単位なので、`paintAnnotations` はそのまま描けます。各種類の説明は[注釈のマーク](https://postext.dev/ja/docs/integration-marks.md)の文書にあります。

### 4 · 文字の進む向きを読む

```js
// script.js, 行 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` は行の区間ごとに一つの片を返し、その `quad` は行の順序を保ちます。`quad[0]` から `quad[1]` へは、アラビア語のページでは左へ、日本語のページでは下へ向かいます。独自の下線やコメントのピンを描くサイトは、言語から推し量るのではなく、ここから向きを取ります。

## レシピの全体

下のファイルはレシピのフォルダーから合成したもので、サンプルのテキストとレシピ集の共通キットを埋め込んであります。1つのページとして動かすには、HTMLを`<body>`に、CSSを`<style>`要素に、スクリプトを`<script type="module">`に入れます。新しいCodePenのpenの各パネルに貼り付けてもかまいません（JSはモジュールとして）。スクリプトはesm.shからpostextを読み込むので、インストールもビルドも要りません。

- レシピのフォルダー: 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 ───────────────────────────────────────────────────────────────────────
```

## アレンジ

### 印の配置をビューアーに任せる

ビューアーの `annotations` オプションは同じ配置と描画を行い、さらに各印にスクリーンリーダー用の名前を付け、`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
   });
```

### 縦組みの小説を一冊組む

[ルビ付きの縦組み文庫](https://postext.dev/ja/cookbook/bunko-novel-furigana.md) は、同じ判型に日本語の本を組みます。ルビ、字詰めのグリッド、小口側の柱が付きます。

## よくあるつまずき

- **アラビア語の本のタグはLANGではなく'ar'にする.** レシピの版はenとesですが、アラビア語のサンプルはどちらの版でもアラビア語です。`locale: LANG`では左から右に組まれ、左綴じになり、ページ番号は1 2 3となり、図のキャプションにはFigureやFiguraが付きます。postext 1.30以降、このタグはテキストを組む言語（計測、描画、埋め込みに使う言語）でもあるので、英語やスペイン語のタグでは、Markazi Textのようなフォントがギュメ（« »）や終止符をアラビア語の字形で描かず、改行の位置も変わります。タグは自分で書いてください。'ar'（アラビア・インド数字、マシュリク地域の慣習）、'ar-EG'や'ar-SA'のような地域付きのタグ、ヨーロッパ式数字を使うマグレブ版なら'ar-MA'、'ar-DZ'、'ar-TN'です。アラビア語を引用するだけのラテン文字のページは、自分のロケールのままにします。
- **日本語のテキストのタグは'ja'。zh-HansやLANGにしない.** レシピの版はenとesですが、日本語のサンプルはどちらの版でも日本語です。`locale: LANG`では英語やスペイン語とタグ付けされ、中国語のタグでは中国語の規則で組まれます（開明式の約物、小書きの仮名が行頭に来てもよい、図の代わりに图、PDFでは中国の字形）。postext 1.30以降、このタグはテキストを組む言語（計測、描画、埋め込みに使う言語）でもあるので、'ja'以外のタグでは日本語の字形ではなく別の字形（中国語のタグでは中国の字形）になり、改行の位置も変わります。'ja'と書いてください。日本の地域（JLReqの改行と約物、ゴマの圏点、ルビの間隔、図と表の表示名）が選ばれ、ハイフネーションが切られます。リントは、zhやkoのタグで仮名を含むテキストをエラーにします。
- **アラビア語の書体にはarabicブロックを通じてarabicファイルが必要.** FontsourceはAmiri、Noto Naskh Arabic、Scheherazade Newをサブセットごとに1ファイルとして配信し、アラビア文字はarabicファイルに入っています。loadFontsが取得するのはlatin（とlatin-ext）だけなので、画面ではアラビア文字がシステムの書体で出て計測が狂い、fontsourceProviderはPDFにそのlatinファイルを渡すため、空の四角が印字されます。キットのarabicブロックを挙げ、loadFontsのあとにloadArabicFonts(FONTS, markdown)を呼び（ページでアラビア文字に使うすべてのウェイトをFONTSに挙げておきます）、renderToPdfにfontProvider: arabicPdfProviderを渡してください。
- **中国語の書体はcjkブロックを通じてスライス単位で読み込む.** Fontsourceは中国語、日本語、韓国語のファミリーを、ウェイトごとに約100個のファイルとして配信し、各ファイルが文字の範囲を受け持ちます。loadFontsが取得するのはlatinファイルだけなので、画面では漢字がシステムの書体で出て計測が狂い、fontsourceProviderはPDFにそのlatinファイルを渡すため、漢字が空の四角で印字されます。キットのcjkブロックを挙げ、loadFontsのあとにloadCjkFonts(FONTS, markdown)を呼び（本で複数のCJK書体を使うときは、それぞれの書体で組むテキストを渡して書体ごとに1回）、renderToPdfにfontProvider: cjkPdfProviderを渡してください。どちらもテキストの文字を含むファイルを取得します。

## クレジット

- レシピ: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- 書体: Noto Naskh Arabic (OFL-1.1), Noto Serif JP (OFL-1.1)
- コード: MIT · サンプルの内容: CC-BY-4.0

## 関連レシピ

- [No. 215 · 余白のメモと、ページ座標から置くポップオーバー](https://postext.dev/ja/cookbook/margin-notes-with-popovers.md): メモの印は語句を薄く塗り、外側の余白に旗を立てる。押すと、rangeRects と pageToClient で語句の下に置いたポップオーバーにメモが開く。 · 難易度 2 (中級) · カタログ
- [No. 214 · 校正記号：削除・置換・挿入](https://postext.dev/ja/cookbook/proofreading-marks-on-pages.md): 編集者の赤字を postext-viewer で組んだ小説のページに描く。削除線、上に書いた差し替え、挿入の記号を Markdown の範囲から置く。 · 難易度 2 (中級) · 小説・戯曲・文芸
- [No. 220 · ページ画像に重ねる SVG の注釈：報告書のために](https://postext.dev/ja/cookbook/marks-as-svg-over-pages.md): layoutAnnotations と annotationsSvg で、校正者の印をビューアーなしでページ画像に重ねる。CMS がメールで送ったり印刷したりできる校正報告書。 · 難易度 2 (中級) · 新聞とニュースレター
