# Тема детского учебника на десяти языках

> Девять полос темы для 3-го класса на десяти языках, справа налево и вертикально: цветные развороты, растущие врезки, карта с подписями.

- Версия HTML: https://postext.dev/ru/cookbook/children-textbook-pages
- Рецепт № 156 · Учебники · Уровень 3 (Продвинутый) · Форматы вывода: Canvas, PDF
- Жанры: Учебники
- Требуется postext ≥ 1.65.0, postext-pdf ≥ 1.65.0 · проверено с 1.65.0, postext-pdf 1.65.0 · дата 2026-10-31
- Страницы: [1](https://postext.dev/cookbook/children-textbook-pages/en/p01.webp?v=79b1742d), [2](https://postext.dev/cookbook/children-textbook-pages/en/p02.webp?v=79b1742d), [3](https://postext.dev/cookbook/children-textbook-pages/en/p03.webp?v=79b1742d), [4](https://postext.dev/cookbook/children-textbook-pages/en/p04.webp?v=79b1742d), [5](https://postext.dev/cookbook/children-textbook-pages/en/p05.webp?v=79b1742d), [6](https://postext.dev/cookbook/children-textbook-pages/en/p06.webp?v=79b1742d), [7](https://postext.dev/cookbook/children-textbook-pages/en/p07.webp?v=79b1742d), [8](https://postext.dev/cookbook/children-textbook-pages/en/p08.webp?v=79b1742d), [9](https://postext.dev/cookbook/children-textbook-pages/en/p09.webp?v=79b1742d)
- PDF: https://postext.dev/cookbook/children-textbook-pages/en/children-textbook-pages.pdf?v=79b1742d
- Открыть в Sandbox: https://postext.dev/ru/sandbox#recipe=children-textbook-pages&lang=en (.postext: https://postext.dev/cookbook/children-textbook-pages/en/children-textbook-pages.postext)
- Последнее обновление: 2026-10-31
- Другие языки: [en](https://postext.dev/en/cookbook/children-textbook-pages.md), [es](https://postext.dev/es/cookbook/children-textbook-pages.md), [ca](https://postext.dev/ca/cookbook/children-textbook-pages.md), [de](https://postext.dev/de/cookbook/children-textbook-pages.md), [el](https://postext.dev/el/cookbook/children-textbook-pages.md), [fr](https://postext.dev/fr/cookbook/children-textbook-pages.md), [it](https://postext.dev/it/cookbook/children-textbook-pages.md), [pt](https://postext.dev/pt/cookbook/children-textbook-pages.md), [zh](https://postext.dev/zh/cookbook/children-textbook-pages.md), [ja](https://postext.dev/ja/cookbook/children-textbook-pages.md), [ar](https://postext.dev/ar/cookbook/children-textbook-pages.md)

## Коротко

Тема школьного учебника о реке на девяти страницах. Каждый параграф занимает цветной разворот с ярлыком заголовка, текстом, картинками и врезками. На карте не нарисовано ни слова: названия берутся из текста.

## Что получится

Девять полос *Our river* («Наша река»), темы 4 вымышленного учебника обществознания для третьего класса, на странице 210 × 280 мм и на десяти языках: испанском, каталанском, английском, португальском, французском, немецком, итальянском, арабском, китайском и японском. Тему открывает картина долины, на полосе содержания перечислены две части, дальше идут три разворота, у каждого свой фон: голубой для воды, зелёный для поля, песочный для солнца. У каждого параграфа есть ярлык с номером и заголовком, текст в две колонки и врезки с ярлыками, которые растут вместе с текстом. Второй параграф — это одна рисованная карта на весь разворот: река, деревни и три течения подписаны на ней из Markdown, а от врезки каждого течения к его участку реки идёт линия. Всё повторяющееся задано один раз: шаблон раскладывает одну карточку картинки, одну врезку течения и одну врезку с картинкой столько раз, сколько просит Markdown, а три вопроса перед темой — это три применения одного модуля. Тексты различаются по длине на пятую часть и больше, но укладываются в одни и те же шаблоны: врезка берёт высоту, нужную её словам, и сдвигает следующую вниз, а карта уменьшается раньше, чем какой-либо текст. Арабская книга идёт справа налево, китайская и японская — сверху вниз; у всех трёх переплёт справа, и каждый разворот читают с правой полосы к левой.

**Рецепт отвечает на вопросы:**

- Как сверстать тему учебника на десяти языках, в том числе справа налево и вертикально, по одним шаблонам?
- Как сделать, чтобы врезки страницы росли вместе с текстом и сдвигали врезки под ними вниз?
- Как взять названия на карте из текста, чтобы перевод менял слова, а не рисунок?

## Короткий ответ

```js
// script.js, строк 90–122
// Ground, tab and number are decoration anchored to the title frame; the number,
// `{headingNumber}`, stands over the padding before its words. A topic extends the base.
const ground = () => ({ kind: 'box', id: 'ground',
  placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: 'fill' } },
  style: { backgroundColor: col('tema-ground') } });
const titleTab = () => ({ kind: 'box', id: 'tab', placement: { ...at('#titulo',
  'top-left'), size: { width: { to: '#titulo', edge: 'right' }, height: { to: '#titulo',
    edge: 'bottom' } } }, style: { backgroundColor: col('tema'), borderRadius: mm(4) } });
const badge = () => ({ kind: 'text', id: 'number', content: '{headingNumber}',
  fontFamily: DISPLAY, fontSize: pt(22), fontWeight: fw(700), color: col('tema'), align: 'center',
  box: { backgroundColor: col('paper'), borderRadius: mm(6) }, placement: { ...at('#titulo',
    corner('top'), inward(CJK ? 2.6 : 5), CJK ? 5 : 2.4), size: { width: mm(12), height: mm(12) } },
});
const title = { name: 'titulo', takes: 'h1', style: 'titulo', width: mm(MEASURE),
  placement: at('container', 'top-left') };

const base = {
  id: 'tema', spread: true, gutter: mm(12),
  decoration: { elements: [ground(), titleTab(), badge()] },
  frames: [title, { name: 'texto', flow: true, columns: 2, columnGap: mm(CJK ? 16 : 7), // 段
    width: mm(MEASURE), fit: { minScale: 0.9 } }],
  groups: [{ name: 'izquierda', kind: 'stack', gap: mm(6), frames: ['titulo', 'texto'] }],
};
const topic = (id, f, more) => ({ id, extends: 'tema', palette: swap(f), ...more });
const box = (name, style, minHeight, more) => ({ name, style, width: mm(MEASURE),
  minHeight: mm(minHeight), ...more });
const answer = (name, lines) => ({ name, optional: true, style: 'respuesta', width: mm(MEASURE),
  height: mm(LINE * lines), minHeight: mm(LINE * lines),
  rules: { every: mm(LINE), color: col('rule'), width: pt(0.75) } });
const PIC = CJK ? 30 : 56; // a picture at the end of a box's first lines pushes the text aside
const withPic = (name, style, minHeight, more) => [box(name, style, minHeight,
  { padding: { right: mm(PIC + 8) }, ...more }), { name: `${name}-foto`, layer: 2, width: mm(PIC),
  exclude: 'push', placement: at(`#${name}`, 'top-right', -5, 8) }];
```

## Ингредиенты

**Чему учит**

- [Макетные страницы](https://postext.dev/ru/docs/composed-pages.md#макетные-страницы): Страница, свёрстанная по шаблону из именованных фреймов в конфигурации; её заполняет ограждение ::::page, содержимое которого называет каждый фрейм по слоту.
- [Сетки с повтором набора фреймов](https://postext.dev/ru/docs/configuration-composed-pages.md#сетки-с-повторением-набора-фреймов): Группа-сетка один раз объявляет набор фреймов, например карточку и подпись, и повторяет его для каждого элемента, который даёт Markdown страницы, рядами равных столбцов, с именами копий #card[1], #card[2]…
- [Модули друг под другом на странице](https://postext.dev/ru/docs/configuration-composed-pages.md#модули): Модуль — это шаблон из нескольких фреймов, групп и оформления для повторного использования; группа modules шаблона страницы берёт блоки :::module в порядке Markdown и ставит их один под другим.

**Также используются**

- [Выноски и легенды на рисунках](https://postext.dev/ru/docs/composed-pages-figures.md#выноски-легенды-и-символы)
- [Фреймы, которые растут в группе](https://postext.dev/ru/docs/composed-pages.md#когда-текст-растёт)
- [Нумерованные ярлыки врезок](https://postext.dev/ru/docs/configuration-callouts.md#стили-врезок)
- [Надписи на рисунке](https://postext.dev/ru/docs/composed-pages-figures.md#рисунки-с-надписями)
- [Содержание](https://postext.dev/ru/docs/configuration-notes-references.md#содержание)
- [Шаблоны разворотов](https://postext.dev/ru/docs/composed-pages.md#развороты)
- [Врезки](https://postext.dev/ru/docs/configuration-callouts.md#стили-врезок)
- [Текст, линейки и рамки в дизайне страницы](https://postext.dev/ru/docs/configuration-headers-footers.md#верхние-и-нижние-колонтитулы)
- [Иллюстрации в дизайне страницы](https://postext.dev/ru/docs/configuration-headers-footers.md#изображения)
- [Привязка элементов дизайна](https://postext.dev/ru/docs/configuration-headers-footers.md#размещение-элементов)
- [Оформление, привязанное к фреймам](https://postext.dev/ru/docs/composed-pages.md#оформление-колонтитулы-и-слои)
- [Зеркальные поля](https://postext.dev/ru/docs/configuration-page-layout.md#зеркальные-поля)
- [Колонтитулы и колонцифры](https://postext.dev/ru/docs/configuration-headers-footers.md#верхние-и-нижние-колонтитулы)
- [Стили заголовков](https://postext.dev/ru/docs/configuration-styles.md#стили-заголовков)
- [Семантическая палитра](https://postext.dev/ru/docs/configuration-fonts-colors-viewers.md#палитра-цветов)
- [Рисунки и таблицы как ресурсы](https://postext.dev/ru/docs/document-format-resources.md#ресурсы)
- [Фреймы, которые отодвигают текст: по рамке или контуру](https://postext.dev/ru/docs/composed-pages.md#фреймы-которые-оттесняют-текст)
- [Атрибуты заголовков](https://postext.dev/ru/docs/document-format.md#атрибуты-заголовка)
- [Шмуцтитулы частей](https://postext.dev/ru/docs/configuration-styles.md#контейнер-part)
- [Экспорт в PDF](https://postext.dev/ru/docs/configuration-pdf-output.md#создание-pdf)
- [Шрифты, встроенные в PDF](https://postext.dev/ru/docs/configuration-pdf-output.md#зачем-нужен-провайдер-шрифтов)
- [Собственные типы ресурсов](https://postext.dev/ru/docs/configuration-resources.md#типы-ресурсов)
- [Главы без номера](https://postext.dev/ru/docs/configuration-styles.md#стили-заголовков)

**Конфигурация вкратце**

- [`bodyText`](https://postext.dev/ru/docs/configuration-text.md#основной-текст), [`calloutStyles`](https://postext.dev/ru/docs/configuration-callouts.md#стили-врезок), [`canvasViewer`](https://postext.dev/ru/docs/configuration-fonts-colors-viewers.md#просмотр-canvas), [`captionStyle`](https://postext.dev/ru/docs/configuration-resources.md#стиль-подписи), [`colorPalette`](https://postext.dev/ru/docs/configuration-fonts-colors-viewers.md#палитра-цветов), [`footer`](https://postext.dev/ru/docs/configuration-headers-footers.md#верхние-и-нижние-колонтитулы), [`header`](https://postext.dev/ru/docs/configuration-headers-footers.md#верхние-и-нижние-колонтитулы), [`headingStyles`](https://postext.dev/ru/docs/configuration-styles.md#стили-заголовков), [`headings`](https://postext.dev/ru/docs/configuration-headings.md#заголовки), [`labelStyles`](https://postext.dev/ru/docs/configuration-composed-pages.md#стили-надписей), [`layout`](https://postext.dev/ru/docs/configuration-page-layout.md#колонки), [`locale`](https://postext.dev/ru/docs/configuration-language.md#перенос-слов), [`orderedLists`](https://postext.dev/ru/docs/configuration-lists-math.md#нумерованные-списки), [`page`](https://postext.dev/ru/docs/configuration-page-layout.md#страница), [`pageTemplates`](https://postext.dev/ru/docs/configuration-composed-pages.md#шаблоны-страниц), [`parts`](https://postext.dev/ru/docs/configuration-styles.md#части), [`resourceTypes`](https://postext.dev/ru/docs/configuration-resources.md#типы-ресурсов), [`toc`](https://postext.dev/ru/docs/configuration-notes-references.md#содержание), [`unorderedLists`](https://postext.dev/ru/docs/configuration-lists-math.md#маркированные-списки)

**API**

- [`buildDocument`](https://postext.dev/ru/docs/configuration-programmatic-usage.md#сборка-документа), [`decompressWoff2`](https://postext.dev/ru/docs/configuration-pdf-output.md#провайдер-шрифтов-в-браузере-fontsource--woff2), `loadVerticalAlternates`, [`registerResourceImage`](https://postext.dev/ru/docs/architecture.md#состав-api), [`renderPageToCanvas`](https://postext.dev/ru/docs/configuration-programmatic-usage.md#рендеринг-страницы-в-растр), [`renderToPdf`](https://postext.dev/ru/docs/configuration-pdf-output.md#создание-pdf), [`withLoadedFonts`](https://postext.dev/ru/docs/configuration-programmatic-usage.md#загрузка-шрифтов-перед-вёрсткой)

**Гарнитуры**

- Nunito (OFL-1.1), Fredoka (OFL-1.1), Noto Naskh Arabic (OFL-1.1), Baloo Bhaijaan 2 (OFL-1.1), Klee One (OFL-1.1), Zen Maru Gothic (OFL-1.1), Noto Serif SC (OFL-1.1), ZCOOL KuaiLe (OFL-1.1)

## Порядок работы

### 1 · Определите, с какой стороны начинает каждый язык

```js
// script.js, строк 33–44
// Arabic runs right to left, Chinese and Japanese down the page, all bound on the right. Frames
// stand in the flow (x along the lines, mirrored in Arabic, down the page when vertical).
const AR = LANG === 'ar', CJK = LANG === 'zh' || LANG === 'ja';
const RIGHT_BOUND = AR || CJK, LATIN = !RIGHT_BOUND; // italics, capitals, tracking, hyphens
const [TEXT, DISPLAY] = { ar: ['Noto Naskh Arabic', 'Baloo Bhaijaan 2'], ja: ['Klee One',
  'Zen Maru Gothic'], zh: ['Noto Serif SC', 'ZCOOL KuaiLe'] }[LANG] ?? ['Nunito', 'Fredoka'];
const START = RIGHT_BOUND ? 'right' : 'left'; // the side a page starts reading from
const corner = (v) => `${v}-${START}`, inward = (x) => (RIGHT_BOUND ? -x : x);
const [SLANT, CAPS] = LATIN ? ['italic', 'uppercase'] : ['normal', 'none'];
const LEAD = AR ? 20 : CJK ? 21 : 17.5, track = (v) => (LATIN ? v : 0); // Naskh, ruby need room
const fw = (w) => ({ 'ZCOOL KuaiLe': 400, 'Zen Maru Gothic': w > 550 ? 700 : 500 })[DISPLAY] ?? w;
const BOLD = TEXT === 'Klee One' ? 600 : 700; // and the weights the faces have
```

Фреймы шаблона стоят в системе координат потока, где x идёт вдоль строк. При `locale: 'ar'` движок отражает эту систему, поэтому арабская книга берёт латинские фреймы без изменений: заголовок стоит первым на правой полосе, три картинки и три врезки течений идут справа налево, а ярлыки, полоски и внутренние отступы врезок следуют за строками. При `layout.writingMode: 'vertical-rl'` x идёт вниз по странице, а y — справа налево: `width` фрейма становится длиной по вертикали, стопка растёт влево, `columns: 2` даёт два яруса (段) по 27 знаков, а фрейм, поставленный `below` другого, оказывается слева от него. Декор (фоны, ярлык заголовка, номер, колонтитулы и колонцифры) стоит на самом листе, поэтому его размещают от `START` — стороны, с которой начинают читать страницу. У каждой письменности есть текстовая гарнитура и округлая акцидентная, а в арабском, китайском и японском изданиях нет курсива, прописных и трекинга.

### 2 · Соберите врезки через `extends`

```js
// script.js, строк 59–86
// Two steps of `extends`: the box (shape, type, tab), then the kind. The colours are `tema`
// entries, so one style serves the three topics; paddings, stripes and tabs are in the flow.
const tab = (f) => ({ position: 'top-left', background: col(f), color: col('paper'),
  fontFamily: DISPLAY, fontSize: pt(12), fontWeight: fw(600), height: mm(7), paddingX: mm(3.2),
  offset: mm(7), inset: mm(5), rule: { enabled: false, color: col(f) } });
const boxText = { fontFamily: TEXT, fontSize: pt(12), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), boldFontWeight: BOLD, firstLineIndent: pt(0),
  textAlign: CJK ? 'justify' : 'left', paragraphSpacing: true };
const calloutStyles = [
  { id: 'caja', backgroundEnabled: true, background: col('paper'), borderRadius: mm(3),
    border: { enabled: false }, padding: { top: mm(3.4), right: mm(5), bottom: mm(4), left: mm(5) },
    body: boxText, lists: { color: col('ink'), gap: mm(2), itemSpacing: mm(1.6) } },
  { id: 'caja-tema', extends: 'caja', label: tab('tema'), lists: { color: col('tema') } },
  { id: 'dato', extends: 'caja-tema', background: col('tema-tint') },
  { id: 'palabras', extends: 'caja-tema', border: { enabled: true, color: col('tema'),
    width: pt(1.4) } }, { id: 'actividad', extends: 'caja-tema',
    stripe: { enabled: true, side: 'left', width: pt(4), color: col('tema') } },
  { id: 'titulo', extends: 'caja', backgroundEnabled: false,
    padding: { top: mm(2.6), right: mm(6), bottom: mm(3.2), left: mm(TAB) } },
  { id: 'titulo-plano', extends: 'titulo', padding: { left: mm(8) } },
  { id: 'portada', extends: 'caja', background: col('agua'), borderRadius: mm(4),
    padding: { top: mm(2.6), right: mm(8), bottom: mm(3.6), left: mm(8) } },
  { id: 'foto', extends: 'caja', borderRadius: mm(2),
    padding: { top: mm(1.8), right: mm(1.8), bottom: mm(2.2), left: mm(1.8) } },
  { id: 'respuesta', extends: 'caja', padding: NONE }, { id: 'colofon', extends: 'caja',
    backgroundEnabled: false, padding: NONE,
    body: { ...boxText, fontSize: pt(8), lineHeight: pt(AR ? 13 : 11), color: col('muted') } },
];
```

Стиль врезки складывается в три шага. `caja` держит форму, шрифт и геометрию ярлыка; `caja-tema` красит ярлык и маркеры списка в цвет темы; `dato`, `palabras` и `actividad` задают вид: врезка с заливкой, с контуром или с полоской. Их цвета — записи палитры (`tema`, `tema-tint`), поэтому каждый стиль написан один раз, а красит его шаблон темы.

### 3 · Пусть каждая тема расширяет один базовый шаблон

```js
// script.js, строк 90–122
// Ground, tab and number are decoration anchored to the title frame; the number,
// `{headingNumber}`, stands over the padding before its words. A topic extends the base.
const ground = () => ({ kind: 'box', id: 'ground',
  placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: 'fill' } },
  style: { backgroundColor: col('tema-ground') } });
