# Abaï et cinq poètes de la steppe, anthologie kazakhe

> Une anthologie de huit pages en six langues cyrilliques : un livre kazakh, un poème par langue, des gloses en pied et l’ornement des feutres.

- Version HTML: https://postext.dev/fr/cookbook/abai-kazakh-anthology
- Recette Nº 210 · Publications complètes · Niveau 2 (Intermédiaire) · Sorties: Canvas, PDF
- Genres: Poésie
- Nécessite postext ≥ 1.100.0, postext-pdf ≥ 1.100.0 · testée avec 1.100.0, postext-pdf 1.100.0 le 2026-12-02
- Pages: [1](https://postext.dev/cookbook/abai-kazakh-anthology/en/p01.webp?v=ae6c047c), [2](https://postext.dev/cookbook/abai-kazakh-anthology/en/p02.webp?v=ae6c047c), [3](https://postext.dev/cookbook/abai-kazakh-anthology/en/p03.webp?v=ae6c047c), [4](https://postext.dev/cookbook/abai-kazakh-anthology/en/p04.webp?v=ae6c047c), [5](https://postext.dev/cookbook/abai-kazakh-anthology/en/p05.webp?v=ae6c047c), [6](https://postext.dev/cookbook/abai-kazakh-anthology/en/p06.webp?v=ae6c047c), [7](https://postext.dev/cookbook/abai-kazakh-anthology/en/p07.webp?v=ae6c047c), [8](https://postext.dev/cookbook/abai-kazakh-anthology/en/p08.webp?v=ae6c047c)
- Ouvrir dans le Sandbox: https://postext.dev/fr/sandbox#recipe=abai-kazakh-anthology&lang=en (.postext: https://postext.dev/cookbook/abai-kazakh-anthology/en/abai-kazakh-anthology.postext)
- Dernière mise à jour: 2026-12-02
- Autres langues: [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), [it](https://postext.dev/it/cookbook/abai-kazakh-anthology.md), [pt](https://postext.dev/pt/cookbook/abai-kazakh-anthology.md), [ru](https://postext.dev/ru/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)

## En bref

Une petite anthologie qui s’ouvre sur Abaï et continue avec des poèmes en kirghize, tatar, bachkir, mongol et tadjik. Les mots difficiles sont expliqués en kazakh au pied de la page, et l’ornement vient des tapis de feutre de la steppe.

## Ce que vous allez composer

Дала үні (*La voix de la steppe*), un cahier de 145 × 215 mm en huit pages. La couverture est un tapis de feutre aux carreaux de cornes de bélier, au-dessus du titre et du sommaire. Le *Premier mot* d’Abaï et la première strophe de ses *Huitains* remplissent une double page ; un poème en kirghize, tatar, bachkir, mongol et tadjik prend une page chacun, sous un panneau à la couleur du poète avec le chiffre romain, le titre, le nom, les dates et la langue. Les mots archaïques ou étrangers sont glosés en kazakh en pied. Le texte est en Alegreya, les titres en Piazzolla. Seul le colophon suit la langue de l’édition.

**Cette recette répond à:**

- Comment composer une anthologie en kazakh, kirghize, tatar, bachkir, mongol et tadjik ?

## La réponse courte

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

## Ingrédients

**Enseigne**

- [Les langues en cyrillique comme langue du document](https://postext.dev/fr/docs/cyrillic-layout.md#commencer-un-livre-en-cyrillique): locale 'ru', 'uk', 'be', 'bg', 'sr', 'mk', 'kk', 'ky', 'tt', 'ba', 'tg' ou 'mn' donne au livre la césure, les légendes, les titres de tableau, les notes, les nombres en lettres, les formats de feuille et le sens du dos de sa langue.
- [Vers ligne à ligne](https://postext.dev/fr/docs/document-format-directives.md#verse): :::verse compose un poème tel qu’il est écrit : un vers par ligne de Markdown, des lignes vides entre les strophes, les espaces de début comme retraits ; un vers trop long passe à la ligne avec un retrait suspendu ou au fer à droite derrière un crochet, jamais séparé de son vers à un saut de page, et les strophes courtes peuvent rester entières.
- [Notes de bas de page](https://postext.dev/fr/docs/document-format-notes-references.md#notes-de-bas-de-page): Des notes appelées avec [^id] et composées au pied de la colonne qui les cite, ou après le chapitre, numérotées par chapitre ou sur tout le livre.

**Utilise aussi**

- [Mots maintenus ensemble en fin de ligne](https://postext.dev/fr/docs/cyrillic-layout.md#mots-gardés-ensemble)
- [Césure et langue du document](https://postext.dev/fr/docs/justification.md#langues-prises-en-charge)
- [Table des matières](https://postext.dev/fr/docs/configuration-notes-references.md#table-des-matières)
- [Titres numérotés](https://postext.dev/fr/docs/configuration-headings.md#réglages-par-niveau)
- [Ouvertures composées](https://postext.dev/fr/docs/configuration-headings.md#étendue-et-maquette-avancée)
- [Styles de titre](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)
- [Attributs de titre](https://postext.dev/fr/docs/document-format.md#attributs-de-titre)
- [Images dans les maquettes de page](https://postext.dev/fr/docs/configuration-headers-footers.md#éléments-image)
- [Texte, filets et boîtes dans les maquettes de page](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page)
- [Titres courants et folios](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page)
- [Couvertures, pages de titre et colophons](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)
- [Métadonnées du document](https://postext.dev/fr/docs/document-format.md#en-tête-yaml)
- [Chapitres non numérotés](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)
- [Marges en miroir](https://postext.dev/fr/docs/configuration-page-layout.md#marges-en-miroir)
- [Retraits, alignement et espacement des paragraphes](https://postext.dev/fr/docs/configuration-text.md#texte-courant)
- [Palette de couleurs sémantique](https://postext.dev/fr/docs/configuration-fonts-colors-viewers.md#palette-de-couleurs)
- [Export PDF](https://postext.dev/fr/docs/configuration-pdf-output.md#générer-des-pdf)
- [Couleur du papier](https://postext.dev/fr/docs/configuration-page-layout.md#page)
- [Styles de paragraphe](https://postext.dev/fr/docs/configuration-styles.md#styles-de-paragraphe)
- [Polices intégrées au PDF](https://postext.dev/fr/docs/configuration-pdf-output.md#pourquoi-un-fournisseur-de-polices)
- [Figures et tableaux comme ressources](https://postext.dev/fr/docs/document-format-resources.md#ressources)
- [Titres courants par section](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)

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

- [`bodyText`](https://postext.dev/fr/docs/configuration-text.md#texte-courant), [`colorPalette`](https://postext.dev/fr/docs/configuration-fonts-colors-viewers.md#palette-de-couleurs), [`footer`](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page), [`footnotes`](https://postext.dev/fr/docs/configuration-notes-references.md#notes-de-bas-de-page), [`header`](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page), [`headingStyles`](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre), [`headings`](https://postext.dev/fr/docs/configuration-headings.md#titres), [`layout`](https://postext.dev/fr/docs/configuration-page-layout.md#mise-en-page), [`locale`](https://postext.dev/fr/docs/configuration-language.md#césure), [`page`](https://postext.dev/fr/docs/configuration-page-layout.md#page), [`paragraphStyles`](https://postext.dev/fr/docs/configuration-styles.md#styles-de-paragraphe), [`toc`](https://postext.dev/fr/docs/configuration-notes-references.md#table-des-matières)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/fr/docs/configuration-programmatic-usage.md#charger-les-polices-avant-la-mise-en-page), [`decompressWoff2`](https://postext.dev/fr/docs/configuration-pdf-output.md#fournisseur-de-polices-dans-le-navigateur-fontsource--woff2), [`registerResourceImage`](https://postext.dev/fr/docs/architecture.md#surface-de-lapi), [`renderPageToCanvas`](https://postext.dev/fr/docs/configuration-programmatic-usage.md#rendre-une-page-en-bitmap), [`renderToPdf`](https://postext.dev/fr/docs/configuration-pdf-output.md#générer-des-pdf)

**Caractères**

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

## Préparation

### 1 · Un livre kazakh, des poèmes en cinq autres langues

Le code est dans [la réponse courte](https://postext.dev/fr/cookbook/abai-kazakh-anthology.md#la-réponse-courte) ci-dessus. `locale: 'kk'` donne au livre sa [césure](https://postext.dev/fr/docs/cyrillic-layout.md#césure-en-douze-langues), ses [mots gardés ensemble](https://postext.dev/fr/docs/cyrillic-layout.md#mots-gardés-ensemble) et ses [notes](https://postext.dev/fr/docs/cyrillic-layout.md#notes-comptées-par-page), comptées de nouveau à chaque page et renfoncées de 1,5 em. Chacun des autres poèmes est un `:::verse{lang=ky}`, composé et balisé dans sa langue dans le PDF et le HTML. `align: 'center'` centre chaque poème sur son vers le plus long, `keepStanzas: 8` garde une strophe sur une page, et deux espaces en tête de vers le renfoncent.

### 2 · Un panneau de feutre à la couleur du poète

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

Le titre porte ce que le panneau imprime : `# Үлгү ырлар {tone="blue" author="Тоқтоғұл Сатылғанов" when="1864–1933" tongue="қырғызша"}`. `panel-{attr.tone}` nomme le dessin, si bien qu’une composition sert quatre couleurs, et le même `author` arrive au sommaire et au pied de page. `numberingTemplate: '{1:I}'` écrit le chiffre romain. Une seconde pièce du même poète prend le style `run-on`, sans saut de page et avec une bordure étroite.

### 3 · Le sommaire sur la couverture

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

Le titre de couverture réserve le tapis et le titre par `minHeight`, et `:::toc` suit dans le flux. `toc.subtitle` imprime l’`author` de chaque titre au-dessous. La couverture n’est ni numérotée ni listée.

### 4 · Des cornes de bélier en demi-cercles

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

Une corne est faite de deux demi-cercles, de rayon 10 puis 6, sur une tige commune. Quatre paires tournées autour d’un losange font le carreau ; une rangée de paires, l’une en haut, l’autre en bas, la bordure. Le trait et le vide ont presque la même largeur, comme dans un *shyrdak*, où chaque feutre est taillé pour entrer dans l’autre.

## La recette complète

Un seul fichier, composé à partir du dossier de la recette avec le texte d’exemple et le kit commun des Recettes déjà inclus ; il construit sa propre page. Pour l’exécuter, placez-le dans un `<script type="module">` d’une page vide ou collez-le dans le panneau JS d’un nouveau pen CodePen (en tant que module). Il importe postext depuis esm.sh : il n’y a rien à installer ni à compiler.

- Dossier de la recette: https://github.com/drnachio/postext/tree/main/cookbook/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 = 'en'; // @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"}
Set in Alegreya, Alegreya Sans and Piazzolla (SIL OFL) · Texts: public domain, from wikisource.org and the editions credited
:::
`].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 ───────────────────────────────────────────────────────────────────────
```

## Erreurs fréquentes

- Vérifiez le caractère lettre à lettre avant de le choisir. Alegreya et Piazzolla ont ә ғ қ ң ө ұ ү һ ҙ ҫ ҡ ҳ ҷ ӣ ӯ ; il en manque à Literata, Spectral et Old Standard. Elles viennent des fichiers `cyrillic-ext` que charge `kitCyrillicFonts`.
- Un titre sans `tone` ne nomme aucun dessin, et son panneau reste vide. Donnez à chaque poème l’un des quatre.

## Crédits

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

## Recettes liées

- [Nº 209 · Douze langues cyrilliques dans un spécimen](https://postext.dev/fr/cookbook/cyrillic-specimen-twelve-languages.md): Un spécimen de quatre pages : un article en douze langues cyrilliques, chacune coupée selon ses règles et dessinée avec ses formes locales. · Niveau 2 (Intermédiaire) · Catalogues
- [Nº 030 · Anthologie avec signatures d’auteur](https://postext.dev/fr/cookbook/anthology-with-bylines.md): Trois essais sur la marche dont les titres donnent auteur, année et revue : l’ouverture imprime les trois ; les titres courants du verso et la table, l’auteur. · Niveau 2 (Intermédiaire) · Fiction, théâtre et prose littéraire
- [Nº 015 · Des poèmes composés vers à vers](https://postext.dev/fr/cookbook/poetry-collection.md): Chaque poème est un bloc :::verse écrit tel qu’imprimé : retraits de 1918 en espaces de tête, renvois pendant 2 em plus loin, ligne blanche entre strophes. · Niveau 2 (Intermédiaire) · Poésie
