# Douze langues cyrilliques dans un spécimen

> 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.

- Version HTML: https://postext.dev/fr/cookbook/cyrillic-specimen-twelve-languages
- Recette Nº 209 · Caractères et texte · Niveau 2 (Intermédiaire) · Sorties: Canvas, PDF
- Genres: Catalogues
- 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/cyrillic-specimen-twelve-languages/en/p01.webp?v=5029f9ce), [2](https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/en/p02.webp?v=5029f9ce), [3](https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/en/p03.webp?v=5029f9ce), [4](https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/en/p04.webp?v=5029f9ce)
- Ouvrir dans le Sandbox: https://postext.dev/fr/sandbox#recipe=cyrillic-specimen-twelve-languages&lang=en (.postext: https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/en/cyrillic-specimen-twelve-languages.postext)
- Dernière mise à jour: 2026-12-02
- Autres langues: [en](https://postext.dev/en/cookbook/cyrillic-specimen-twelve-languages.md), [es](https://postext.dev/es/cookbook/cyrillic-specimen-twelve-languages.md), [ca](https://postext.dev/ca/cookbook/cyrillic-specimen-twelve-languages.md), [de](https://postext.dev/de/cookbook/cyrillic-specimen-twelve-languages.md), [el](https://postext.dev/el/cookbook/cyrillic-specimen-twelve-languages.md), [it](https://postext.dev/it/cookbook/cyrillic-specimen-twelve-languages.md), [pt](https://postext.dev/pt/cookbook/cyrillic-specimen-twelve-languages.md), [ru](https://postext.dev/ru/cookbook/cyrillic-specimen-twelve-languages.md), [zh](https://postext.dev/zh/cookbook/cyrillic-specimen-twelve-languages.md), [ja](https://postext.dev/ja/cookbook/cyrillic-specimen-twelve-languages.md), [ar](https://postext.dev/ar/cookbook/cyrillic-specimen-twelve-languages.md)

## En bref

La feuille de spécimen d’une fonderie, avec un article en douze langues cyrilliques, du russe au mongol. Chaque passage coupe ses mots selon sa langue ; le bulgare, le serbe et le macédonien montrent les lettres qu’ils dessinent autrement.

## Ce que vous allez composer

Un spécimen de 205 × 260 mm en quatre pages. La couverture est un mur de douze carreaux, chacun portant une lettre propre à un alphabet. Deux pages en vis-à-vis réunissent douze notices, six langues slaves à gauche, le kazakh, le kirghize, le tatar, le bachkir, le tadjik et le mongol à droite : le nom, les lettres particulières en vermillon, l’article premier de la Déclaration universelle des droits de l’homme en colonnes justifiées, un vers d’un auteur de la langue et l’alphabet. La dernière page montre les formes locales en grand et le mot « bibliothèque » coupé dans les douze.

**Cette recette répond à:**

- Comment composer plusieurs langues cyrilliques dans un document, avec leurs césures et leurs formes ?
- Comment obtenir une bonne justification et une bonne césure pour un texte en espagnol, en français ou en allemand ?

## La réponse courte

```js
// script.js, lignes 40–62
// The document is Russian, so that is what divides and shapes anything left unnamed. A
// passage names its language on its container:
//   :::paragraphs{style="article" lang=bg}
// Its words are divided by Bulgarian patterns and kept together by Bulgarian rules; it is
// measured, painted and embedded with the Bulgarian forms (locl) the font holds, and tagged
// as Bulgarian in the HTML and the PDF. A run inside a line takes :ltr[…]{lang=bg}.
const LOCALE = 'ru';
const bodyText = { // config().bodyText
  fontFamily: SERIF, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  textAlign: 'justify', firstLineIndent: pt(0),
  // 54 mm hold about 32 letters: words are divided at two letters, the spaces give from
  // 0.75 to 1.8 of the face's own, and a line takes up to 20 ‰ of tracking.
  hyphenation: { leftMin: 2, rightMin: 2 }, minWordSpacing: 0.75, maxWordSpacing: 1.8,
  maxJustifyTracking: 20, shapingLanguage: 'document', // the default: locale, then lang
};
const passages = [ // config().paragraphStyles
  { id: 'article', firstLineIndent: pt(0), marginBottom: pt(LEAD / 2) },
  { id: 'line', fontSize: pt(11.2), lineHeight: pt(LEAD), textAlign: 'left',
    italicColor: col('red'), hyphenation: { enabled: false }, marginBottom: pt(LEAD / 2) },
  { id: 'abc', ...face(SANS, 8.4, 400, 'muted'), lineHeight: pt(11.4), textAlign: 'left',
    hyphenation: { enabled: false } },
];
```

## 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.
- [Césure et langue du document](https://postext.dev/fr/docs/justification.md#langues-prises-en-charge): Une césure fondée sur les motifs TeX dans vingt et une langues, dont le grec et celles en alphabet cyrillique, choisie par la locale du document, qui fixe aussi les mentions de suite des tableaux et la langue du PDF balisé.
- [Passages dans l’autre sens](https://postext.dev/fr/docs/arabic-layout.md#isolats): :rtl[…] et :ltr[…] isolent un passage de l’autre sens à l’intérieur d’une ligne (un nom de produit latin dans un texte arabe, un titre arabe dans une phrase anglaise), avec un lang facultatif ; les isolats Unicode U+2066–2069 saisis dans le texte fonctionnent de la même façon.

**Utilise aussi**

- [Mots maintenus ensemble en fin de ligne](https://postext.dev/fr/docs/cyrillic-layout.md#mots-gardés-ensemble)
- [Texte courant](https://postext.dev/fr/docs/configuration-text.md#texte-courant)
- [Styles de paragraphe](https://postext.dev/fr/docs/configuration-styles.md#styles-de-paragraphe)
- [Styles de caractère](https://postext.dev/fr/docs/document-format-inline.md#styles-de-caractère)
- [Taquets de tabulation et points de conduite](https://postext.dev/fr/docs/configuration-text.md#taquets-de-tabulation)
- [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)
- [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)
- [Bandeaux à fond perdu et onglets](https://postext.dev/fr/docs/configuration-headers-footers.md#placement-des-éléments)
- [Couvertures, pages de titre et colophons](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)
- [Couleur du papier](https://postext.dev/fr/docs/configuration-page-layout.md#page)
- [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)
- [Polices intégrées au PDF](https://postext.dev/fr/docs/configuration-pdf-output.md#pourquoi-un-fournisseur-de-polices)
- [Colonnes dans un encadré ou dans le texte](https://postext.dev/fr/docs/document-format-directives.md#columns)
- [Filet de colonne](https://postext.dev/fr/docs/configuration-page-layout.md#filet-entre-colonnes)
- [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), [`characterStyles`](https://postext.dev/fr/docs/configuration-styles.md#styles-de-caractère), [`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), [`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)

**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), [`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**

- Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)

## Préparation

### 1 · Nommer deux fois la langue de chaque passage

Le code est dans [la réponse courte](https://postext.dev/fr/cookbook/cyrillic-specimen-twelve-languages.md#la-réponse-courte) ci-dessus. `lang` sur un bloc `:::paragraphs` déclare la langue de son texte : il choisit les [motifs qui coupent ses mots](https://postext.dev/fr/docs/cyrillic-layout.md#césure-en-douze-langues), et le texte est mesuré, peint et incorporé avec les formes que le caractère réserve à cette langue, puis balisé comme tel dans le PDF et le HTML. Un passage au milieu d’une ligne prend un isolat, `:ltr[…]{lang=bg}`. Les colonnes font 54 mm : on peut couper après deux lettres, et une ligne admet jusqu’à 20 ‰ d’interlettrage.

### 2 · Un titre, quatre données

```js
// script.js, lignes 66–80
// ## Українська {code="uk" letters="33 буквы" special="Ґ Є І Ї"}
const entry = { level: 2, fontFamily: SERIF, fontSize: pt(21), lineHeight: pt(26), fontWeight: 900,
  marginTop: pt(0), marginBottom: pt(LEAD / 4),
  advancedDesign: { enabled: true, minHeight: mm(25.4), slot: { elements: [
    { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(2.5), color: col('ink'),
      placement: { ...at('container', 'top-left'), size: { width: 'fill' } } },
    text('code', '{attr.code}', face(SANS, 8, 700, 'red', { textTransform: 'uppercase',
      letterSpacing: pt(1.2) }), at('container', 'top-left', 0, 2.6)),
    text('count', '{attr.letters}', face(SANS, 8, 400, 'muted', { align: 'right' }),
      at('container', 'top-right', 0, 2.6)),
    text('name', '{titleText}', face(SERIF, 22, 900, 'ink', { lineHeight: 1.1 }),
      at('container', 'top-left', 0, 6.6)),
    text('special', '{attr.special}', face(SERIF, 17, 700, 'red', { lineHeight: 1.2 }),
      at('container', 'top-left', 0, 18)),
  ] } } };
```

Le code, le nombre de lettres et les lettres absentes du russe voyagent dans le titre : `## Українська {code="uk" letters="33 буквы" special="Ґ Є І Ї"}`. La composition les imprime sous un filet gras, et `minHeight` donne à toutes les notices la même tête : les textes d’une rangée commencent sur la même ligne.

### 3 · Un mur de lettres

```js
// script.js, lignes 94–113
const [TILE_W, TILE_H] = [TRIM_W / 3, 52]; // mm
const INKS = ['red', 'ink', 'ochre', 'pine', 'cream', 'red', 'ink', 'ochre', 'pine', 'red', 'ink',
  'cream']; // ink of each tile, row by row
const tile = (ink, i) => {
  const place = { ...at('page', 'top-left', (i % 3) * TILE_W, Math.floor(i / 3) * TILE_H),
    size: { width: mm(TILE_W), height: mm(TILE_H) } };
  const letter = ink === 'cream' ? 'red' : ink === 'ochre' ? 'ink' : 'cream';
  return [{ kind: 'box', id: `tile-${i}`, style: { backgroundColor: col(ink) }, placement: place },
    text(`letter-${i}`, `{attr.l${i + 1}}`, face(SERIF, 108, 900, letter, { align: 'center',
      verticalAlign: 'center', lineHeight: 1 }), place)];
};
const cover = { id: 'cover', breakBefore: { enabled: true, parity: 'any' },
  header: { elements: [] }, footer: { elements: [] },
  advancedDesign: { enabled: true, minHeight: mm(200), slot: { elements: [
    ...INKS.flatMap(tile),
    text('title', '{titleText}', face(SERIF, 40, 900, 'ink', { lineHeight: 1.05, align: 'left' }),
      { ...at('page', 'top-left', SIDE, 4 * TILE_H + 10), size: { width: mm(TRIM_W - 2 * SIDE) } }),
    text('subtitle', '{subtitle}', face(SANS, 13, 400, 'muted', { lineHeight: 1.3, align: 'left' }),
      { ...at('#title', 'below', 0, 2), size: { width: 'fill' } }),
  ] } } };
```

Les douze lettres de la couverture sont les attributs `l1` à `l12` de son titre, et la composition bâtit une boîte et un texte pour chacune à partir d’une liste d’encres. Changer une lettre, c’est changer le Markdown. Les carreaux partent du coin de la page et vont jusqu’à la coupe.

### 4 · Formes locales, ligne à ligne

```js
// script.js, lignes 117–127
const tabs = (...at) => at.map((x) => ({ position: mm(x), align: 'start' }));
const formsStyles = [ // config().paragraphStyles
  { id: 'forms', fontSize: pt(29), lineHeight: pt(3 * LEAD), textAlign: 'left',
    tabStops: tabs(26, 78), hyphenation: { enabled: false } },
  { id: 'weights', fontSize: pt(15.5), lineHeight: pt(2 * LEAD), textAlign: 'left',
    hyphenation: { enabled: false } },
  { id: 'cuts', fontSize: pt(12), lineHeight: pt(1.5 * LEAD), textAlign: 'left', tabStops: tabs(22),
    hyphenation: { enabled: false } },
  { id: 'colophon', ...face(SANS, 7.8, 400, 'muted'), lineHeight: pt(11), textAlign: 'left',
    marginTop: pt(3 * LEAD), hyphenation: { locale: LANG, enabled: false } },
];
```

La même chaîne passe par le caractère en russe puis en bulgare ; en italique, en russe, en serbe et en macédonien. Source Serif 4 a les trois jeux. Des taquets alignent les rangées, chacune étant un isolat dans sa langue. [Mise en valeur et formes locales](https://postext.dev/fr/docs/cyrillic-layout.md#mise-en-valeur-accent-tonique-et-vers) donne la liste des lettres qui changent.

## 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/cyrillic-specimen-twelve-languages

### script.js

```js
// ═══ Postext Cookbook · Nº 209 · Twelve Cyrillic languages in one type specimen ═══════
// https://postext.dev/en/cookbook/cyrillic-specimen-twelve-languages
// Code: MIT · Text: UDHR, article 1 (UN, PD) and lines by twelve authors (PD) · Pictures: none
// Fonts: Source Serif 4, Source Sans 3 (SIL OFL 1.1) · Needs postext ≥ 1.100.0
import { buildDocumentWithFonts, renderPageToCanvas } 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 = 'cyrillic-specimen-twelve-languages';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// The sheet of a type foundry between the wars: black, vermilion and two dull inks on cream.
const palette = {
  ink: '#1d1b1a', // text, heavy rules, the dark tiles
  red: '#b8321e', // the letters Russian lacks, the plates' titles, red tiles
  pine: '#1f4b4a', // green tiles
  ochre: '#d59b3a', // ochre tiles
  cream: '#f6efdf', // the paper and the letters on the tiles
  muted: '#655d51', // alphabets, author names, the colophon
};
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' } }));
const [SERIF, SANS] = ['Source Serif 4', 'Source Sans 3']; // both draw local forms by language
const [BODY, LEAD] = [10.5, 14]; // pt
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const text = (id, content, look, placement) => ({ kind: 'text', id, content, overflow: 'wrap',
  ...look, placement });
const face = (fontFamily, size, fontWeight, color, extra = {}) => ({ fontFamily,
  fontSize: pt(size), fontWeight, color: col(color), ...extra });

// #region page: 84 × 108/16, 205 × 260 mm trimmed, three columns to a plate
const [TRIM_W, SIDE] = [205, 15]; // mm
const page = { sizePreset: '84x108/16', dpi: 150, backgroundColor: col('cream'),
  margins: { top: mm(18), bottom: mm(17), left: mm(SIDE), right: mm(SIDE), mirror: true } };
const COLUMN_GAP = 6; // mm
// #endregion

// #region answer: each passage named in its own language, for its breaks and its letters
// The document is Russian, so that is what divides and shapes anything left unnamed. A
// passage names its language on its container:
//   :::paragraphs{style="article" lang=bg}
// Its words are divided by Bulgarian patterns and kept together by Bulgarian rules; it is
// measured, painted and embedded with the Bulgarian forms (locl) the font holds, and tagged
// as Bulgarian in the HTML and the PDF. A run inside a line takes :ltr[…]{lang=bg}.
const LOCALE = 'ru';
const bodyText = { // config().bodyText
  fontFamily: SERIF, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  textAlign: 'justify', firstLineIndent: pt(0),
  // 54 mm hold about 32 letters: words are divided at two letters, the spaces give from
  // 0.75 to 1.8 of the face's own, and a line takes up to 20 ‰ of tracking.
  hyphenation: { leftMin: 2, rightMin: 2 }, minWordSpacing: 0.75, maxWordSpacing: 1.8,
  maxJustifyTracking: 20, shapingLanguage: 'document', // the default: locale, then lang
};
const passages = [ // config().paragraphStyles
  { id: 'article', firstLineIndent: pt(0), marginBottom: pt(LEAD / 2) },
  { id: 'line', fontSize: pt(11.2), lineHeight: pt(LEAD), textAlign: 'left',
    italicColor: col('red'), hyphenation: { enabled: false }, marginBottom: pt(LEAD / 2) },
  { id: 'abc', ...face(SANS, 8.4, 400, 'muted'), lineHeight: pt(11.4), textAlign: 'left',
    hyphenation: { enabled: false } },
];
// #endregion

// #region entry: a heavy rule, the language's name and the letters Russian lacks
// ## Українська {code="uk" letters="33 буквы" special="Ґ Є І Ї"}
const entry = { level: 2, fontFamily: SERIF, fontSize: pt(21), lineHeight: pt(26), fontWeight: 900,
  marginTop: pt(0), marginBottom: pt(LEAD / 4),
  advancedDesign: { enabled: true, minHeight: mm(25.4), slot: { elements: [
    { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(2.5), color: col('ink'),
      placement: { ...at('container', 'top-left'), size: { width: 'fill' } } },
    text('code', '{attr.code}', face(SANS, 8, 700, 'red', { textTransform: 'uppercase',
      letterSpacing: pt(1.2) }), at('container', 'top-left', 0, 2.6)),
    text('count', '{attr.letters}', face(SANS, 8, 400, 'muted', { align: 'right' }),
      at('container', 'top-right', 0, 2.6)),
    text('name', '{titleText}', face(SERIF, 22, 900, 'ink', { lineHeight: 1.1 }),
      at('container', 'top-left', 0, 6.6)),
    text('special', '{attr.special}', face(SERIF, 17, 700, 'red', { lineHeight: 1.2 }),
      at('container', 'top-left', 0, 18)),
  ] } } };
// #endregion

// #region plate: the band over a page of six languages
const plate = { id: 'plate', breakBefore: { enabled: true, parity: 'any' }, marginBottom: pt(LEAD),
  advancedDesign: { enabled: true, minHeight: mm(20), slot: { elements: [
    text('title', '{titleText}', face(SERIF, 27, 900, 'red', { lineHeight: 1.1, align: 'left' }),
      { ...at('container', 'top-left'), size: { width: 'fill' } }),
    text('lead', '{attr.lead}', face(SANS, 10.5, 400, 'ink', { lineHeight: 1.3, align: 'left' }),
      { ...at('#title', 'below', 0, 1.5), size: { width: 'fill' } }),
  ] } } };
// #endregion

// #region cover: twelve letters, one from each alphabet, on a wall of tiles
const [TILE_W, TILE_H] = [TRIM_W / 3, 52]; // mm
const INKS = ['red', 'ink', 'ochre', 'pine', 'cream', 'red', 'ink', 'ochre', 'pine', 'red', 'ink',
  'cream']; // ink of each tile, row by row
const tile = (ink, i) => {
  const place = { ...at('page', 'top-left', (i % 3) * TILE_W, Math.floor(i / 3) * TILE_H),
    size: { width: mm(TILE_W), height: mm(TILE_H) } };
  const letter = ink === 'cream' ? 'red' : ink === 'ochre' ? 'ink' : 'cream';
  return [{ kind: 'box', id: `tile-${i}`, style: { backgroundColor: col(ink) }, placement: place },
    text(`letter-${i}`, `{attr.l${i + 1}}`, face(SERIF, 108, 900, letter, { align: 'center',
      verticalAlign: 'center', lineHeight: 1 }), place)];
};
const cover = { id: 'cover', breakBefore: { enabled: true, parity: 'any' },
  header: { elements: [] }, footer: { elements: [] },
  advancedDesign: { enabled: true, minHeight: mm(200), slot: { elements: [
    ...INKS.flatMap(tile),
    text('title', '{titleText}', face(SERIF, 40, 900, 'ink', { lineHeight: 1.05, align: 'left' }),
      { ...at('page', 'top-left', SIDE, 4 * TILE_H + 10), size: { width: mm(TRIM_W - 2 * SIDE) } }),
    text('subtitle', '{subtitle}', face(SANS, 13, 400, 'muted', { lineHeight: 1.3, align: 'left' }),
      { ...at('#title', 'below', 0, 2), size: { width: 'fill' } }),
  ] } } };
// #endregion

// #region forms: the same letters at display size, each row in its own language
const tabs = (...at) => at.map((x) => ({ position: mm(x), align: 'start' }));
const formsStyles = [ // config().paragraphStyles
  { id: 'forms', fontSize: pt(29), lineHeight: pt(3 * LEAD), textAlign: 'left',
    tabStops: tabs(26, 78), hyphenation: { enabled: false } },
  { id: 'weights', fontSize: pt(15.5), lineHeight: pt(2 * LEAD), textAlign: 'left',
    hyphenation: { enabled: false } },
  { id: 'cuts', fontSize: pt(12), lineHeight: pt(1.5 * LEAD), textAlign: 'left', tabStops: tabs(22),
    hyphenation: { enabled: false } },
  { id: 'colophon', ...face(SANS, 7.8, 400, 'muted'), lineHeight: pt(11), textAlign: 'left',
    marginTop: pt(3 * LEAD), hyphenation: { locale: LANG, enabled: false } },
];
// #endregion

const folio = (parity, edge, x) => text(`folio-${parity}`, '{pageNumber}',
  face(SANS, 9, 700, 'ink', { parity }), at('page', edge, x, -9));
const config = () => ({
  locale: LOCALE, // written out, never LANG: the specimen is Russian in every edition
  colorPalette, page, bodyText,
  layout: { layoutType: 'single', gutterWidth: mm(COLUMN_GAP),
    columnRule: { enabled: false, color: col('muted'), lineWidth: pt(0.5) } },
  headings: { fontFamily: SERIF, fontWeight: 900, color: col('ink'), levels: [
    { level: 1, breakBefore: { enabled: true, parity: 'any' } }, entry,
    { level: 3, fontFamily: SANS, fontSize: pt(11), lineHeight: pt(LEAD), fontWeight: 700,
      color: col('red'), marginTop: pt(LEAD), marginBottom: pt(0) },
  ] },
  headingStyles: [cover, plate],
  paragraphStyles: [...passages, ...formsStyles],
  characterStyles: [
    { id: 'who', ...face(SANS, 8.4, 400, 'muted') },
    { id: 'black', fontWeight: 900 },
    { id: 'tag', ...face(SANS, 9, 400, 'muted') },
  ],
  header: { elements: [] },
  footer: { elements: [folio('even', 'bottom-left', SIDE), folio('odd', 'bottom-right', -SIDE)] },
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The specimen (content.text.<lang>.md), then its colophon in the edition's language.
const markdown = [String.raw`---
title: "Двенадцать кириллиц"
subtitle: "Образцы шрифта для набора на двенадцати языках"
---

# Двенадцать кириллиц {style="cover" l1="Ж" l2="Ї" l3="Ў" l4="Ъ" l5="Ђ" l6="Ѓ" l7="Қ" l8="Ң" l9="Җ" l10="Ҙ" l11="Ӯ" l12="Ө"}

# Славянские языки {style="plate" lead="Статья 1 Всеобщей декларации прав человека с переносами по правилам каждого языка"}

:::columns{count=3 breaks="5,9" marginBottom="3em"}
## Русский {code="ru" letters="33 буквы" special="Ё Ъ Ы Э"}

:::paragraphs{style="article" lang=ru}
Все люди рождаются свободными и равными в своем достоинстве и правах. Они наделены разумом и совестью и должны поступать в отношении друг друга в духе братства.
:::

:::paragraphs{style="line" lang=ru}
*Мороз и солнце; день чудесный!*\
:span[А. С. Пушкин]{style="who"}
:::

:::paragraphs{style="abc" lang=ru}
Аа Бб Вв Гг Дд Ее Ёё Жж Зз Ии Йй Кк Лл Мм Нн Оо Пп Рр Сс Тт Уу Фф Хх Цц Чч Шш Щщ Ъъ Ыы Ьь Ээ Юю Яя
:::

## Українська {code="uk" letters="33 буквы" special="Ґ Є І Ї"}

:::paragraphs{style="article" lang=uk}
Всі люди народжуються вільними і рівними у своїй гідності та правах. Вони наділені розумом і совістю і повинні діяти у відношенні один до одного в дусі братерства.
:::

:::paragraphs{style="line" lang=uk}
*Реве та стогне Дніпр широкий*\
:span[Т. Г. Шевченко]{style="who"}
:::

:::paragraphs{style="abc" lang=uk}
Аа Бб Вв Гг Ґґ Дд Ее Єє Жж Зз Ии Іі Її Йй Кк Лл Мм Нн Оо Пп Рр Сс Тт Уу Фф Хх Цц Чч Шш Щщ Ьь Юю Яя
:::

## Беларуская {code="be" letters="32 буквы" special="І Ў Ё Э"}

:::paragraphs{style="article" lang=be}
Усе людзі нараджаюцца свабоднымі і роўнымі ў сваёй годнасці і правах. Яны надзелены розумам і сумленнем і павінны ставіцца адзін да аднаго ў духу брацтва.
:::

:::paragraphs{style="line" lang=be}
*А хто там ідзе, а хто там ідзе?*\
:span[Янка Купала]{style="who"}
:::

:::paragraphs{style="abc" lang=be}
Аа Бб Вв Гг Дд Ее Ёё Жж Зз Іі Йй Кк Лл Мм Нн Оо Пп Рр Сс Тт Уу Ўў Фф Хх Цц Чч Шш Ыы Ьь Ээ Юю Яя
:::
:::

:::columns{count=3 breaks="5,9" marginBottom="3em"}
## Български {code="bg" letters="30 букв" special="Ъ Щ Ю Я"}

:::paragraphs{style="article" lang=bg}
Всички хора се раждат свободни и равни по достойнство и права. Те са надарени с разум и съвест и следва да се отнасят помежду си в дух на братство.
:::

:::paragraphs{style="line" lang=bg}
*Тая прохладна майска вечер*\
:span[Иван Вазов]{style="who"}
:::

:::paragraphs{style="abc" lang=bg}
Аа Бб Вв Гг Дд Ее Жж Зз Ии Йй Кк Лл Мм Нн Оо Пп Рр Сс Тт Уу Фф Хх Цц Чч Шш Щщ Ъъ Ьь Юю Яя
:::

## Српски {code="sr" letters="30 букв" special="Ђ Ј Љ Њ Ћ Џ"}

:::paragraphs{style="article" lang=sr}
Сва људска бића рађају се слободна и једнака у достојанству и правима. Она су обдарена разумом и свешћу и треба једни према другима да поступају у духу братства.
:::

:::paragraphs{style="line" lang=sr}
*Пиши као што говориш*\
:span[Вук Караџић]{style="who"}
:::

:::paragraphs{style="abc" lang=sr}
Аа Бб Вв Гг Дд Ђђ Ее Жж Зз Ии Јј Кк Лл Љљ Мм Нн Њњ Оо Пп Рр Сс Тт Ћћ Уу Фф Хх Цц Чч Џџ Шш
:::

## Македонски {code="mk" letters="31 буква" special="Ѓ Ѕ Ј Љ Њ Ќ Џ"}

:::paragraphs{style="article" lang=mk}
Сите човечки суштества се раѓаат слободни и еднакви по достоинство и права. Тие се обдарени со разум и совест и треба да се однесуваат еден кон друг во духот на општо човечката припадност.
:::

:::paragraphs{style="line" lang=mk}
*Како на вратот ѓердани*\
:span[Кочо Рацин]{style="who"}
:::

:::paragraphs{style="abc" lang=mk}
Аа Бб Вв Гг Дд Ѓѓ Ее Жж Зз Ѕѕ Ии Јј Кк Лл Љљ Мм Нн Њњ Оо Пп Рр Сс Тт Ќќ Уу Фф Хх Цц Чч Џџ Шш
:::
:::

# От Казани до Улан-Батора {style="plate" lead="Тюркские языки, таджикский и монгольский: красным набраны буквы, которых нет в русском алфавите"}

:::columns{count=3 breaks="5,9" marginBottom="1em"}
## Қазақша {code="kk" letters="42 буквы" special="Ә Ғ Қ Ң Ө Ұ Ү Һ І"}

:::paragraphs{style="article" lang=kk}
Барлық адамдар тумысынан азат және қадір-қасиеті мен құқықтары тең болып дүниеге келеді. Адамдарға ақыл-парасат, ар-ождан берілген, сондықтан олар бір-бірімен туыстық, бауырмалдық қарым-қатынас жасаулары тиіс.
:::

:::paragraphs{style="line" lang=kk}
*Ғылым таппай мақтанба*\
:span[Абай]{style="who"}
:::

:::paragraphs{style="abc" lang=kk}
Аа Әә Бб Вв Гг Ғғ Дд Ее Ёё Жж Зз Ии Йй Кк Ққ Лл Мм Нн Ңң Оо Өө Пп Рр Сс Тт Уу Ұұ Үү Фф Хх Һһ Цц Чч Шш Щщ Ъъ Ыы Іі Ьь Ээ Юю Яя
:::

## Кыргызча {code="ky" letters="36 букв" special="Ң Ө Ү"}

:::paragraphs{style="article" lang=ky}
Бардык адамдар өз беделинде жана укуктарында эркин жана тең укуктуу болуп жаралат. Алардын аң-сезими менен абийири бар жана бири-бирине бир туугандык мамиле кылууга тийиш.
:::

:::paragraphs{style="line" lang=ky}
*Дайранын көркү кемеде*\
:span[Токтогул]{style="who"}
:::

:::paragraphs{style="abc" lang=ky}
Аа Бб Вв Гг Дд Ее Ёё Жж Зз Ии Йй Кк Лл Мм Нн Ңң Оо Өө Пп Рр Сс Тт Уу Үү Фф Хх Цц Чч Шш Щщ Ъъ Ыы Ьь Ээ Юю Яя
:::

## Татарча {code="tt" letters="39 букв" special="Ә Җ Ң Ө Ү Һ"}

:::paragraphs{style="article" lang=tt}
Барлык кешеләр дә азат һәм үз абруйлары һәм хокуклары ягыннан тиң булып туалар. Аларга акыл һәм вөҗдан бирелгән һәм бер-берсенә карата туганнарча мөнәсәбәттә булырга тиешләр.
:::

:::paragraphs{style="line" lang=tt}
*И туган тел, и матур тел*\
:span[Габдулла Тукай]{style="who"}
:::

:::paragraphs{style="abc" lang=tt}
Аа Әә Бб Вв Гг Дд Ее Ёё Жж Җҗ Зз Ии Йй Кк Лл Мм Нн Ңң Оо Өө Пп Рр Сс Тт Уу Үү Фф Хх Һһ Цц Чч Шш Щщ Ъъ Ыы Ьь Ээ Юю Яя
:::
:::

:::columns{count=3 breaks="5,9" marginBottom="1em"}
## Башҡортса {code="ba" letters="42 буквы" special="Ғ Ҙ Ҡ Ң Ө Ҫ Ү Һ Ә"}

:::paragraphs{style="article" lang=ba}
Барлыҡ кешеләр ирекле, дәрәжәләре һәм хоҡуҡтары тигеҙ булып тыуалар. Улар аҡыл һәм выждан эйәһе һәм бер-береһенә ҡарата ҡәрҙәшлек рухында хәрәкәт итергә тейештәр.
:::

:::paragraphs{style="line" lang=ba}
*Башҡорттарым, уҡыу кәрәк*\
:span[М. Аҡмулла]{style="who"}
:::

:::paragraphs{style="abc" lang=ba}
Аа Бб Вв Гг Ғғ Дд Ҙҙ Ее Ёё Жж Зз Ии Йй Кк Ҡҡ Лл Мм Нн Ңң Оо Өө Пп Рр Сс Тт Ҫҫ Уу Үү Фф Хх Һһ Цц Чч Шш Щщ Ъъ Ыы Ьь Ээ Әә Юю Яя
:::

## Тоҷикӣ {code="tg" letters="35 букв" special="Ғ Ӣ Қ Ӯ Ҳ Ҷ"}

:::paragraphs{style="article" lang=tg}
Тамоми одамон озод ва аз лиҳози шарафу ҳуқуқ ба ҳам баробар ба дунё меоянд. Онҳо соҳиби ақлу виҷдонанд ва бояд бо якдигар муносибати бародарона дошта бошанд.
:::

:::paragraphs{style="line" lang=tg}
*Бӯи ҷӯи Мӯлиён ояд ҳаме*\
:span[Рӯдакӣ]{style="who"}
:::

:::paragraphs{style="abc" lang=tg}
Аа Бб Вв Гг Ғғ Дд Ее Ёё Жж Зз Ии Ӣӣ Йй Кк Ққ Лл Мм Нн Оо Пп Рр Сс Тт Уу Ӯӯ Фф Хх Ҳҳ Чч Ҷҷ Шш Ъъ Ээ Юю Яя
:::

## Монгол {code="mn" letters="35 букв" special="Ө Ү"}

:::paragraphs{style="article" lang=mn}
Хүн бүр төрж мэндлэхэд эрх чөлөөтэй, адилхан нэр төртэй, ижил эрхтэй байдаг. Оюун ухаан, нандин чанар заяасан хүн гэгч өөр хоорондоо ахан дүүгийн үзэл санаагаар харьцах учиртай.
:::

:::paragraphs{style="line" lang=mn}
*Энэ бол миний төрсөн нутаг*\
:span[Д. Нацагдорж]{style="who"}
:::

:::paragraphs{style="abc" lang=mn}
Аа Бб Вв Гг Дд Ее Ёё Жж Зз Ии Йй Кк Лл Мм Нн Оо Өө Пп Рр Сс Тт Уу Үү Фф Хх Цц Чч Шш Щщ Ъъ Ыы Ьь Ээ Юю Яя
:::
:::

# Местные формы {style="plate" lead="Одна буква, разные рисунки: шрифт берёт их по языку текста"}

### Прямой шрифт: Россия и Болгария

:::paragraphs{style="forms"}
:span[Русский]{style="tag"}	:ltr[в г д ж з и й к л п т ц ш щ ю]{lang=ru}

:span[Български]{style="tag"}	:ltr[в г д ж з и й к л п т ц ш щ ю]{lang=bg}
:::

### Курсив: Россия, Сербия и Македония

:::paragraphs{style="forms"}
:span[Русский]{style="tag"}	:ltr[*б г д п т*]{lang=ru}	:ltr[*Добрый день, город*]{lang=ru}

:span[Српски]{style="tag"}	:ltr[*б г д п т*]{lang=sr}	:ltr[*Добар дан, граде*]{lang=sr}

:span[Македонски]{style="tag"}	:ltr[*б г д п т*]{lang=mk}	:ltr[*Добар ден, граде*]{lang=mk}
:::

### Три насыщенности

:::paragraphs{style="weights"}
Съешь ещё этих мягких французских булок, да выпей чаю

**Съешь ещё этих мягких французских булок, да выпей чаю**

:span[Съешь ещё этих мягких французских булок, да выпей чаю]{style="black"}
:::

### Библиотека на двенадцати языках

:::columns{count=3 breaks="5,9"}
:::paragraphs{style="cuts"}
:span[Русский]{style="tag"}	:ltr[биб·лио·те·ка]{lang=ru}

:span[Українська]{style="tag"}	:ltr[бі·бліо·те·ка]{lang=uk}

:span[Беларуская]{style="tag"}	:ltr[біб·лія·тэ·ка]{lang=be}

:span[Български]{style="tag"}	:ltr[биб·ли·о·те·ка]{lang=bg}

:span[Српски]{style="tag"}	:ltr[би·бли·о·те·ка]{lang=sr}

:span[Македонски]{style="tag"}	:ltr[би·бли·о·те·ка]{lang=mk}

:span[Қазақша]{style="tag"}	:ltr[кі·тап·ха·на]{lang=kk}

:span[Кыргызча]{style="tag"}	:ltr[ки·теп·ка·на]{lang=ky}

:span[Татарча]{style="tag"}	:ltr[ки·тап·ха·нә]{lang=tt}

:span[Башҡортса]{style="tag"}	:ltr[ки·тап·ха·на]{lang=ba}

:span[Тоҷикӣ]{style="tag"}	:ltr[ки·тоб·хо·на]{lang=tg}

:span[Монгол]{style="tag"}	:ltr[хэв·лэл]{lang=mn}
:::
:::

`, String.raw`:::paragraphs{style="colophon"}
Set in Source Serif 4 and Source Sans 3 (SIL OFL) · Text: UDHR, article 1, and lines by the authors named, public domain
:::
`].join('\n\n');

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { // every face the pages use, with the Cyrillic files their letters need
  'Source Serif 4': ['400', '400i', '700', '900'],
  'Source Sans 3': ['400', '700'],
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown }, config(), kitCyrillicFonts(FONTS));
showPages(doc, { title: 'Двенадцать кириллиц' });
offerPdf(() => renderToPdf(doc, { fontProvider: cyrillicPdfProvider }), `${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 · 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

- Le caractère doit avoir les formes. PT Serif n’en a aucune pour ces langues ; Vollkorn et Lora ont les bulgares et les serbes. Sans elles, l’isolat coupe et balise toujours le texte, mais les lettres restent russes.
- Il doit aussi avoir les lettres. Ә, Ғ, Ң, Ҙ, Ҷ et Ӯ sont dans le fichier `cyrillic-ext` de la famille, que charge `kitCyrillicFonts` ; il en manque à Literata et à Spectral.

## Crédits

- Recette: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Texte: Article 1 of the Universal Declaration of Human Rights in eleven languages, from the plain texts of the UDHR in XML project, with four misprints of the Kazakh, Kyrgyz and Tatar files corrected: United Nations ([source](http://efele.net/udhr/assemblies/first_article_all.txt)), domaine public
- Texte: Article 1 in Bashkir: United Nations ([source](https://www.omniglot.com/writing/bashkir.htm)), domaine public
- Texte: Opening lines and sayings of Pushkin, Shevchenko, Kupala, Vazov, Vuk Karadžić, Racin, Abai, Toktogul, Tukay, Akmulla, Rudaki and Natsagdorj: The authors named, domaine public
- Texte: The titles, the alphabets and the colophon: Postext Cookbook, original
- Caractères: Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)
- Code: MIT · Contenu d’exemple: MIT

## Recettes liées

- [Nº 210 · Abaï et cinq poètes de la steppe, anthologie kazakhe](https://postext.dev/fr/cookbook/abai-kazakh-anthology.md): 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. · Niveau 2 (Intermédiaire) · Poésie
- [Nº 201 · Un roman grec coupé selon le grec monotonique](https://postext.dev/fr/cookbook/monotonic-greek-novel.md): Le premier chapitre de « Η τιμή και το χρήμα » de Theotokis en livre de 13,5 × 20,5 cm : motifs du grec monotonique, guillemets «» et capitales sans accent. · Niveau 2 (Intermédiaire) · Fiction, théâtre et prose littéraire
- [Nº 153 · Une planche lettrée en six langues](https://postext.dev/fr/cookbook/one-page-six-languages.md): Une planche de BD, découpage et images fixes, lettrée par langue : la langue choisit le caractère ; japonais vertical, japonais et arabe de droite à gauche. · Niveau 3 (Avancé) · Bande dessinée