const titleTab = () => ({ kind: 'box', id: 'tab', placement: { ...at('#titulo',
  'top-left'), size: { width: { to: '#titulo', edge: 'right' }, height: { to: '#titulo',
    edge: 'bottom' } } }, style: { backgroundColor: col('tema'), borderRadius: mm(4) } });
const badge = () => ({ kind: 'text', id: 'number', content: '{headingNumber}',
  fontFamily: DISPLAY, fontSize: pt(22), fontWeight: fw(700), color: col('tema'), align: 'center',
  box: { backgroundColor: col('paper'), borderRadius: mm(6) }, placement: { ...at('#titulo',
    corner('top'), inward(CJK ? 2.6 : 5), CJK ? 5 : 2.4), size: { width: mm(12), height: mm(12) } },
});
const title = { name: 'titulo', takes: 'h1', style: 'titulo', width: mm(MEASURE),
  placement: at('container', 'top-left') };

const base = {
  id: 'tema', spread: true, gutter: mm(12),
  decoration: { elements: [ground(), titleTab(), badge()] },
  frames: [title, { name: 'texto', flow: true, columns: 2, columnGap: mm(CJK ? 16 : 7), // 段
    width: mm(MEASURE), fit: { minScale: 0.9 } }],
  groups: [{ name: 'izquierda', kind: 'stack', gap: mm(6), frames: ['titulo', 'texto'] }],
};
const topic = (id, f, more) => ({ id, extends: 'tema', palette: swap(f), ...more });
const box = (name, style, minHeight, more) => ({ name, style, width: mm(MEASURE),
  minHeight: mm(minHeight), ...more });
