# Abaj e cinque poeti della steppa, antologia kazaka

> Un’antologia di otto pagine in sei lingue cirilliche: un libro kazako, una poesia per lingua, glosse a piè di pagina e ornamento di feltro.

- Versione HTML: https://postext.dev/it/cookbook/abai-kazakh-anthology
- Ricetta Nº 210 · Pubblicazioni complete · Livello 2 (Intermedio) · Output: Canvas, PDF
- Generi: Poesia
- Richiede postext ≥ 1.100.0, postext-pdf ≥ 1.100.0 · provata con 1.100.0, postext-pdf 1.100.0 il 2026-12-02
- Pagine: [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)
- Apri nella Sandbox: https://postext.dev/it/sandbox#recipe=abai-kazakh-anthology&lang=en (.postext: https://postext.dev/cookbook/abai-kazakh-anthology/en/abai-kazakh-anthology.postext)
- Ultimo aggiornamento: 2026-12-02
- Altre lingue: [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), [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)

## In breve

Una piccola antologia che si apre con Abaj e prosegue con poesie in kirghiso, tataro, baschiro, mongolo e tagico. Le parole difficili sono spiegate in kazako a piè di pagina, e l’ornamento viene dai tappeti di feltro della steppa.

## Che cosa comporrai

Дала үні (*La voce della steppa*), un fascicolo di 145 × 215 mm in otto pagine. La copertina è un tappeto di feltro a piastrelle di corna d’ariete sopra il titolo e l’indice. La *Prima parola* di Abaj e la prima strofa delle sue *Ottave* riempiono una doppia pagina; una poesia in kirghiso, tataro, baschiro, mongolo e tagico occupa una pagina ciascuna, sotto un pannello nel colore del poeta con il numero romano, il titolo, il nome, le date e la lingua. Le parole arcaiche o straniere sono glossate in kazako al piede. Il testo è in Alegreya, i titoli in Piazzolla. Solo il colophon segue la lingua dell’edizione.

**Questa ricetta risponde a:**

- Come compongo un’antologia in kazako, kirghiso, tataro, baschiro, mongolo e tagico?

## La risposta breve

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

## Ingredienti

**Insegna**

