# Абай и пять поэтов степи, казахская антология

> Антология на восьми страницах и шести языках: казахская книга, по стихотворению на язык, глоссы внизу страницы и узоры войлочных ковров.

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

## Коротко

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

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

Дала үні («Голос степи») — тетрадь форматом 145 × 215 мм на восьми страницах. Обложка — войлочный ковёр из плиток с бараньими рогами над названием и оглавлением. «Слово первое» Абая и первая строфа его «Восьмистиший» занимают разворот; стихотворения на киргизском, татарском, башкирском, монгольском и таджикском получают по странице, под плашкой в цвете поэта с римской цифрой, названием, именем, годами жизни и языком. Старые и чужие слова объяснены по-казахски внизу страницы. Текст набран Alegreya, названия — Piazzolla. Языку издания следует только выходная заметка.

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

- Как набрать антологию на казахском, киргизском, татарском, башкирском, монгольском и таджикском?

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

```js
// script.js, строк 41–59
// The book is Kazakh: its hyphenation, the ties (a dash opens no line, a number keeps its unit)
// and its notes, which start again on every page with an indent of 1.5 em.
const LOCALE = 'kk';
// A poem in another language is a :::verse block that names it: the poem is shaped by that
// language and tagged with it in the PDF and the HTML, :::verse{lang=ky}.
// ky Kyrgyz, tt Tatar, ba Bashkir, mn Mongolian, tg Tajik. Two spaces at the head of a line
// draw it in, as in the third and sixth lines of «Сегіз аяқ».
const verse = { align: 'center', hang: em(2), keepStanzas: 8 }; // bodyText.verse
const bodyText = {
  fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('red'),
  textAlign: 'justify', firstLineIndent: em(1.5), minWordSpacing: 0.75, maxWordSpacing: 1.7,
  maxJustifyTracking: 15,
  hyphenation: { leftMin: 2, rightMin: 2 }, verse,
};
// The glosses are Kazakh, whatever the language of the word: жеме — сөгіс, кінә.
const footnotes = { fontFamily: TEXT, fontSize: pt(8.8), lineHeight: pt(11.5),
  color: col('muted'), separator: { enabled: true, width: 0.2, lineWidth: pt(0.6),
    color: col('gold') } };
```

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

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