const answer = (name, lines) => ({ name, optional: true, style: 'respuesta', width: mm(MEASURE),
  height: mm(LINE * lines), minHeight: mm(LINE * lines),
  rules: { every: mm(LINE), color: col('rule'), width: pt(0.75) } });
const PIC = CJK ? 30 : 56; // a picture at the end of a box's first lines pushes the text aside
const withPic = (name, style, minHeight, more) => [box(name, style, minHeight,
  { padding: { right: mm(PIC + 8) }, ...more }), { name: `${name}-foto`, layer: 2, width: mm(PIC),
  exclude: 'push', placement: at(`#${name}`, 'top-right', -5, 8) }];
```

Базовый шаблон — это разворот: фон до вылета, ярлык заголовка с номером и текст в две колонки. Тема расширяет его (`extends: 'tema'`), задаёт свою `palette` (три записи `tema` получают цвета семейства, и вместе меняются фон, ярлык, номер и все врезки) и добавляет собственные фреймы. Ярлык и номер — декор, привязанный к фрейму заголовка, поэтому высота ярлыка равна высоте заголовка на данном языке. Номер — это `{headingNumber}`, счётчик заголовка, попавшего во фрейм. Он рисуется поверх внутреннего отступа фрейма, перед словами: ни один блок страницы его не повторяет, а щелчок по нему попадает в номер, а не во фрейм.

### 4 · Задайте повторяющееся один раз

```js
// script.js, строк 126–131
const grid = (name, frames, columns, placement, more, width = MEASURE) => ({ name, kind: 'grid',
  columns, columnGap: mm(5), rowGap: mm(CJK ? 8 : 12), repeat: { frames },
  placement: { ...placement, size: { width: mm(width), height: 'fill' } }, ...more });
const question = { id: 'pregunta', role: 'module', // a question and the lines to answer it on
  frames: [box('caja', 'dato', CJK ? 22 : 14, { width: 'fill' }), { ...answer('lineas',
    CJK ? 2 : 3), width: 'fill', placement: at('#caja', 'below', 0, CJK ? 4 : 7) }] };
```

Группа-сетка повторяет набор фреймов по разу на каждый элемент страницы. Ряд картинок — это `grid('fotos', ['foto'], 3, …)`: три блока `:::figure{slot="foto"}` дают три карточки с именами от `#foto[1]` до `#foto[3]`, а врезка *Try it* висит под `#foto[1]`. Врезки солнечной темы — сетка в одну колонку, набор которой состоит из врезки и её картинки (`['uso', 'uso-foto']`): каждый `:::frame{slot="uso"}` содержит свои слова и внутри себя `:::figure{slot="uso-foto"}`, который к ним относится. На странице вопросов модуль идёт стопкой: `pregunta` — шаблон с `role: 'module'`, врезка с заливкой и линейки для ответа, а группа `preguntas` этой страницы (`modules: true`) ставит по одному такому модулю на каждый `:::module{template="pregunta"}` в Markdown. Высота фрейма равна высоте его слов и не бывает меньше `minHeight`, поэтому более длинный испанский текст сдвигает нижние ряды, а когда странице не хватает места, [лестница подгонки](https://postext.dev/ru/docs/composed-pages.md#когда-всё-равно-не-помещается) уменьшает карту и картинки раньше текста, до 90 %.

Врезки течений — сетка из трёх под картой (`grid('cursos', ['curso'], 3, …)`), по одной на каждый `:::frame{slot="curso"}`. Карта называет те же три участка подписями в стиле `curso`, на зелёном цвете ярлыков врезок, так что читатель находит участок каждой врезки по названию и цвету. На вертикальной странице течения стоят в одну колонку рядом с картой.

### 5 · Поставьте названия на карту из текста

```js
// script.js, строк 250–290
// An anchor is a point of the painting (fractions of its width and height) and a label style;
// every language's ::label lines use the same anchors. A right-bound book shows the painting
// mirrored, the mountains on the right, so the river runs the way its pages are read: x comes
// from the other edge and a turn goes the other way. `start` is a label's own start, so the
// spring's label keeps it in Arabic and takes `end` in a label set left to right.
const halo = { color: col('paper'), width: pt(1.8) };
const labelStyles = [
  { id: 'sierra', fontFamily: DISPLAY, fontSize: pt(13), fontWeight: fw(600), color: col('ink'),
    textTransform: CAPS, letterSpacing: track(0.14), halo },
  { id: 'agua', fontFamily: TEXT, fontSize: pt(11), fontWeight: BOLD, fontStyle: SLANT,
    color: { hex: '#0b3a5c', model: 'hex' }, halo, // a name set away draws a leader to its point
    leader: { width: pt(1), endCap: 'dot', capSize: mm(1.6) } },
  { id: 'mar', fontFamily: TEXT, fontSize: pt(12), fontWeight: BOLD, fontStyle: SLANT,
    color: col('paper'), halo: { color: { hex: '#0b3a5c', model: 'hex' }, width: pt(1.8) } },
  { id: 'pueblo', fontFamily: DISPLAY, fontSize: pt(12), fontWeight: fw(600), color: col('ink'),
    halo },
  { id: 'curso', fontFamily: DISPLAY, fontSize: pt(10.5), fontWeight: fw(600), color: col('paper'),
    textTransform: CAPS, letterSpacing: track(0.08), background: col('campo'),
    padding: mm(1.6) },
];
const ANCHORS = [
  { id: 'sierra', x: 0.21, y: 0.055, style: 'sierra' },
  // The spring and the dam: the point is the place, `labelAt` where its name stands.
  { id: 'nacimiento', x: 0.049, y: 0.098, labelAt: { x: 0.075, y: 0.115 }, style: 'agua',
    align: 'start' },
  { id: 'fontalba', x: 0.135, y: 0.255, style: 'pueblo', verticalAlign: 'top' },
  { id: 'embalse', x: 0.293, y: 0.275, labelAt: { x: 0.31, y: 0.155 }, style: 'agua',
    width: 0.12 },
  { id: 'molinar', x: 0.505, y: 0.35, style: 'pueblo', verticalAlign: 'bottom' },
  { id: 'aldamar', x: 0.845, y: 0.505, style: 'pueblo', verticalAlign: 'bottom' },
  { id: 'mar', x: 0.965, y: 0.28, style: 'mar' },
  { id: 'rio', x: 0.61, y: 0.715, style: 'agua', rotate: -3 },
  { id: 'alto', x: 0.17, y: 0.45, style: 'curso' },
  { id: 'medio', x: 0.4, y: 0.77, style: 'curso' },
  { id: 'bajo', x: 0.74, y: 0.865, style: 'curso' },
];
const flip = (x) => Math.round((1 - x) * 1000) / 1000;
const flipped = (a) => ({ ...a, x: flip(a.x), ...(a.labelAt && { labelAt: { ...a.labelAt,
    x: flip(a.labelAt.x) } }),
  ...(a.rotate && { rotate: -a.rotate }), ...(a.align && !AR && { align: 'end' }) });
const anchors = RIGHT_BOUND ? ANCHORS.map(flipped) : ANCHORS;
```