- [Le lingue in cirillico come lingua del documento](https://postext.dev/it/docs/cyrillic-layout.md#iniziare-un-libro-in-cirillico): locale 'ru', 'uk', 'be', 'bg', 'sr', 'mk', 'kk', 'ky', 'tt', 'ba', 'tg' o 'mn' dà al libro la sillabazione, le didascalie, i titoli delle tabelle, le note, i numeri in lettere, i formati di foglio e il verso del dorso della sua lingua.
- [Versi riga per riga](https://postext.dev/it/docs/document-format-directives.md#verse): :::verse compone una poesia così come è scritta: un verso per riga di Markdown, righe vuote tra le strofe, spazi iniziali come rientri; un verso troppo lungo va a capo con un rientro sospeso o allineato a destra dietro una parentesi quadra, senza mai essere separato dal suo verso a un’interruzione di pagina, e le strofe brevi si possono tenere intere.
- [Note a piè di pagina](https://postext.dev/it/docs/document-format-notes-references.md#note-a-piè-di-pagina): Note citate con [^id] e composte al piede della colonna che le cita, o dopo il capitolo, numerate per capitolo o per tutto il libro.

**Usa anche**

- [Parole tenute insieme a fine riga](https://postext.dev/it/docs/cyrillic-layout.md#parole-tenute-insieme)
- [Sillabazione e lingua del documento](https://postext.dev/it/docs/justification.md#lingue-supportate)
- [Indice](https://postext.dev/it/docs/configuration-notes-references.md#indice-dei-contenuti)
- [Titoli numerati](https://postext.dev/it/docs/configuration-headings.md#personalizzazioni-per-livello)
- [Aperture progettate](https://postext.dev/it/docs/configuration-headings.md#estensione-e-grafica-avanzata)
- [Stili di titolo](https://postext.dev/it/docs/configuration-styles.md#stili-dei-titoli)
- [Attributi dei titoli](https://postext.dev/it/docs/document-format.md#attributi-dei-titoli)
- [Immagini nei progetti di pagina](https://postext.dev/it/docs/configuration-headers-footers.md#elementi-immagine)
- [Testo, filetti e riquadri nei progetti di pagina](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina)
- [Testatine e folio](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina)
- [Copertine, frontespizi e colophon](https://postext.dev/it/docs/configuration-styles.md#stili-dei-titoli)
- [Metadati del documento](https://postext.dev/it/docs/document-format.md#front-matter)
- [Capitoli non numerati](https://postext.dev/it/docs/configuration-styles.md#stili-dei-titoli)
- [Margini speculari](https://postext.dev/it/docs/configuration-page-layout.md#margini-speculari)
- [Rientri, allineamento e spaziatura dei paragrafi](https://postext.dev/it/docs/configuration-text.md#testo-corrente)
- [Tavolozza di colori semantica](https://postext.dev/it/docs/configuration-fonts-colors-viewers.md#tavolozza-dei-colori)
- [Esportazione in PDF](https://postext.dev/it/docs/configuration-pdf-output.md#generare-pdf)
- [Colore della carta](https://postext.dev/it/docs/configuration-page-layout.md#pagina)
- [Stili di paragrafo](https://postext.dev/it/docs/configuration-styles.md#stili-di-paragrafo)
- [Font incorporati nel PDF](https://postext.dev/it/docs/configuration-pdf-output.md#perché-un-provider-di-font)
- [Figure e tabelle come risorse](https://postext.dev/it/docs/document-format-resources.md#risorse)
- [Testatine per sezione](https://postext.dev/it/docs/configuration-styles.md#stili-dei-titoli)

**La configurazione in breve**

- [`bodyText`](https://postext.dev/it/docs/configuration-text.md#testo-corrente), [`colorPalette`](https://postext.dev/it/docs/configuration-fonts-colors-viewers.md#tavolozza-dei-colori), [`footer`](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina), [`footnotes`](https://postext.dev/it/docs/configuration-notes-references.md#note-a-piè-di-pagina), [`header`](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina), [`headingStyles`](https://postext.dev/it/docs/configuration-styles.md#stili-dei-titoli), [`headings`](https://postext.dev/it/docs/configuration-headings.md#titoli), [`layout`](https://postext.dev/it/docs/configuration-page-layout.md#impaginazione), [`locale`](https://postext.dev/it/docs/configuration-language.md#sillabazione), [`page`](https://postext.dev/it/docs/configuration-page-layout.md#pagina), [`paragraphStyles`](https://postext.dev/it/docs/configuration-styles.md#stili-di-paragrafo), [`toc`](https://postext.dev/it/docs/configuration-notes-references.md#indice-dei-contenuti)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/it/docs/configuration-programmatic-usage.md#caricare-i-font-prima-dellimpaginazione), [`decompressWoff2`](https://postext.dev/it/docs/configuration-pdf-output.md#provider-di-font-per-il-browser-fontsource--woff2), [`registerResourceImage`](https://postext.dev/it/docs/architecture.md#superficie-dellapi), [`renderPageToCanvas`](https://postext.dev/it/docs/configuration-programmatic-usage.md#rasterizzare-una-pagina), [`renderToPdf`](https://postext.dev/it/docs/configuration-pdf-output.md#generare-pdf)

**Caratteri**

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

## Preparazione

### 1 · Un libro kazako con poesie in altre cinque lingue

Il codice è [la risposta breve](https://postext.dev/it/cookbook/abai-kazakh-anthology.md#la-risposta-breve) qui sopra. `locale: 'kk'` dà al libro la [sillabazione](https://postext.dev/it/docs/cyrillic-layout.md#sillabazione-in-dodici-lingue), le [parole tenute insieme](https://postext.dev/it/docs/cyrillic-layout.md#parole-tenute-insieme) e le [note](https://postext.dev/it/docs/cyrillic-layout.md#note-contate-per-pagina), contate di nuovo a ogni pagina e rientrate di 1,5 em. Ognuna delle altre poesie è un `:::verse{lang=ky}`, composto e marcato nella sua lingua nel PDF e nell’HTML. `align: 'center'` centra ogni poesia sul verso più lungo, `keepStanzas: 8` tiene la strofa in una pagina e due spazi all’inizio del verso lo fanno rientrare.

### 2 · Un pannello di feltro nel colore del poeta

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

Il titolo porta ciò che il pannello stampa: `# Үлгү ырлар {tone="blue" author="Тоқтоғұл Сатылғанов" when="1864–1933" tongue="қырғызша"}`. `panel-{attr.tone}` nomina il disegno, così un progetto serve per quattro colori, e lo stesso `author` arriva all’indice e al piede. `numberingTemplate: '{1:I}'` scrive il numero romano. Un secondo brano dello stesso poeta usa lo stile `run-on`, senza salto di pagina e con una bordura stretta.

### 3 · L’indice in copertina

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

Il titolo di copertina riserva il tappeto e il titolo con `minHeight`, e `:::toc` segue nel flusso. `toc.subtitle` stampa sotto ogni titolo il suo `author`. La copertina non è numerata né elencata.

### 4 · Corna d’ariete da semicerchi

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

Un corno è fatto di due semicerchi, di raggio 10 e poi 6, su uno stelo comune. Quattro coppie ruotate attorno a un rombo fanno la piastrella; una fila di coppie, una in su e una in giù, la bordura. Tratto e vuoto sono quasi della stessa larghezza, come in uno *shyrdak*, dove ogni feltro è tagliato per incastrarsi nell’altro.

## La ricetta completa

Un unico file, composto a partire dalla cartella della ricetta con il testo di esempio e il kit comune del Ricettario già inclusi; costruisce la propria pagina. Per eseguirlo, mettilo in uno `<script type="module">` di una pagina vuota, oppure incollalo nel pannello JS di un nuovo pen di CodePen (come modulo). Importa postext da esm.sh: non c’è niente da installare né da compilare.

- Cartella della ricetta: 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 ───────────────────────────────────────────────────────────────────────
```

## Errori frequenti

- Controlla il carattere lettera per lettera prima di sceglierlo. Alegreya e Piazzolla hanno ә ғ қ ң ө ұ ү һ ҙ ҫ ҡ ҳ ҷ ӣ ӯ; a Literata, Spectral e Old Standard ne mancano alcune. Vengono dai file `cyrillic-ext` che `kitCyrillicFonts` carica.
- Un titolo senza `tone` non nomina alcun disegno, e il suo pannello resta vuoto. Dai a ogni poesia uno dei quattro.

## Crediti

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

## Ricette correlate

- [Nº 209 · Dodici lingue cirilliche in un campionario](https://postext.dev/it/cookbook/cyrillic-specimen-twelve-languages.md): Un campionario di quattro pagine: un articolo in dodici lingue cirilliche, ognuna divisa con le sue regole e disegnata con le sue forme locali. · Livello 2 (Intermedio) · Cataloghi
- [Nº 030 · Un’antologia con le firme degli autori](https://postext.dev/it/cookbook/anthology-with-bylines.md): Tre saggi sul camminare i cui titoli indicano autore, anno e rivista: l’apertura li stampa tutti e tre; le testatine del verso e l’indice stampano l’autore. · Livello 2 (Intermedio) · Narrativa, teatro e prosa letteraria
- [Nº 015 · Poesie composte verso per verso](https://postext.dev/it/cookbook/poetry-collection.md): Ogni poesia è un blocco :::verse scritto come stampato: i rientri del 1918 sono spazi iniziali, i versi a capo sporgono di 2 em, righe vuote tra le strofe. · Livello 2 (Intermedio) · Poesia