- [Языки с кириллицей как язык документа](https://postext.dev/ru/docs/cyrillic-layout.md#как-начать-книгу-на-кириллице): locale 'ru', 'uk', 'be', 'bg', 'sr', 'mk', 'kk', 'ky', 'tt', 'ba', 'tg' или 'mn' даёт книге переносы, подписи, заголовки таблиц, сноски, числа прописью, форматы бумажного листа и направление надписи на корешке, принятые в её языке.
- [Стихи строка за строкой](https://postext.dev/ru/docs/document-format-directives.md#verse): :::verse набирает стихотворение так, как оно записано: одна стихотворная строка на строку Markdown, пустые строки между строфами, пробелы в начале как отступы; слишком длинная строка переходит на следующую с втяжкой или вправо за скобкой, при разрыве страницы не отрывается от продолжения, а короткие строфы можно не разрывать.
- [Сноски](https://postext.dev/ru/docs/document-format-notes-references.md#сноски): Примечания со ссылкой [^id], набранные внизу колонки, где стоит ссылка, или после главы, с нумерацией по главам или сквозной по книге.

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

- [Слова, не разделяемые на конце строки](https://postext.dev/ru/docs/cyrillic-layout.md#слова-которые-не-разрывают)
- [Перенос слов и язык документа](https://postext.dev/ru/docs/justification.md#поддерживаемые-языки)
- [Содержание](https://postext.dev/ru/docs/configuration-notes-references.md#содержание)
- [Нумерованные заголовки](https://postext.dev/ru/docs/configuration-headings.md#переопределения-для-уровней)
- [Оформленные начальные полосы](https://postext.dev/ru/docs/configuration-headings.md#ширина-и-расширенный-дизайн)
- [Стили заголовков](https://postext.dev/ru/docs/configuration-styles.md#стили-заголовков)
- [Атрибуты заголовков](https://postext.dev/ru/docs/document-format.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/configuration-styles.md#стили-заголовков)
- [Метаданные документа](https://postext.dev/ru/docs/document-format.md#метаданные-frontmatter)
- [Главы без номера](https://postext.dev/ru/docs/configuration-styles.md#стили-заголовков)
- [Зеркальные поля](https://postext.dev/ru/docs/configuration-page-layout.md#зеркальные-поля)
- [Отступы, выключка и отбивка абзацев](https://postext.dev/ru/docs/configuration-text.md#основной-текст)
- [Семантическая палитра](https://postext.dev/ru/docs/configuration-fonts-colors-viewers.md#палитра-цветов)
- [Экспорт в PDF](https://postext.dev/ru/docs/configuration-pdf-output.md#создание-pdf)
- [Цвет бумаги](https://postext.dev/ru/docs/configuration-page-layout.md#страница)
- [Стили абзацев](https://postext.dev/ru/docs/configuration-styles.md#стили-абзацев)
- [Шрифты, встроенные в PDF](https://postext.dev/ru/docs/configuration-pdf-output.md#зачем-нужен-провайдер-шрифтов)
- [Рисунки и таблицы как ресурсы](https://postext.dev/ru/docs/document-format-resources.md#ресурсы)
- [Колонтитулы разделов](https://postext.dev/ru/docs/configuration-styles.md#стили-заголовков)

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

- [`bodyText`](https://postext.dev/ru/docs/configuration-text.md#основной-текст), [`colorPalette`](https://postext.dev/ru/docs/configuration-fonts-colors-viewers.md#палитра-цветов), [`footer`](https://postext.dev/ru/docs/configuration-headers-footers.md#верхние-и-нижние-колонтитулы), [`footnotes`](https://postext.dev/ru/docs/configuration-notes-references.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#заголовки), [`layout`](https://postext.dev/ru/docs/configuration-page-layout.md#колонки), [`locale`](https://postext.dev/ru/docs/configuration-language.md#перенос-слов), [`page`](https://postext.dev/ru/docs/configuration-page-layout.md#страница), [`paragraphStyles`](https://postext.dev/ru/docs/configuration-styles.md#стили-абзацев), [`toc`](https://postext.dev/ru/docs/configuration-notes-references.md#содержание)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/ru/docs/configuration-programmatic-usage.md#загрузка-шрифтов-перед-вёрсткой), [`decompressWoff2`](https://postext.dev/ru/docs/configuration-pdf-output.md#провайдер-шрифтов-в-браузере-fontsource--woff2), [`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)

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

- Alegreya (OFL-1.1), Alegreya Sans (OFL-1.1), Piazzolla (OFL-1.1)

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

### 1 · Казахская книга и стихи ещё на пяти языках

Код — [короткий ответ](https://postext.dev/ru/cookbook/abai-kazakh-anthology.md#короткий-ответ) выше. `locale: 'kk'` задаёт книге [переносы](https://postext.dev/ru/docs/cyrillic-layout.md#перенос-слов-на-двенадцати-языках), [неразрывные слова](https://postext.dev/ru/docs/cyrillic-layout.md#слова-которые-не-разрывают) и [сноски](https://postext.dev/ru/docs/cyrillic-layout.md#сноски-по-страницам), которые на каждой странице считаются заново и набраны с отступом 1,5 em. Каждое из остальных стихотворений — блок `:::verse{lang=ky}`: оно набрано и помечено на своём языке в PDF и HTML. `align: 'center'` ставит стихотворение по центру по самой длинной строке, `keepStanzas: 8` держит строфу на одной странице, а два пробела в начале строки сдвигают её.

### 2 · Войлочная плашка в цвете поэта

```js
// script.js, строк 63–84
// # Үлгү ырлар {tone="blue" author="Тоқтоғұл Сатылғанов" when="1864–1933" tongue="қырғызша"}
const PANEL = 56; // mm: the panel's height, from the head of the page
const opener = { enabled: true, minHeight: mm(PANEL - TOP + 8), slot: { elements: [
  image('panel', 'panel-{attr.tone}', { ...at('page', 'top-left'), size: { width: mm(TRIM_W) } }),
  text('number', '{number}', DISPLAY, 17, 700, 'cream', at('container', 'top-left', 0, -10)),
  text('title', '{titleText}', DISPLAY, 21, 800, 'cream',
    { ...at('container', 'top-left', 0, -2.5), ...fill }),
  text('author', '{attr.author}', SANS, 12, 700, 'cream', at('container', 'top-left', 0, 11)),
  text('when', '{attr.when} · {attr.tongue}', SANS, 11, 400, 'cream',
    { ...at('container', 'top-right', 0, 11.3) }, { align: 'right' }),
] } };
// A second piece by the same poet goes on in the page, under a narrower border.
const runOn = { id: 'run-on', breakBefore: { enabled: false }, marginTop: pt(LEAD),
  marginBottom: pt(0), advancedDesign: { enabled: true, minHeight: pt(3.6 * LEAD), slot: {
    elements: [
      image('strip', 'strip', { ...at('container', 'top-left'), ...fill }),
      text('number', '{number}', DISPLAY, 13, 700, 'red', at('container', 'top-left', 0, 9)),
      text('title', '{titleText}', DISPLAY, 17, 800, 'red',
        at('container', 'top-left', 9, 7.8)),
      text('tongue', '{attr.tongue}', SANS, 10, 400, 'muted',
        at('container', 'top-right', 0, 10), { align: 'right' }),
    ] } } };
```

Заголовок несёт всё, что печатает плашка: `# Үлгү ырлар {tone="blue" author="Тоқтоғұл Сатылғанов" when="1864–1933" tongue="қырғызша"}`. `panel-{attr.tone}` называет рисунок, поэтому одно оформление служит четырём цветам, а тот же `author` попадает в оглавление и в нижний колонтитул. `numberingTemplate: '{1:I}'` пишет римскую цифру. Вторая вещь того же поэта набрана стилем `run-on`: без новой страницы и с узкой каймой.

### 3 · Оглавление на обложке

```js
// script.js, строк 88–106
const none = { numbered: false, toc: false, header: { elements: [] }, footer: { elements: [] } };
const RUG = 2 * (TRIM_W / 4); // mm: two rows of four tiles
const cover = { id: 'cover', ...none, marginBottom: pt(0), advancedDesign: { enabled: true,
  minHeight: mm(RUG - TOP + 41), slot: { elements: [
    image('rug', 'rug', { ...at('page', 'top-left'), size: { width: mm(TRIM_W) } }),
    text('title', '{titleText}', DISPLAY, 42, 800, 'red',
      at('page', 'top-left', INNER, RUG + 9)),
    text('subtitle', '{subtitle}', SANS, 13, 400, 'ink', at('#title', 'below', 0, 0.5)),
  ] } } };
const toc = {
  levels: [{ level: 1, fontFamily: DISPLAY, fontSize: pt(11), color: col('ink'),
    numberFontWeight: 700, numberColor: col('red'), numberWidth: mm(8), numberGap: mm(2),
    marginBottom: pt(2.5) }],
  pageNumber: { fontFamily: SANS, fontSize: pt(10), fontWeight: 700, color: col('red'),
    width: mm(5) },
  leader: { char: '. ', gap: mm(2) },
  subtitle: { enabled: true, attr: 'author', italic: false, fontFamily: SANS, fontSize: pt(9),
    color: col('muted') },
};
```

Заголовок обложки оставляет место для ковра и названия через `minHeight`, а `:::toc` идёт следом в потоке. `toc.subtitle` печатает под каждым названием его `author`. Сама обложка не нумеруется и в оглавление не входит.

### 4 · Бараньи рога из полуокружностей

```js
// script.js, строк 110–144
// A pair of horns is two half circles a side, radius 10 and then 6, on a stem; four pairs round
// a diamond make the tile, and a row of pairs, one up and one down, the border. The width of
// the stroke leaves as much ground as wool, so either colour can be read as the figure.
const horn = (side, sweep) => `M50 20 A10 10 0 0 ${sweep} ${50 + side * 20} 20 `
  + `A6 6 0 0 ${sweep} ${50 + side * 8} 20`;
const pair = `M50 40 V20 ${horn(-1, 0)} ${horn(1, 1)}`;
const horns = (colour, turn, w = 5.6) => `<path d="${pair}" transform="${turn}" fill="none" `
  + `stroke="${colour}" stroke-width="${w}" stroke-linecap="round" stroke-linejoin="round"/>`;
const shape = (d, colour, turn = '') => `<path d="${d}" fill="${colour}" transform="${turn}"/>`;
const tile = (x, y, ground, wool, spark) => `<g transform="translate(${x} ${y})">`
  + shape('M0 0H100V100H0Z', ground)
  + [0, 90, 180, 270].map((a) => horns(wool, `rotate(${a} 50 50)`)
    + shape('M0 0H17L0 17Z', spark, `rotate(${a} 50 50)`)).join('')
  + shape('M50 35L65 50L50 65L35 50Z', wool) + shape('M50 43L57 50L50 57L43 50Z', spark)
  + '</g>';
const UNIT = 50; // a pair of horns and its gap, in the border's units
const border = (n, colour, y) => Array.from({ length: n }, (_, i) => horns(colour, i % 2
  ? `translate(${i * UNIT - 25} ${y + 43}) scale(1 -1)`
  : `translate(${i * UNIT - 25} ${y - 3})`)).join('');
const teeth = (n, step, y, h, colour) => shape(Array.from({ length: n }, (_, i) =>
  `M${i * step} ${y}h${step}l${-step / 2} ${h}Z`).join(''), colour);
const svg = (w, h, body) => ({ width: w, height: h, markup: `<svg xmlns="http://www.w3.org/2000/`
  + `svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${body}</svg>` });
const { cream, gold } = palette;
const panel = (tone) => svg(600, 231.7, // the trim's width, 12 pairs of horns
  shape('M0 0H600V231.7H0Z', palette[tone]) + border(12, cream, 174)
  + shape('M0 160H600V163H0Z', cream) + teeth(48, 12.5, 222.7, 9, gold));
const rug = ['red', 'blue', 'green', 'ochre', 'blue', 'ochre', 'red', 'green'];
const ART = {
  rug: svg(400, 200, rug.map((tone, i) => tile((i % 4) * 100, Math.floor(i / 4) * 100,
    palette[tone], cream, gold)).join('')),
  strip: svg(1000, 60, shape('M0 0H1000V60H0Z', palette.red) + border(20, cream, 10)),
  ...Object.fromEntries(['red', 'blue', 'green', 'ochre']
    .map((tone) => [`panel-${tone}`, panel(tone)])),
};
```

Рог — это две полуокружности, радиусом 10, а потом 6, на общем стебле. Четыре пары вокруг ромба дают плитку; ряд пар, одна вверх, другая вниз, — кайму. Штрих и просвет близки по ширине, как в шырдаке, где один войлок вырезан под другой.

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

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

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

### script.js

```js
// ═══ Postext Cookbook · Nº 210 · A Kazakh anthology of six languages of the steppe ═══
// https://postext.dev/en/cookbook/abai-kazakh-anthology
// Code: MIT · Text: Abai, Toktogul, Tukay, Akmulla, Natsagdorj, Rudaki (PD) · Ornament: code
// Fonts: Alegreya, Alegreya Sans, Piazzolla (SIL OFL 1.1) · Needs postext ≥ 1.100.0
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'ru'; // @lang: the language of the colophon ('en' | 'es' | 'ru')
const RECIPE = 'abai-kazakh-anthology';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// The dyed felts of a shyrdak, the mosaic rug of the yurt: madder, indigo, pine and bark, all
// cut against undyed wool.
const palette = {
  ink: '#2a1d17', // text, brown-black wool
  red: '#9c2a26', // madder: Abai, Rudaki, the note marks
  blue: '#1f4e79', // indigo: Toktogul, Natsagdorj
  green: '#2f5d3a', // pine: Tukay
  ochre: '#8a5010', // bark: Akmulla
  gold: '#dba544', // the small triangles and diamonds
  cream: '#f5ecda', // the paper and the undyed wool
  muted: '#6b5647', // languages, dates, notes
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = Object.entries({ ...palette, 'main-color': palette.red })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
// All three hold ә ғ қ ң ө ұ ү һ, ҙ ҫ ҡ and ҷ ҳ ӣ ӯ in their cyrillic-ext files.
const [TEXT, SANS, DISPLAY] = ['Alegreya', 'Alegreya Sans', 'Piazzolla'];
const [BODY, LEAD] = [11, 14.5]; // pt
const [TRIM_W, TRIM_H, TOP, INNER, OUTER] = [145, 215, 22, 21, 19]; // mm: 60 × 90/16
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const text = (id, content, fontFamily, size, fontWeight, color, placement, extra = {}) => ({
  kind: 'text', id, content, fontFamily, fontSize: pt(size), fontWeight, color: col(color),
  align: 'left', lineHeight: 1.1, overflow: 'wrap', placement, ...extra });
const fill = { size: { width: 'fill' } };
const image = (id, resourceId, placement) => ({ kind: 'image', id, resourceId, placement });

// #region answer: a Kazakh document, with each poem named in its own language
// The book is Kazakh: its hyphenation, the ties (a dash opens no line, a number keeps its unit)
// and its notes, which start again on every page with an indent of 1.5 em.
const LOCALE = 'kk';
// A poem in another language is a :::verse block that names it: the poem is shaped by that
// language and tagged with it in the PDF and the HTML, :::verse{lang=ky}.
// ky Kyrgyz, tt Tatar, ba Bashkir, mn Mongolian, tg Tajik. Two spaces at the head of a line
// draw it in, as in the third and sixth lines of «Сегіз аяқ».
const verse = { align: 'center', hang: em(2), keepStanzas: 8 }; // bodyText.verse
const bodyText = {
  fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('red'),
  textAlign: 'justify', firstLineIndent: em(1.5), minWordSpacing: 0.75, maxWordSpacing: 1.7,
  maxJustifyTracking: 15,
  hyphenation: { leftMin: 2, rightMin: 2 }, verse,
};
// The glosses are Kazakh, whatever the language of the word: жеме — сөгіс, кінә.
const footnotes = { fontFamily: TEXT, fontSize: pt(8.8), lineHeight: pt(11.5),
  color: col('muted'), separator: { enabled: true, width: 0.2, lineWidth: pt(0.6),
    color: col('gold') } };
// #endregion

// #region opener: a felt panel in the poet's colour, named by the heading's attributes
// # Үлгү ырлар {tone="blue" author="Тоқтоғұл Сатылғанов" when="1864–1933" tongue="қырғызша"}
const PANEL = 56; // mm: the panel's height, from the head of the page
const opener = { enabled: true, minHeight: mm(PANEL - TOP + 8), slot: { elements: [
  image('panel', 'panel-{attr.tone}', { ...at('page', 'top-left'), size: { width: mm(TRIM_W) } }),
  text('number', '{number}', DISPLAY, 17, 700, 'cream', at('container', 'top-left', 0, -10)),
  text('title', '{titleText}', DISPLAY, 21, 800, 'cream',
    { ...at('container', 'top-left', 0, -2.5), ...fill }),
  text('author', '{attr.author}', SANS, 12, 700, 'cream', at('container', 'top-left', 0, 11)),
  text('when', '{attr.when} · {attr.tongue}', SANS, 11, 400, 'cream',
    { ...at('container', 'top-right', 0, 11.3) }, { align: 'right' }),
] } };
// A second piece by the same poet goes on in the page, under a narrower border.
const runOn = { id: 'run-on', breakBefore: { enabled: false }, marginTop: pt(LEAD),
  marginBottom: pt(0), advancedDesign: { enabled: true, minHeight: pt(3.6 * LEAD), slot: {
    elements: [
      image('strip', 'strip', { ...at('container', 'top-left'), ...fill }),
      text('number', '{number}', DISPLAY, 13, 700, 'red', at('container', 'top-left', 0, 9)),
      text('title', '{titleText}', DISPLAY, 17, 800, 'red',
        at('container', 'top-left', 9, 7.8)),
      text('tongue', '{attr.tongue}', SANS, 10, 400, 'muted',
        at('container', 'top-right', 0, 10), { align: 'right' }),
    ] } } };
// #endregion

// #region cover: the rug over the title, and the contents under it
const none = { numbered: false, toc: false, header: { elements: [] }, footer: { elements: [] } };
const RUG = 2 * (TRIM_W / 4); // mm: two rows of four tiles
const cover = { id: 'cover', ...none, marginBottom: pt(0), advancedDesign: { enabled: true,
  minHeight: mm(RUG - TOP + 41), slot: { elements: [
    image('rug', 'rug', { ...at('page', 'top-left'), size: { width: mm(TRIM_W) } }),
    text('title', '{titleText}', DISPLAY, 42, 800, 'red',
      at('page', 'top-left', INNER, RUG + 9)),
    text('subtitle', '{subtitle}', SANS, 13, 400, 'ink', at('#title', 'below', 0, 0.5)),
  ] } } };
const toc = {
  levels: [{ level: 1, fontFamily: DISPLAY, fontSize: pt(11), color: col('ink'),
    numberFontWeight: 700, numberColor: col('red'), numberWidth: mm(8), numberGap: mm(2),
    marginBottom: pt(2.5) }],
  pageNumber: { fontFamily: SANS, fontSize: pt(10), fontWeight: 700, color: col('red'),
    width: mm(5) },
  leader: { char: '. ', gap: mm(2) },
  subtitle: { enabled: true, attr: 'author', italic: false, fontFamily: SANS, fontSize: pt(9),
    color: col('muted') },
};
// #endregion

// #region art: ram's horns, the қошқар мүйіз of the felt rugs, from half circles
// A pair of horns is two half circles a side, radius 10 and then 6, on a stem; four pairs round
// a diamond make the tile, and a row of pairs, one up and one down, the border. The width of
// the stroke leaves as much ground as wool, so either colour can be read as the figure.
const horn = (side, sweep) => `M50 20 A10 10 0 0 ${sweep} ${50 + side * 20} 20 `
  + `A6 6 0 0 ${sweep} ${50 + side * 8} 20`;
const pair = `M50 40 V20 ${horn(-1, 0)} ${horn(1, 1)}`;
const horns = (colour, turn, w = 5.6) => `<path d="${pair}" transform="${turn}" fill="none" `
  + `stroke="${colour}" stroke-width="${w}" stroke-linecap="round" stroke-linejoin="round"/>`;
const shape = (d, colour, turn = '') => `<path d="${d}" fill="${colour}" transform="${turn}"/>`;
const tile = (x, y, ground, wool, spark) => `<g transform="translate(${x} ${y})">`
  + shape('M0 0H100V100H0Z', ground)
  + [0, 90, 180, 270].map((a) => horns(wool, `rotate(${a} 50 50)`)
    + shape('M0 0H17L0 17Z', spark, `rotate(${a} 50 50)`)).join('')
  + shape('M50 35L65 50L50 65L35 50Z', wool) + shape('M50 43L57 50L50 57L43 50Z', spark)
  + '</g>';
const UNIT = 50; // a pair of horns and its gap, in the border's units
const border = (n, colour, y) => Array.from({ length: n }, (_, i) => horns(colour, i % 2
  ? `translate(${i * UNIT - 25} ${y + 43}) scale(1 -1)`
  : `translate(${i * UNIT - 25} ${y - 3})`)).join('');
const teeth = (n, step, y, h, colour) => shape(Array.from({ length: n }, (_, i) =>
  `M${i * step} ${y}h${step}l${-step / 2} ${h}Z`).join(''), colour);
const svg = (w, h, body) => ({ width: w, height: h, markup: `<svg xmlns="http://www.w3.org/2000/`
  + `svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${body}</svg>` });
const { cream, gold } = palette;
const panel = (tone) => svg(600, 231.7, // the trim's width, 12 pairs of horns
  shape('M0 0H600V231.7H0Z', palette[tone]) + border(12, cream, 174)
  + shape('M0 160H600V163H0Z', cream) + teeth(48, 12.5, 222.7, 9, gold));
const rug = ['red', 'blue', 'green', 'ochre', 'blue', 'ochre', 'red', 'green'];
const ART = {
  rug: svg(400, 200, rug.map((tone, i) => tile((i % 4) * 100, Math.floor(i / 4) * 100,
    palette[tone], cream, gold)).join('')),
  strip: svg(1000, 60, shape('M0 0H1000V60H0Z', palette.red) + border(20, cream, 10)),
  ...Object.fromEntries(['red', 'blue', 'green', 'ochre']
    .map((tone) => [`panel-${tone}`, panel(tone)])),
};
// #endregion

const folio = (id, content, parity, edge, x, extra) => text(id, content, SANS, 9.5, 400, 'muted',
  at('page', edge, x, -11), { parity, ...extra });
const right = { align: 'right' };
const bold = { fontWeight: 700, color: col('red') };
const footer = { elements: [ // the title on the verso, the poet on the recto
  folio('even-folio', '{pageNumber}', 'even', 'bottom-left', OUTER, bold),
  folio('even-title', '{title}', 'even', 'bottom-left', OUTER + 9),
  folio('odd-author', '{attr.author}', 'odd', 'bottom-right', -OUTER - 9, right),
  folio('odd-folio', '{pageNumber}', 'odd', 'bottom-right', -OUTER, { ...right, ...bold }),
] };
const config = () => ({
  locale: LOCALE, // written out, never LANG: the book is Kazakh in every edition
  colorPalette, bodyText, footnotes, toc, footer, header: { elements: [] },
  page: { sizePreset: '60x90/16', dpi: 150, backgroundColor: col('cream'), margins: {
    top: mm(TOP), bottom: mm(22), left: mm(INNER), right: mm(OUTER), mirror: true } },
  layout: { layoutType: 'single' },
  headings: { fontFamily: DISPLAY, fontWeight: 800, color: col('red'), levels: [
    { level: 1, numberingTemplate: '{1:I}', advancedDesign: opener, marginBottom: pt(0),
      breakBefore: { enabled: true, parity: 'any' } }] },
  headingStyles: [cover, runOn],
  paragraphStyles: [{ id: 'colophon', fontFamily: SANS, fontSize: pt(8.2), lineHeight: pt(11),
    color: col('muted'), textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD),
    hyphenation: { locale: LANG, enabled: false } }],
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The anthology (content.text.<lang>.md), then its colophon in the edition's language.
const markdown = [String.raw`---
title: "Дала үні"
subtitle: "Алты тілдегі шағын антология"
---

# Дала үні {style="cover"}

:::toc

# Бірінші сөз {tone="red" author="Абай Құнанбайұлы" when="1845–1904" tongue="қазақша"}

Бұл жасқа келгенше жақсы өткіздік пе, жаман өткіздік пе, әйтеуір бірталай өмірімізді өткіздік: алыстық, жұлыстық, айтыстық, тартыстық — әурешілікті көре-көре келдік. Енді жер ортасы жасқа келдік: қажыдық, жалықтық; қылып жүрген ісіміздің баянсызын, байлаусызын көрдік, бәрі қоршылық[^1] екенін білдік. Ал, енді қалған өмірімізді қайтіп, не қылып өткіземіз? Соны таба алмай өзім де қайранмын.

Ел бағу? Жоқ, елге бағым жоқ. Бағусыз дертке ұшырайын деген кісі бақпаса, не албыртқан, көңілі басылмаған жастар бағамын демесе, бізді құдай сақтасын!

Мал бағу? Жоқ, баға алмаймын. Балалар өздеріне керегінше өздері бағар. Енді қартайғанда қызығын өзің түгел көре алмайтұғын, ұры, залым, тілемсектердің азығын бағып беремін деп, қалған аз ғана өмірімді қор қылар жайым жоқ.

Ғылым бағу? Жоқ, ғылым бағарға да ғылым сөзін сөйлесер адам жоқ. Білгеніңді кімге үйретерсің, білмегеніңді кімнен сұрарсың? Елсіз-күнсізде кездемені жайып салып, қолына кезін[^2] алып отырғанның не пайдасы бар? Мұңдасып шер тарқатысар кісі болмаған соң, ғылым өзі — бір тез қартайтатұғын күйік.

Софылық[^3] қылып, дін бағу? Жоқ, ол да болмайды, оған да тыныштық керек. Не көңілде, не көрген күніңде бір тыныштық жоқ, осы елге, осы жерде не қылған софылық?

Балаларды бағу? Жоқ, баға алмаймын. Бағар едім, қалайша бағудың мәнісін де білмеймін, не болсын деп бағам, қай елге қосайын, қай харекетке[^4] қосайын? Балаларымның өзіне ілгері өмірінің, білімінің пайдасын тыныштықпенен көрерлік орын тапқаным жоқ, қайда бар, не қыл дерімді біле алмай отырмын, не бол деп бағам? Оны да ермек қыла алмадым.

Ақыры ойладым: осы ойыма келген нәрселерді қағазға жаза берейін, ақ қағаз бен қара сияны ермек қылайын, кімде-кім ішінен керекті сөз тапса, жазып алсын, я оқысын, керегі жоқ десе, өз сөзім өзімдікі дедім де, ақыры осыған байладым, енді мұнан басқа ешбір жұмысым жоқ.

# Сегіз аяқ {style="run-on" author="Абай Құнанбайұлы" tongue="қазақша, үзінді"}

:::verse
Алыстан сермеп,
Жүректен тербеп,
  Шымырлап бойға жайылған.
Қиуадан шауып,
Қисынын тауып,
  Тағыны[^5] жетіп қайырған —
Толғауы тоқсан қызыл тіл,
Сөйлеймін десең өзің біл.
:::

# Үлгү ырлар {tone="blue" author="Тоқтоғұл Сатылғанов" when="1864–1933" tongue="қырғызша, үзінді"}

:::verse{lang=ky}
Дайранын көркү кемеде,
Баланын көркү энеде,
Акыл айтсаң тыңшабай,
Акмактын көркү жемеде[^6].

Бычактын көркү кынында,
Жылкынын сыны кулунда,
Азамат болсоң, эр жигит,
Ардактуу иштен корунба.

Шибердин[^7] көркү — мал менен,
Жылкынын көркү — жал менен.
Жылдыздай жанган кара көз,
Жигиттин көркү — жар менен.

Булбулдун көркү гүлдө бар,
Ырчынын көркү үндө бар,
Ак шумкар учса асманга,
Амалың болсо үндөп ал!
:::

# Туган тел {tone="green" author="Ғабдолла Тоқай" when="1886–1913" tongue="татарша"}

:::verse{lang=tt}
И туган тел, и матур тел, әткәм-әнкәмнең теле!
Дөньяда күп нәрсә белдем син туган тел аркылы.

Иң элек бу тел белән әнкәм бишектә[^8] көйләгән,
Аннары төннәр буе әбкәм[^9] хикәят сөйләгән.

И туган тел! Һәрвакытта ярдәмең берлән синең,
Кечкенәдән аңлашылган шатлыгым, кайгым минем.

И туган тел! Синдә булган иң элек кылган догам:
Ярлыкагыл[^10], дип, үзем һәм әткәм-әнкәмне, ходам!
:::

# Башҡорттарым, уҡыу кәрәк! {tone="ochre" author="Мифтахетдин Ақмолла" when="1831–1895" tongue="башқұртша, үзінді"}

:::verse{lang=ba}
Башҡорттарым, уҡыу кәрәк, уҡыу кәрәк!
Арабыҙҙа наҙандар күп, уҡыу һирәк.
Аңғыра айыуҙан Уралдағы ҡурҡҡандай,
Эй, туғандар, наҙанлыҡтан ҡурҡыу кәрәк!

Илтифат ит[^11]: уҡыуҙалыр шәрафәттәр,
Яһиллыҡтан[^12] килә ятыр ҙур афәттәр.
Уҡығандар күктә осор, һыуҙа йөҙөр,
Юҡтыр унда әүлиәлек, кәрамәттәр.

Уҡығанға был донъяла жәләл булыр,
Харам тигән күп шәйҙәр хәләл булыр.
Ырыҫ, дәүләт шишмәһен асам тиһәң,
Ғилем-һөнәр берҙән-бер әмәл булыр.

Алтыға берҙе ҡушып, һан ун булмай,
Сәғәтте алға бороп, төн көн булмай.
Белемлелек — арыҫландан көслө батыр,
Шуға атланмай, һинең төшөң һис өн булмай.
:::

# Миний нутаг {tone="blue" author="Дашдоржийн Нацагдорж" when="1906–1937" tongue="моңғолша, үзінді"}

:::verse{lang=mn}
Хэнтий, Хангай, Соёны өндөр сайхан нуруунууд
Хойд зүгийн чимэг болсон ой хөвч уулнууд
Мэнэн, Шарга, Номины өргөн их говиуд[^13]
Өмнө зүгийн манлай болсон элсэн манхан далайнууд
  Энэ бол миний төрсөн нутаг
  Монголын сайхан орон

Хэрлэн, Онон, Туулын тунгалаг ариун мөрнүүд
Хотол олны эм болсон горхи, булаг рашаанууд[^14]
Хөвсгөл, Увс, Буйрын гүн цэнхэр нуурууд
Хүн малын ундаа болсон тойром бүрд уснууд
  Энэ бол миний төрсөн нутаг
  Монголын сайхан орон

Орхон, Сэлэнгэ, Хөхийн онц сайхан голууд
Уурхай баялгийн охь болсон олон уул даваанууд
Хуучин хөшөө дурсгал, хот балгадын сууринууд
Хол газраа одсон харгуй дардан замууд
  Энэ бол миний төрсөн нутаг
  Монголын сайхан орон
:::

# Бӯи ҷӯи Мӯлиён {tone="red" author="Әбу Абдаллаһ Рудаки" when="858–941" tongue="тәжікше"}

:::verse{lang=tg}
Бӯи ҷӯи Мӯлиён[^15] ояд ҳаме,
Ёди ёри меҳрубон ояд ҳаме.

Реги Омуву дурушти роҳи ӯ,
Зери поям парниён[^16] ояд ҳаме.

Оби Ҷайҳун[^17] бо ҳама паҳноварӣ
Хинги[^18] моро то миён ояд ҳаме.

Эй Бухоро, шод бошу дер зӣ,
Мир наздат шодмон ояд ҳаме.

Мир моҳ асту Бухоро осмон,
Моҳ сӯи осмон ояд ҳаме.

Мир сарв асту Бухоро бӯстон,
Сарв сӯи бӯстон ояд ҳаме.
:::

[^1]: Қоршылық: қорлық.

[^2]: Кез: ескі ұзындық өлшемі.

[^3]: Софылық: сопылық.

[^4]: Харекет: әрекет, кәсіп.

[^5]: Тағы: жабайы аң.

[^6]: Жеме: сөгіс, кінә.

[^7]: Шибер: шүйгін шалғын.

[^8]: Бишек: бесік.

[^9]: Әбкәм: әжем.

[^10]: Ярлыкагыл: жарылқа.

[^11]: Илтифат ит: назар аудар.

[^12]: Яһиллыҡ: надандық.

[^13]: Говь: шөл дала.

[^14]: Рашаан: шипалы бұлақ.

[^15]: Мӯлиён: Бұхара маңындағы арық пен бақтар.

[^16]: Парниён: жібек мата.

[^17]: Ҷайҳун, Ому: Әмудария.

[^18]: Хинг: боз ат.
`, String.raw`:::paragraphs{style="colophon"}
Набрано шрифтами Alegreya, Alegreya Sans и Piazzolla (SIL OFL) · Тексты: общественное достояние, с wikisource.org и из указанных изданий
:::
`].join('\n\n');
const resources = Object.entries(ART).map(([id, { width, height }]) => ({ id, typeId: 'figure',
  kind: 'svg', createdAt: 0, updatedAt: 0, svg: { fileId: `${id}.svg`, width, height } }));

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { // every face the pages use, with the cyrillic-ext files its letters need
  Alegreya: ['400'],
  'Alegreya Sans': ['400', '700'],
  Piazzolla: ['700', '800'],
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
for (const [id, { markup }] of Object.entries(ART)) await loadSvg(`${id}.svg`, markup);
const doc = await buildDocumentWithFonts({ markdown, resources }, config(),
  kitCyrillicFonts(FONTS));
showPages(doc, { title: 'Дала үні' });
offerPdf(() => renderToPdf(doc, { fontProvider: cyrillicPdfProvider, resourceBytes: imageBytes }),
  `${RECIPE}.pdf`);

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

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

// ─── Kit · fonts 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 · cyrillic v1 ── Cyrillic faces · postext.dev/cookbook
// Fontsource ships a family's Cyrillic letters in files of their own:
// `cyrillic` holds the Russian, Ukrainian, Belarusian, Bulgarian, Serbian and
// Macedonian alphabets, the stress mark and №; `cyrillic-ext` the letters of
// Kazakh, Kyrgyz, Tatar, Bashkir, Tajik and Mongolian. The fonts block loads
// latin, latin-ext and greek; this one adds these.

/** The unicode-ranges Fontsource's stylesheets declare the two files with (a
 *  function: the kit runs after the pen's code). */
function cyrillicRanges() {
  return {
    cyrillic: 'U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116',
    'cyrillic-ext': 'U+0460-052F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F',
  };
}

/** The Cyrillic files `text` needs that `meta`'s family ships. */
function cyrillicSubsetsFor(text, meta) {
  return [[/[́Ѐ-џҐґҰұ№]/u, 'cyrillic'],
    [/[Ѡ-ҏҒ-үҲ-ԯᲀ-ᲊ₴ⷠ-ⷿꙀ-ꚟ]/u, 'cyrillic-ext']]
    .filter(([re, x]) => re.test(text) && meta?.subsets?.includes(x)).map(([, x]) => x);
}

/** kitFonts(FONTS) for a pen in Cyrillic: the fonts block's files, then the
 *  Cyrillic ones `text` needs. A family without them fails, so that no page
 *  is set in a fallback face unseen; list in `latin` the families that set
 *  Latin text alone. */
function kitCyrillicFonts(FONTS = {}, latin = []) {
  return { ...kitFonts(FONTS), resolve: async (family, weight, style, request = {}) => {
    const files = await fontsourceResolver(family, weight, style, request);
    const meta = await fontsourceMeta(family);
    if (!files || latin.includes(family)) return files;
    if (/\p{Script=Cyrillic}/u.test(request.text ?? '') && !meta?.subsets?.includes('cyrillic')) {
      throw new Error(`${family} has no Cyrillic letters at Fontsource`);
    }
    const at = await fontsourceAt(fontsourceId(family));
    return [...files, ...cyrillicSubsetsFor(request.text ?? '', meta).map((subset) => ({
      source: `${at}files/${fontsourceId(family)}-${subset}-${weight}-${style}.woff2`,
      unicodeRange: cyrillicRanges()[subset],
    }))];
  } };
}

/** fontsourceProvider (the pdf block) with the Cyrillic files a face's
 *  letters need, after its others, as the screen added them. */
async function cyrillicPdfProvider(family, weight, style, request) {
  const first = await fontsourceProvider(family, weight, style, request);
  const files = Array.isArray(first) ? first : [first];
  const meta = await fontsourceMeta(family);
  const text = String.fromCodePoint(...(request?.codePoints ?? []));
  const subsets = cyrillicSubsetsFor(text, meta);
  if (!subsets.length) return first;
  const s = style === 'italic' && !meta.styles.includes('italic') ? 'normal' : style;
  const w = (await fontsourceWeights(family, s)).reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const at = await fontsourceAt(fontsourceId(family));
  const more = await Promise.all(subsets.map(async (subset, i) => {
    const url = `${at}files/${fontsourceId(family)}-${subset}-${w}-${s}.woff2`;
    const res = await fetch(url);
    if (!res.ok) throw new Error(`Fontsource file ${url} (${res.status})`);
    return Object.assign(await decompressWoff2(new Uint8Array(await res.arrayBuffer())),
      { unicodeRange: cyrillicRanges()[subset], order: files.length + i });
  }));
  return [...files, ...more];
}

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

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

- Проверьте шрифт по буквам, прежде чем брать его. В Alegreya и Piazzolla есть ә ғ қ ң ө ұ ү һ ҙ ҫ ҡ ҳ ҷ ӣ ӯ; в Literata, Spectral и Old Standard некоторых нет. Буквы лежат в файлах `cyrillic-ext`, которые загружает `kitCyrillicFonts`.
- Заголовок без `tone` не называет рисунка, и плашка остаётся пустой. Дайте каждому стихотворению один из четырёх цветов.

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

- Рецепт: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Текст: «Бірінші сөз» (1890): Abai Qunanbaiuly ([источник](https://abai.kz/post/12154)), общественное достояние
- Текст: «Сегіз аяқ», first stanza: Abai Qunanbaiuly ([источник](https://wikisource.org/wiki/Сегіз_аяқ)), общественное достояние
- Текст: «Үлгү ырлар», four stanzas of seven: Toktogul Satylganov ([источник](https://wikisource.org/wiki/Үлгү_ырлар)), общественное достояние
- Текст: «Туган тел» (1909): Ğabdulla Tukay ([источник](https://wikisource.org/wiki/Туган_тел_(Тукай))), общественное достояние
- Текст: «Башҡорттарым, уҡыу кәрәк!», four stanzas: Miftahetdin Akmulla ([источник](https://wikisource.org)), общественное достояние
- Текст: «Миний нутаг», first three stanzas, spelling after several modern editions: Dashdorjiin Natsagdorj ([источник](https://mn.wikipedia.org/wiki/Миний_Нутаг)), общественное достояние
- Текст: «Бӯи ҷӯи Мӯлиён» in Tajik Cyrillic: Rudaki ([источник](https://tg.wikipedia.org/wiki/Рӯдакӣ)), общественное достояние
- Текст: The title, the glosses and the colophon: Postext Cookbook, оригинал
- Шрифты: Alegreya (OFL-1.1), Alegreya Sans (OFL-1.1), Piazzolla (OFL-1.1)
- Код: MIT · Образец содержания: MIT

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

- [№ 209 · Двенадцать кириллических языков в образце шрифта](https://postext.dev/ru/cookbook/cyrillic-specimen-twelve-languages.md): Четырёхстраничный образец: одна статья на двенадцати кириллических языках, каждый со своими переносами и местными формами букв. · Уровень 2 (Средний) · Каталоги
- [№ 030 · Антология с именами авторов](https://postext.dev/ru/cookbook/anthology-with-bylines.md): Три эссе о прогулках с автором, годом и журналом в заголовке: начальная полоса печатает всё, левый колонтитул и содержание — автора. · Уровень 2 (Средний) · Художественная литература, драматургия и эссеистика
- [№ 015 · Стихи, набранные строка за строкой](https://postext.dev/ru/cookbook/poetry-collection.md): Каждое стихотворение — блок :::verse: отступы 1918 года заданы пробелами, перенесённая часть строки стоит на 2 em правее, строфы разделены пустой строкой. · Уровень 2 (Средний) · Поэзия