Карта — это картина без единой буквы. Каждое место на ней — якорь изображения: точка в долях ширины и высоты со стилем подписи, а каждая языковая версия пишет у этих якорей свои строки `::label`. *Penalta Reservoir*, *Pantà de Penyalta* и *Embalse de Peñalta* стоят в одном и том же месте, а более длинное название разбивается на строки в пределах `width` якоря. В книге с переплётом справа та же картина отражена (`mapa-1900-rtl.jpg`), и река течёт от гор справа к морю слева, как читаются её страницы; `flipped` переносит каждый якорь и место его подписи на другую сторону и поворачивает в обратном направлении. *Spring* и *Penalta Reservoir* отнесены от своих мест через `labelAt`, а `leader` стиля `agua` ведёт линию с точкой от названия к роднику и к плотине.

### 6 · Не разрывайте части содержания

```js
// script.js, строк 227–246
const partAt = (x) => (CJK ? at('container', 'left', x) : at('container', START, inward(x)));
const toc = {
  levels: [{ level: 1, fontFamily: DISPLAY, fontSize: pt(15), lineHeight: pt(22),
    fontWeight: fw(500), color: col('ink'), numberFontWeight: fw(600), numberColor: col('agua'),
    numberWidth: mm(9), marginTop: pt(4) }, { level: 2, fontFamily: TEXT, fontSize: pt(11.5),
    lineHeight: pt(18), indent: mm(9), color: col('ink') }],
  pageNumber: { fontFamily: DISPLAY, fontWeight: fw(500), width: mm(9), color: col('agua') },
  leader: { char: CJK ? '…' : '.', gap: mm(1.5) },
  parts: { height: pt(34), marginTop: pt(12), marginBottom: pt(4), design: { elements: [
    { kind: 'box', id: 'band',
      placement: { ...at('container', 'top-left'), size: { width: 'fill', height: 'fill' } },
      style: { backgroundColor: col('paper'), borderRadius: mm(3) } },
    { kind: 'text', id: 'letter', content: '{number}', fontFamily: DISPLAY, fontSize: pt(16),
      fontWeight: fw(700), color: col('paper'), align: 'center',
      box: { backgroundColor: col('agua'), borderRadius: mm(4) },
      placement: { ...partAt(2), size: { width: mm(8), height: mm(8) } } },
    { kind: 'text', id: 'name', content: '{titleText}', fontFamily: DISPLAY, fontSize: pt(13),
      fontWeight: fw(600), color: col('agua'), align: START, placement: partAt(14) },
  ] } },
};
```

`:::toc{keep="part" levels="1-2"}` перечисляет темы с их разделами и держит строку каждой части вместе с её пунктами. Блок `:::part` при `parts.page: false` — лишь строка содержания и раздел для колонтитулов: шмуцтитула он не добавляет. Содержание — макетная страница: в её шаблоне есть фрейм с `takes: "toc"`, который принимает `:::toc` и верстает его по собственным правилам содержания. Поэтому строки частей, отточия и `keep` работают как в обычном тексте, а бледный фон — декор шаблона.

## Рецепт целиком

Один файл, собранный из папки рецепта; образец текста и общий набор функций рецептов встроены в него; он сам строит свою страницу. Чтобы запустить его, поместите его в `<script type="module">` на пустой странице или вставьте в панель JS нового пена CodePen (как модуль). Он импортирует postext с esm.sh, поэтому ничего не нужно устанавливать и собирать.

- Папка с исходными файлами: https://github.com/drnachio/postext/tree/main/cookbook/children-textbook-pages

### script.js

```js
// ═══ Postext Cookbook · Nº 156 · A children's textbook unit in ten languages ═════
// https://postext.dev/en/cookbook/children-textbook-pages
// Code: MIT · Text: original (CC BY 4.0) · Pictures: generated with diffusion models
// Fonts: Nunito, Fredoka and three pairs for Arabic, Chinese, Japanese · Needs postext ≥ 1.65.0
import {
  buildDocument, withLoadedFonts, renderPageToCanvas, registerResourceImage,
  loadVerticalAlternates,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the unit (es en ca pt fr de it ar zh ja)
const RECIPE = 'children-textbook-pages';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// One ink and three families (accent, box tint, page ground); a topic swaps the `tema` entries.
const FAMILIES = {
  agua: { main: '#1b6aa0', tint: '#e1f0fa', ground: '#d3e8f6' },
  campo: { main: '#336f27', tint: '#e5f1dc', ground: '#d9ebcb' },
  sol: { main: '#9a5209', tint: '#fcefd2', ground: '#f8e6b8' },
};
const palette = { ink: '#1d2f3f', muted: '#4f6272', rule: '#7e98ab', paper: '#ffffff',
  agua: FAMILIES.agua.main, campo: FAMILIES.campo.main, // the blue of the folios and the contents
  tema: FAMILIES.agua.main, 'tema-tint': FAMILIES.agua.tint, 'tema-ground': FAMILIES.agua.ground };
const swap = (f) => `tema=${FAMILIES[f].main}, tema-tint=${FAMILIES[f].tint}, `
  + `tema-ground=${FAMILIES[f].ground}`;
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: 'water (defaults)', value: { hex: palette.agua, model: 'hex' } },
];

// #region editions: how each language runs and is bound, and the two faces of its script
// Arabic runs right to left, Chinese and Japanese down the page, all bound on the right. Frames
// stand in the flow (x along the lines, mirrored in Arabic, down the page when vertical).
const AR = LANG === 'ar', CJK = LANG === 'zh' || LANG === 'ja';
const RIGHT_BOUND = AR || CJK, LATIN = !RIGHT_BOUND; // italics, capitals, tracking, hyphens
const [TEXT, DISPLAY] = { ar: ['Noto Naskh Arabic', 'Baloo Bhaijaan 2'], ja: ['Klee One',
  'Zen Maru Gothic'], zh: ['Noto Serif SC', 'ZCOOL KuaiLe'] }[LANG] ?? ['Nunito', 'Fredoka'];
const START = RIGHT_BOUND ? 'right' : 'left'; // the side a page starts reading from
const corner = (v) => `${v}-${START}`, inward = (x) => (RIGHT_BOUND ? -x : x);
const [SLANT, CAPS] = LATIN ? ['italic', 'uppercase'] : ['normal', 'none'];
const LEAD = AR ? 20 : CJK ? 21 : 17.5, track = (v) => (LATIN ? v : 0); // Naskh, ruby need room
const fw = (w) => ({ 'ZCOOL KuaiLe': 400, 'Zen Maru Gothic': w > 550 ? 700 : 500 })[DISPLAY] ?? w;
const BOLD = TEXT === 'Klee One' ? 600 : 700; // and the weights the faces have
// #endregion

const PAGE = { w: 210, h: 280, top: 18, bottom: 18, inner: 14, outer: 12 }; // mm, mirrored
const HALF = PAGE.w - PAGE.inner - PAGE.outer, TALL = PAGE.h - PAGE.top - PAGE.bottom; // 184, 244
const MEASURE = CJK ? TALL : HALF; // a page's type area along the lines
const SHEET = 2 * HALF + 2 * PAGE.inner; // a spread's content area: 396 mm
const RIGHT = HALF + 2 * PAGE.inner; // where the second page's type area starts on the sheet
const LINE = 8, TAB = 22; // mm between answer lines; of the title before its words (the badge)
const NONE = { top: mm(0), right: mm(0), bottom: mm(0), left: mm(0) }; // no padding
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const onSecond = at('container', 'top-left', CJK ? 0 : RIGHT, CJK ? RIGHT : 0); // flow x or y
const DOWN = 156; // mm: a vertical field spread's map takes the head, its frames stand under it

// #region boxes: callout styles that extend each other
// Two steps of `extends`: the box (shape, type, tab), then the kind. The colours are `tema`
// entries, so one style serves the three topics; paddings, stripes and tabs are in the flow.
const tab = (f) => ({ position: 'top-left', background: col(f), color: col('paper'),
  fontFamily: DISPLAY, fontSize: pt(12), fontWeight: fw(600), height: mm(7), paddingX: mm(3.2),
  offset: mm(7), inset: mm(5), rule: { enabled: false, color: col(f) } });
const boxText = { fontFamily: TEXT, fontSize: pt(12), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), boldFontWeight: BOLD, firstLineIndent: pt(0),
  textAlign: CJK ? 'justify' : 'left', paragraphSpacing: true };
const calloutStyles = [
  { id: 'caja', backgroundEnabled: true, background: col('paper'), borderRadius: mm(3),
    border: { enabled: false }, padding: { top: mm(3.4), right: mm(5), bottom: mm(4), left: mm(5) },
    body: boxText, lists: { color: col('ink'), gap: mm(2), itemSpacing: mm(1.6) } },
  { id: 'caja-tema', extends: 'caja', label: tab('tema'), lists: { color: col('tema') } },
  { id: 'dato', extends: 'caja-tema', background: col('tema-tint') },
  { id: 'palabras', extends: 'caja-tema', border: { enabled: true, color: col('tema'),
    width: pt(1.4) } }, { id: 'actividad', extends: 'caja-tema',
    stripe: { enabled: true, side: 'left', width: pt(4), color: col('tema') } },
  { id: 'titulo', extends: 'caja', backgroundEnabled: false,
    padding: { top: mm(2.6), right: mm(6), bottom: mm(3.2), left: mm(TAB) } },
  { id: 'titulo-plano', extends: 'titulo', padding: { left: mm(8) } },
  { id: 'portada', extends: 'caja', background: col('agua'), borderRadius: mm(4),
    padding: { top: mm(2.6), right: mm(8), bottom: mm(3.6), left: mm(8) } },
  { id: 'foto', extends: 'caja', borderRadius: mm(2),
    padding: { top: mm(1.8), right: mm(1.8), bottom: mm(2.2), left: mm(1.8) } },
  { id: 'respuesta', extends: 'caja', padding: NONE }, { id: 'colofon', extends: 'caja',
    backgroundEnabled: false, padding: NONE,
    body: { ...boxText, fontSize: pt(8), lineHeight: pt(AR ? 13 : 11), color: col('muted') } },
];
// #endregion

// #region answer: one base template and a family of topics that extend it
// Ground, tab and number are decoration anchored to the title frame; the number,
// `{headingNumber}`, stands over the padding before its words. A topic extends the base.
const ground = () => ({ kind: 'box', id: 'ground',
  placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: 'fill' } },
  style: { backgroundColor: col('tema-ground') } });
const titleTab = () => ({ kind: 'box', id: 'tab', placement: { ...at('#titulo',
  'top-left'), size: { width: { to: '#titulo', edge: 'right' }, height: { to: '#titulo',
    edge: 'bottom' } } }, style: { backgroundColor: col('tema'), borderRadius: mm(4) } });
const badge = () => ({ kind: 'text', id: 'number', content: '{headingNumber}',
  fontFamily: DISPLAY, fontSize: pt(22), fontWeight: fw(700), color: col('tema'), align: 'center',
  box: { backgroundColor: col('paper'), borderRadius: mm(6) }, placement: { ...at('#titulo',
    corner('top'), inward(CJK ? 2.6 : 5), CJK ? 5 : 2.4), size: { width: mm(12), height: mm(12) } },
});
const title = { name: 'titulo', takes: 'h1', style: 'titulo', width: mm(MEASURE),
  placement: at('container', 'top-left') };

const base = {
  id: 'tema', spread: true, gutter: mm(12),
  decoration: { elements: [ground(), titleTab(), badge()] },
  frames: [title, { name: 'texto', flow: true, columns: 2, columnGap: mm(CJK ? 16 : 7), // 段
    width: mm(MEASURE), fit: { minScale: 0.9 } }],
  groups: [{ name: 'izquierda', kind: 'stack', gap: mm(6), frames: ['titulo', 'texto'] }],
};
const topic = (id, f, more) => ({ id, extends: 'tema', palette: swap(f), ...more });
const box = (name, style, minHeight, more) => ({ name, style, width: mm(MEASURE),
  minHeight: mm(minHeight), ...more });
const answer = (name, lines) => ({ name, optional: true, style: 'respuesta', width: mm(MEASURE),
  height: mm(LINE * lines), minHeight: mm(LINE * lines),
  rules: { every: mm(LINE), color: col('rule'), width: pt(0.75) } });
const PIC = CJK ? 30 : 56; // a picture at the end of a box's first lines pushes the text aside
const withPic = (name, style, minHeight, more) => [box(name, style, minHeight,
  { padding: { right: mm(PIC + 8) }, ...more }), { name: `${name}-foto`, layer: 2, width: mm(PIC),
  exclude: 'push', placement: at(`#${name}`, 'top-right', -5, 8) }];
// #endregion

// #region repeats: a grid lays its set once per item (#foto[1], #foto[2]…); a module per use
const grid = (name, frames, columns, placement, more, width = MEASURE) => ({ name, kind: 'grid',
  columns, columnGap: mm(5), rowGap: mm(CJK ? 8 : 12), repeat: { frames },
  placement: { ...placement, size: { width: mm(width), height: 'fill' } }, ...more });
const question = { id: 'pregunta', role: 'module', // a question and the lines to answer it on
  frames: [box('caja', 'dato', CJK ? 22 : 14, { width: 'fill' }), { ...answer('lineas',
    CJK ? 2 : 3), width: 'fill', placement: at('#caja', 'below', 0, CJK ? 4 : 7) }] };
// #endregion
const under = ({ placement, ...frame }) => ({ ...frame, width: mm(TALL - DOWN) }); // the map's
const stack = (name, frames, more) => ({ name, kind: 'stack', frames, gap: mm(CJK ? 8 : 12),
  ...more });
const pageTemplates = [
  base,
  topic('tema-agua', 'agua', {
    frames: [
      { name: 'foto', style: 'foto' },
      box('probar', 'palabras', CJK ? 30 : 46, { placement: at('#foto[1]', 'below', 0, 10) }),
      ...[['sabias', 'dato', 40], ['palabras', 'palabras', CJK ? 50 : 62],
        ['actividades', 'actividad', CJK ? 46 : 58]].map((f) => box(...f, { placement: onSecond })),
    ],
    groups: [grid('fotos', ['foto'], 3, at('#texto', 'below', 0, 8), { rowAlign: 'start' }),
      stack('derecha', ['sabias', 'palabras', 'actividades'])],
  }),
  topic('tema-campo', 'campo', {
    frames: [
      { name: 'mapa', crossGutter: true, width: mm(CJK ? DOWN - 6 : SHEET),
        ...(CJK && { height: mm(SHEET), placement: at('container', 'top-left') }) },
      ...(CJK ? [{ ...under(title), placement: at('container', 'top-left', DOWN) },
        under({ name: 'texto', flow: true, columns: 1 }), under(box('actividad', 'actividad', 24))]
        : [box('actividad', 'actividad', 24)]),
      { name: 'curso', style: 'dato', minHeight: mm(46) },
    ],
    groups: [
      stack('izquierda', CJK ? ['titulo', 'texto', 'actividad'] : ['titulo', 'mapa', 'texto',
        'actividad'], { gap: mm(6), ...(CJK && { placement: at('container', 'top-left', DOWN) }) }),
      grid('cursos', ['curso'], CJK ? 1 : 3, CJK ? at('container', 'top-left', DOWN, RIGHT)
        : at('#mapa', 'below', RIGHT, 6), { columnGap: mm(6), rowGap: mm(6) },
        CJK ? TALL - DOWN : MEASURE),
    ],
  }),
  topic('tema-sol', 'sol', {
    frames: [
      ...withPic('cuidar', 'palabras', CJK ? 52 : 64), box('turno', 'actividad', CJK ? 30 : 40),
      ...withPic('uso', 'dato', CJK ? 52 : 66),
    ],
    groups: [stack('izquierda', ['titulo', 'texto', 'cuidar', 'turno']),
      grid('usos', ['uso', 'uso-foto'], 1, onSecond, { rowAlign: 'start' })],
  }),
  { id: 'saberes', header: false,
    decoration: { elements: [titleTab()] },
    frames: [{ ...title, style: 'titulo-plano' },
      { name: 'texto', flow: true, width: mm(MEASURE) }],
    groups: [stack('pagina', ['titulo', 'texto'], { gap: mm(CJK ? 4 : 7) }),
      { name: 'preguntas', modules: true, gap: mm(CJK ? 4 : 7), placement: { ...at('#texto',
        'below', 0, CJK ? 4 : 7), size: { width: mm(MEASURE), height: 'fill' } } }] },
  question,
  // The contents: a frame takes the :::toc and lays it by the contents' own rules.
  { id: 'indice',
    decoration: { elements: [ground(), titleTab()] },
    frames: [{ ...title, style: 'titulo-plano' },
      { name: 'lista', takes: 'toc', width: mm(MEASURE) },
      { name: 'mapa', style: 'foto', width: mm(CJK ? 44 : HALF), ...(CJK && { height: mm(76) }) }],
    groups: [{ name: 'pagina', kind: 'stack', gap: mm(7), frames: ['titulo', 'lista', 'mapa'] }] },
  // The opener: a painting to the bleed, the title over its foot (down its right when vertical).
  { id: 'unidad', header: false, footer: false,
    decoration: { elements: [
      { kind: 'image', id: 'portada', resourceId: 'portada', decorative: true,
        placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: mm(157.5) } } },
      { kind: 'text', id: 'kicker', content: '{attr.unidad}', fontFamily: DISPLAY, fontSize: pt(11),
        fontWeight: fw(600), letterSpacing: pt(track(1)), textTransform: CAPS, color: col('agua'),
        align: START, box: { backgroundColor: col('paper'), borderRadius: mm(2), padding: {
          left: mm(2), right: mm(2) } }, placement: { ...at('#titulo', corner('top'), 0, -9),
          size: { height: mm(7), ...(CJK && { width: mm(60) }) } } }, // the room over capitals
    ] },
    frames: [
      { name: 'titulo', takes: 'h1', style: 'portada', width: mm(CJK ? TALL - 104 : 120),
        placement: CJK ? at('container', 'top-left', 104) : at('container', 'top-left', 0, 104) },
      { name: 'texto', flow: true, width: mm(CJK ? TALL - 142 : 160) },
      box('aprenderas', 'dato', 36, CJK ? { width: mm(TALL - 142) } : {}),
      { name: 'colofon', style: 'colofon', width: mm(CJK ? TALL - 142 : HALF),
        placement: at('container', CJK ? 'bottom-right' : 'bottom-left') },
    ],
    groups: [{ name: 'pagina', kind: 'stack', gap: mm(7), ...(CJK
      ? { frames: ['texto', 'aprenderas'], placement: at('container', 'top-left', 142, 26) }
      : { frames: ['titulo', 'texto', 'aprenderas'] }) }] },
];

// The running heads and the folios, on the outer side: an even page's left when left-bound.
const outside = (parity) => (parity === 'even') !== RIGHT_BOUND ? 'left' : 'right';
const outer = (parity, v, x, y) => at('page', `${v}-${outside(parity)}`,
  outside(parity) === 'left' ? x : -x, y);
const head = (id, content, parity) => ({ kind: 'text', id, content, parity,
  fontFamily: LATIN ? TEXT : DISPLAY, fontSize: pt(8), fontWeight: LATIN ? 700 : fw(500),
  letterSpacing: pt(track(1)), color: col('muted'), textTransform: CAPS, align: outside(parity),
  placement: outer(parity, 'top', PAGE.outer, 9) });
const folio = (id, parity) => ({ kind: 'text', id, content: '{pageNumber}', parity,
  fontFamily: DISPLAY, fontSize: pt(11), fontWeight: fw(600), color: col('paper'), align: 'center',
  box: { backgroundColor: col('agua'), borderRadius: mm(4) },
  placement: { ...outer(parity, 'bottom', PAGE.outer, -8), size: { width: mm(8), height: mm(8) } },
});

// #region contents: the toc settings; a frame of the 'indice' template takes the :::toc
const partAt = (x) => (CJK ? at('container', 'left', x) : at('container', START, inward(x)));
const toc = {
  levels: [{ level: 1, fontFamily: DISPLAY, fontSize: pt(15), lineHeight: pt(22),
    fontWeight: fw(500), color: col('ink'), numberFontWeight: fw(600), numberColor: col('agua'),
    numberWidth: mm(9), marginTop: pt(4) }, { level: 2, fontFamily: TEXT, fontSize: pt(11.5),
    lineHeight: pt(18), indent: mm(9), color: col('ink') }],
  pageNumber: { fontFamily: DISPLAY, fontWeight: fw(500), width: mm(9), color: col('agua') },
  leader: { char: CJK ? '…' : '.', gap: mm(1.5) },
  parts: { height: pt(34), marginTop: pt(12), marginBottom: pt(4), design: { elements: [
    { kind: 'box', id: 'band',
      placement: { ...at('container', 'top-left'), size: { width: 'fill', height: 'fill' } },
      style: { backgroundColor: col('paper'), borderRadius: mm(3) } },
    { kind: 'text', id: 'letter', content: '{number}', fontFamily: DISPLAY, fontSize: pt(16),
      fontWeight: fw(700), color: col('paper'), align: 'center',
      box: { backgroundColor: col('agua'), borderRadius: mm(4) },
      placement: { ...partAt(2), size: { width: mm(8), height: mm(8) } } },
    { kind: 'text', id: 'name', content: '{titleText}', fontFamily: DISPLAY, fontSize: pt(13),
      fontWeight: fw(600), color: col('agua'), align: START, placement: partAt(14) },
  ] } },
};
// #endregion

// #region art-labels: the map's label styles and anchors; the words are in the Markdown
// An anchor is a point of the painting (fractions of its width and height) and a label style;
// every language's ::label lines use the same anchors. A right-bound book shows the painting
// mirrored, the mountains on the right, so the river runs the way its pages are read: x comes
// from the other edge and a turn goes the other way. `start` is a label's own start, so the
// spring's label keeps it in Arabic and takes `end` in a label set left to right.
const halo = { color: col('paper'), width: pt(1.8) };
const labelStyles = [
  { id: 'sierra', fontFamily: DISPLAY, fontSize: pt(13), fontWeight: fw(600), color: col('ink'),
    textTransform: CAPS, letterSpacing: track(0.14), halo },
  { id: 'agua', fontFamily: TEXT, fontSize: pt(11), fontWeight: BOLD, fontStyle: SLANT,
    color: { hex: '#0b3a5c', model: 'hex' }, halo, // a name set away draws a leader to its point
    leader: { width: pt(1), endCap: 'dot', capSize: mm(1.6) } },
  { id: 'mar', fontFamily: TEXT, fontSize: pt(12), fontWeight: BOLD, fontStyle: SLANT,
    color: col('paper'), halo: { color: { hex: '#0b3a5c', model: 'hex' }, width: pt(1.8) } },
  { id: 'pueblo', fontFamily: DISPLAY, fontSize: pt(12), fontWeight: fw(600), color: col('ink'),
    halo },
  { id: 'curso', fontFamily: DISPLAY, fontSize: pt(10.5), fontWeight: fw(600), color: col('paper'),
    textTransform: CAPS, letterSpacing: track(0.08), background: col('campo'),
    padding: mm(1.6) },
];
const ANCHORS = [
  { id: 'sierra', x: 0.21, y: 0.055, style: 'sierra' },
  // The spring and the dam: the point is the place, `labelAt` where its name stands.
  { id: 'nacimiento', x: 0.049, y: 0.098, labelAt: { x: 0.075, y: 0.115 }, style: 'agua',
    align: 'start' },
  { id: 'fontalba', x: 0.135, y: 0.255, style: 'pueblo', verticalAlign: 'top' },
  { id: 'embalse', x: 0.293, y: 0.275, labelAt: { x: 0.31, y: 0.155 }, style: 'agua',
    width: 0.12 },
  { id: 'molinar', x: 0.505, y: 0.35, style: 'pueblo', verticalAlign: 'bottom' },
  { id: 'aldamar', x: 0.845, y: 0.505, style: 'pueblo', verticalAlign: 'bottom' },
  { id: 'mar', x: 0.965, y: 0.28, style: 'mar' },
  { id: 'rio', x: 0.61, y: 0.715, style: 'agua', rotate: -3 },
  { id: 'alto', x: 0.17, y: 0.45, style: 'curso' },
  { id: 'medio', x: 0.4, y: 0.77, style: 'curso' },
  { id: 'bajo', x: 0.74, y: 0.865, style: 'curso' },
];
const flip = (x) => Math.round((1 - x) * 1000) / 1000;
const flipped = (a) => ({ ...a, x: flip(a.x), ...(a.labelAt && { labelAt: { ...a.labelAt,
    x: flip(a.labelAt.x) } }),
  ...(a.rotate && { rotate: -a.rotate }), ...(a.align && !AR && { align: 'end' }) });
const anchors = RIGHT_BOUND ? ANCHORS.map(flipped) : ANCHORS;
// #endregion

const config = {
  canvasViewer: { pageGap: 0 }, // the Canvas joins the two pages of a spread
  locale: t({ es: 'es', en: 'en-gb', ca: 'ca', pt: 'pt-BR', fr: 'fr', de: 'de', it: 'it',
    ar: 'ar', zh: 'zh-Hans', ja: 'ja' }), // written out: Arabic sets its pages right to left
  resourceTypes: [{ id: 'dibujo', name: t({ es: 'Dibujo', en: 'Picture', ca: 'Dibuix',
    pt: 'Desenho', fr: 'Dessin', de: 'Bild', it: 'Disegno', ar: 'رسم', zh: '图', ja: '絵' }),
  shortLabel: '', numberingTemplate: '', resetOn: 'never', counterFormat: 'decimal',
  captionPrefix: '', defaultPlacement: { position: 'here' } }],
  colorPalette,
  page: { sizePreset: 'custom', width: mm(PAGE.w), height: mm(PAGE.h), dpi: 150, margins: {
    top: mm(PAGE.top), bottom: mm(PAGE.bottom), left: mm(PAGE.inner), right: mm(PAGE.outer),
    mirror: true } },
  layout: { layoutType: 'single', ...(CJK && { writingMode: 'vertical-rl' }) }, // right-bound
  bodyText: { fontFamily: TEXT, fontSize: pt(12), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    boldFontWeight: BOLD, textAlign: CJK ? 'justify' : 'left', firstLineIndent: CJK ? em(1) : pt(0),
    paragraphSpacing: !CJK, hyphenation: { enabled: LATIN }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: DISPLAY, fontWeight: fw(600), color: col('ink'), levels: [{ level: 1,
    fontSize: pt(28), lineHeight: pt(AR ? 40 : 32), color: col('paper'), marginTop: pt(0),
    marginBottom: pt(0), breakBefore: { enabled: false } }, { level: 2, fontSize: pt(15),
    lineHeight: pt(AR ? 24 : 19), marginTop: pt(9), marginBottom: pt(3) }] },
  headingStyles: [{ id: 'portada', numbered: false, toc: false, fontSize: pt(46),
    lineHeight: pt(AR ? 64 : 48) }, { id: 'previo', numbered: false, toc: false }],
  toc,
  parts: { page: false }, // a part is a row of the contents, with no divider page
  unorderedLists: { bulletChar: '•', color: col('agua'), fontWeight: BOLD, itemSpacing: pt(3) },
  orderedLists: { numberFormat: { zh: 'simp-chinese-informal', ja: 'japanese-informal' }[LANG]
    ?? 'arabic', fontFamily: DISPLAY, fontWeight: fw(600), color: col('agua'), itemSpacing: pt(4) },
  labelStyles,
  captionStyle: { fontFamily: TEXT, fontSize: pt(9), color: col('ink'), descriptionItalic: LATIN,
    gap: pt(4) },
  calloutStyles,
  header: { elements: [head('materia', '{subtitle}', 'even'), head('unidad', '{title}', 'odd')] },
  footer: { elements: [folio('folio-par', 'even'), folio('folio-impar', 'odd')] },
  pageTemplates,
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "Our river"
subtitle: "Social science · Year 3"
---

::::page{template="unidad" unidad="Unit 4 · Social science"}
# Our river {style="portada"}

Every town you know stands near water. This unit follows one river, the Aldara, from the snow where it starts to the sea where it ends. You will find out where a river is born, how it changes on its way down, and how the people of Fontalba, Molinar and Aldamar live beside it.

:::frame{slot="aprenderas" label="You will learn"}
- How a spring becomes a stream, and a stream becomes a river.
- What the upper, middle and lower course of a river are.
- How people use river water, and how to look after it.
:::

:::frame{slot="colofon"}
Set in Nunito and Fredoka (SIL OFL) · Original text (CC BY 4.0) · Illustrations generated with diffusion models
:::
::::

::::page{template="indice"}
# In this unit {style="previo"}

:::toc{keep="part" levels="1-2"}

:::figure{resource="rio" slot="mapa"}
::alt[Painted map of the valley of the River Aldara, from the snowy mountains to the sea.]
::caption[The River Aldara from its spring to the sea. The map is on pages 6 and 7.]
:::
::::

::::page{template="saberes"}
# What do you know about rivers? {style="previo"}

Before you start, think about the rivers you have seen. Write your ideas on the lines. At the end of the unit, come back to them and see what has changed.

:::module{template="pregunta"}
:::frame{slot="caja" label="Think 1"}
Where do you think a river starts?
:::
:::

:::module{template="pregunta"}
:::frame{slot="caja" label="Think 2"}
What do people use a river for?
:::
:::

:::module{template="pregunta"}
:::frame{slot="caja" label="Think 3"}
Which animals and plants live in or beside a river?
:::
:::
::::

:::part{number="A" title="A river from the mountains to the sea"}
:::

::::page{template="tema-agua" spread}
# Where a river is born

Rain and snow fall on the mountains. Some of the water runs down the slopes and some soaks into the ground. Underground it moves slowly, until it meets rock it cannot cross. Then it comes out into the open. A place where water comes out of the ground is called a **spring**.

## From spring to stream

A spring gives only a trickle. The trickle runs downhill and meets other trickles, and together they make a **stream**. On a steep slope a stream runs fast. It rolls pebbles along and wears them smooth. When streams meet, they make a bigger one. The River Aldara begins like this, in the snow of the White Range, 1,850 metres above the sea.

:::figure{resource="nacimiento" slot="foto"}
::alt[Clear water trickling out between mossy rocks.]
::caption[A spring. The water has been underground for months.]
:::

:::figure{resource="arroyo" slot="foto"}
::alt[A stream tumbling over round stones.]
::caption[A stream, steep and fast, with pebbles worn smooth.]
:::

:::figure{resource="cascada" slot="foto"}
::alt[A small waterfall falling into a green pool.]
::caption[A waterfall, where the stream drops over a step of rock.]
:::

:::frame{slot="probar" label="Try it"}
Hold a wet sponge over a tray and squeeze it gently. Where does the water come out? Watch how it drips and then runs. That is how a spring feeds a stream.
:::

:::frame{slot="sabias" label="Did you know?"}
At its spring, the Aldara is a trickle you could step over. After 94 kilometres it is as wide as a football pitch is long.
:::

:::frame{slot="palabras" label="Words to learn"}
**Spring:** a place where water comes out of the ground.

**Stream:** a small river that runs fast down a slope.

**Tributary:** a stream that flows into a bigger river.

**Bank:** the land along the side of a river.
:::

:::frame{slot="actividades" label="Activities"}
1. Look at the three pictures. Which one shows a spring? How can you tell?
2. Why does a stream run faster in the mountains than in the valley?
3. Which of the four words in the box can you see in the pictures?
:::
::::

::::page{template="tema-campo" spread}
# From the mountains to the sea

The River Aldara is 94 kilometres long. It starts in the White Range, crosses a valley and a plain, and reaches the sea at Aldamar. Geographers split a river into three parts. Each part is called a **course**, and each one looks different.

:::figure{resource="mapa" slot="mapa"}
::alt[A painted map of the valley: snowy mountains and a spring at the left, the village of Fontalba, a reservoir with a dam, the town of Molinar with its bridge and mill, farm fields, the river bending across a plain, and the port of Aldamar by the sea at the right.]
::label[White Range]{at="sierra"}
::label[Spring]{at="nacimiento"}
::label[Fontalba]{at="fontalba"}
::label[Penalta Reservoir]{at="embalse"}
::label[Molinar]{at="molinar"}
::label[Aldamar]{at="aldamar"}
::label[Sea]{at="mar"}
::label[River Aldara]{at="rio"}
::label[Upper course]{at="alto"}
::label[Middle course]{at="medio"}
::label[Lower course]{at="bajo"}
:::

:::frame{slot="actividad" label="Look at the map"}
Follow the river with your finger from the spring to the sea. Which town is nearest to the sea?
:::

:::frame{slot="curso" label="Upper course"}
The slope is steep. The water is cold, clear and fast, and it cuts into the rock. Fontalba stands here.
:::

:::frame{slot="curso" label="Middle course"}
The valley is wider and the river slows down. Farmers water their fields, and Molinar grew around a bridge and a mill.
:::

:::frame{slot="curso" label="Lower course"}
The land is almost flat. The river is wide and slow, and it bends in great loops. At Aldamar it flows into the sea.
:::
::::

:::part{number="B" title="People and the river"}
:::

::::page{template="tema-sol" spread}
# People and the river

People have always settled near rivers. They need water to drink, to wash and to grow food. A river also gives fish, a road for boats and the push that turns a wheel.

## Looking after the river

A river stays clean only if we keep it clean. Rubbish, oil and dirty water make the river sick, and the fish and plants that live in it suffer. Everything that goes down a drain or a street ends up in a river or in the sea.

:::frame{slot="cuidar" label="We look after our river"}
- We put rubbish in the bin, never in the water.
- We use water carefully and turn off the tap.
- We keep to the paths and leave plants and animals alone.
- We help to clean the bank when the school organises it.
:::

:::frame{slot="turno" label="Your turn"}
1. Draw a poster with three rules to keep our river clean.
2. Ask at home: where does the water from your tap come from?
:::

:::figure{resource="limpieza" slot="cuidar-foto"}
::alt[Children with gloves and paper bags picking up litter on a river bank.]
:::

:::frame{slot="uso" label="1 · Water for the fields"}
In the middle course, farmers open small canals so the river water runs between the rows. Without it, tomatoes and lettuces would not grow in summer. A single canal can carry water for many kilometres.

:::figure{resource="riego" slot="uso-foto"}
::alt[A farmer lifting a gate in an irrigation canal in a field of vegetables.]
:::
:::

:::frame{slot="uso" label="2 · Mills"}
Long ago the falling water turned the wheel of the mill at Molinar. The wheel moved the stones that ground wheat into flour for the whole valley. Today the old mill is a small museum.

:::figure{resource="molino" slot="uso-foto"}
::alt[An old stone mill with a big wooden wheel beside a river.]
:::
:::

:::frame{slot="uso" label="3 · Sport and play"}
Now the calm lower course is a place for canoes. On summer mornings children from Aldamar learn to paddle with a monitor, and everyone wears a life jacket.

:::figure{resource="piraguas" slot="uso-foto"}
::alt[Children in life jackets paddling two canoes on a calm river.]
:::
:::
::::
`; // content.<lang>.md, inlined by the Cookbook

// #region art: nine paintings (JPEGs in assets/), the pictures of the unit
// Painted with a diffusion model in a coloured-pencil and watercolour manner, cut to the shape
// of the frames that show them and declared with their pixels. Nothing is written on them: the
// names on the map are ::label lines of the Markdown, standing at the anchors above. A
// right-bound book's map is the same painting mirrored.
const ART = { portada: ['portada-1400.jpg', 1400, 1021, 165],
  mapa: [RIGHT_BOUND ? 'mapa-1900-rtl.jpg' : 'mapa-1900.jpg', 1900, 730, 122],
  ...Object.fromEntries(['nacimiento', 'arroyo', 'cascada', 'riego', 'molino', 'piraguas',
    'limpieza'].map((id) => [id, [`${id}-720.jpg`, 720, 540, 330]])) };
const resources = await Promise.all(Object.entries(ART).map(async ([id, [fileId, w, h, ppi]]) => {
  await loadImage(fileId, asset(fileId));
  return { id, typeId: 'dibujo', kind: 'bitmap', caption: '', altText: '', createdAt: 0,
    updatedAt: 0, bitmap: { fileId, format: 'jpeg', width: w, height: h, resolution: ppi },
    ...(id === 'mapa' && { anchors }) };
}));
// The map again with no anchors, small, under the contents.
resources.push({ ...resources.find((r) => r.id === 'mapa'), id: 'rio', anchors: [] });
// #endregion

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
// Every face of the ten editions; each loads its own two, with the cjk and arabic blocks' files.
const FONTS = {
  Nunito: ['400', '400i', '700'], Fredoka: ['500', '600', '700'],
  'Noto Naskh Arabic': ['400', '700'], 'Baloo Bhaijaan 2': ['500', '600', '700'],
  'Klee One': ['400', '600'], 'Zen Maru Gothic': ['500', '700'], // a textbook hand, rounded heads
  'Noto Serif SC': ['400', '700'], 'ZCOOL KuaiLe': ['400'],
};
for (const face of Object.keys(FONTS)) if (![TEXT, DISPLAY].includes(face)) delete FONTS[face];
await loadFonts(FONTS, markdown);
await loadCjkFonts(FONTS, markdown, { vertical: CJK });
await loadArabicFonts(FONTS, markdown);

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await withLoadedFonts(() => buildDocument({ markdown, resources }, config),
  { ...kitFonts(FONTS), text: markdown });
showBook(doc, { title: t({ es: 'Nuestro río', en: 'Our river', ca: 'El nostre riu',
  pt: 'Nosso rio', fr: 'Notre fleuve', de: 'Unser Fluss', it: 'Il nostro fiume', ar: 'نهرنا',
  zh: '我们的河流', ja: 'わたしたちの川' }) });
offerPdf(() => renderToPdf(doc, { resourceBytes: imageBytes,
  fontProvider: { zh: cjkPdfProvider, ja: cjkPdfProvider, ar: arabicPdfProvider }[LANG]
    ?? fontsourceProvider }), `${RECIPE}.pdf`);

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

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

// ─── Kit · fonts 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 · pdf v3 ── the same in every recipe that exports a PDF
/** The Fontsource files the screen used, as TrueType, with their range and
 *  place: the nearest weight the family ships in that style, upright with no italic;
 *  latin, then what its letters need (kitSubsetsFor). */
async function fontsourceProvider(family, weight, style, request) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  const s = style === 'italic' && meta && !meta.styles.includes('italic') ? 'normal' : style;
  const shipped = meta ? await fontsourceWeights(family, s) : [];
  const weights = shipped.length ? shipped : [400, 700];
  const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const text = String.fromCodePoint(...(request?.codePoints ?? []));
  const files = await Promise.all(['latin', ...kitSubsetsFor(text, meta)].map(async (subset, order) => {
    const res = await fetch(`${await fontsourceAt(id)}files/${id}-${subset}-${w}-${s}.woff2`);
    if (!res.ok) throw new Error(`Fontsource has no ${family} ${w} ${s} ${subset}`);
    return Object.assign(await decompressWoff2(new Uint8Array(await res.arrayBuffer())),
      { unicodeRange: kitRanges()[subset], order });
  }));
  return files.length === 1 ? files[0] : files;
}

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

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

/** Registers SVG markup as a vector image, its fonts inside (inlineSvgFonts, ≥ 1.25).
 *  `options` go to registerResourceImage: { singleInk: true } tints it on the canvas. */
async function loadSvg(fileId, svg, options) {
  if (typeof inlineSvgFonts === 'function') svg = await inlineSvgFonts(svg, svgFaces);
  const img = new Image();
  img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
  await img.decode();
  registerResourceImage(fileId, img, options);
  (loadImage.bytes ??= new Map()).set(fileId, new TextEncoder().encode(svg));
}

/** A face's Fontsource files: nearest weight; latin + what the SVG sets. */
async function svgFaces(family, weight, style, { codePoints = [] } = {}) {
  const [id, m] = [fontsourceId(family), await fontsourceMeta(family)];
  const w = m?.weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a)) ?? weight;
  const s = m?.styles.includes(style) === false ? 'normal' : style;
  return Promise.all(['latin', ...kitSubsetsFor(String.fromCodePoint(...codePoints), m)].map(async (x) => new Uint8Array(
    await (await fetch(`${await fontsourceAt(id)}files/${id}-${x}-${w}-${s}.woff2`)).arrayBuffer())));
}

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

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

// ─── Kit · cjk 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 ───────────────────────────────────────────────────────────────────────
```

## Варианты

### Добавьте четвёртое семейство

Тема о море — это четвёртая запись в `FAMILIES` и шаблон, созданный вызовом `topic('tema-mar', 'mar', { frames })`. `swap('mar')` записывает его палитру, а врезки и фон ей следуют.

```diff
-  sol: { main: '#9a5209', tint: '#fcefd2', ground: '#f8e6b8' },
+  sol: { main: '#9a5209', tint: '#fcefd2', ground: '#f8e6b8' },
+  mar: { main: '#0f5a6b', tint: '#dcf0f2', ground: '#cbe6ea' },
```

### Сохраните кегль текста

Фрейм, который не должен уменьшать свой текст, получает `fit: { shrinkText: false }`. Тогда более длинный текст сильнее давит на соседние фреймы, и лестница первыми уменьшает картинки.

```diff
   frames: [title, { name: 'texto', flow: true, columns: 2, columnGap: mm(CJK ? 16 : 7), // 段
-    width: mm(MEASURE), fit: { minScale: 0.9 } }],
+    width: mm(MEASURE), fit: { shrinkText: false } }],
```

## Частые ошибки

- Название, нарисованное в картинке, не сменится вместе с языком: на карте нет ни слова, все названия — подписи.
- Палитра темы меняет только записи `tema`. Колонцифры и содержание берут `agua`, где тот же синий, поэтому на зелёных и песочных страницах они остаются синими; свяжите их с `tema`, и они последуют за темой.
- Арабско-индийская цифра рядом с точкой посередине строки читается как две цифры: `١ · ماء` похоже на `٠١ ماء`, потому что арабский ноль — это точка. В арабском издании написано `١- ماء للحقول`, а номер темы дан словом.
- Элемент декора стоит на листе, а не в потоке: значок, поставленный в `top-left` фрейма, остаётся слева и в арабской книге. `corner('top')` и `inward(x)` размещают его от стороны, с которой начинают читать страницу.
- В сетке каждый элемент — отдельный блок: картинка врезки входит в её набор, только если её `:::figure` написан внутри `:::frame` врезки. Написанная после него, картинка становится отдельным элементом и занимает собственную ячейку.
- Два рисунка с одним и тем же ресурсом берут слова первого: маленькая карта на странице содержания — тот же файл под отдельным ресурсом `rio`, без якорей.

## Источники и лицензии

- Рецепт: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Текст: Our river, a children's textbook unit written for this recipe in Spanish and set in ten languages: Postext Cookbook, CC-BY-4.0
- Изображения: The valley of the River Aldara, painted from the mountains to the sea, with two children watching the water.: Generated With Diffusion Models, оригинал
- Изображения: The painted map of the valley, from the spring to the port, with no lettering: the names are labels set from the Markdown.: Generated With Diffusion Models, оригинал
- Изображения: The same painted map mirrored, the mountains on the right, for the books bound on the right (Arabic, Chinese, Japanese).: Generated With Diffusion Models, оригинал
- Изображения: A spring between mossy rocks.: Generated With Diffusion Models, оригинал
- Изображения: A mountain stream over round stones.: Generated With Diffusion Models, оригинал
- Изображения: A small waterfall into a green pool.: Generated With Diffusion Models, оригинал
- Изображения: A farmer opening the gate of an irrigation canal.: Generated With Diffusion Models, оригинал
- Изображения: An old stone watermill with its wheel.: Generated With Diffusion Models, оригинал
- Изображения: Children paddling canoes on a calm river.: Generated With Diffusion Models, оригинал
- Изображения: Children and a teacher picking up litter on a river bank.: Generated With Diffusion Models, оригинал
- Шрифты: Nunito (OFL-1.1), Fredoka (OFL-1.1), Noto Naskh Arabic (OFL-1.1), Baloo Bhaijaan 2 (OFL-1.1), Klee One (OFL-1.1), Zen Maru Gothic (OFL-1.1), Noto Serif SC (OFL-1.1), ZCOOL KuaiLe (OFL-1.1)
- Код: MIT · Образец содержания: CC-BY-4.0

## Похожие рецепты

- [№ 157 · Школьный атлас с надписями из Markdown](https://postext.dev/ru/cookbook/school-atlas-labelled-maps.md): Карты написаны без единой буквы: названия ставят строки ::label по якорям ресурса. Макетные страницы, карта на разворот, три языка. · Уровень 3 (Продвинутый) · Учебники
- [№ 158 · Иллюстрированная лента времени на развороте](https://postext.dev/ru/cookbook/illustrated-timeline-spread.md): Шаблон разворота ведёт ленту времени учебника через две страницы: полоса через корешок, сетка с карточкой на дату и линия к каждой карточке. · Уровень 3 (Продвинутый) · Учебники
- [№ 008 · Семейство врезок учебника с цветовым кодом](https://postext.dev/ru/cookbook/textbook-box-family.md): Шесть видов врезок учебника в трёх цветах: их различают полоса со значком, значок на углу, ярлык с номером, ряд пиктограмм или метка за рамкой. · Уровень 2 (Средний) · Учебники
