# Dotze llengües ciríl·liques en un mostrari tipogràfic

> Un mostrari de quatre pàgines: un article en dotze llengües ciríl·liques, cadascuna partida per les seves regles i amb les seves formes locals.

- Versió HTML: https://postext.dev/ca/cookbook/cyrillic-specimen-twelve-languages
- Recepta Núm. 209 · Text i tipografia · Nivell 2 (Intermedi) · Sortides: Canvas, PDF
- Gèneres: Catàlegs
- Requereix postext ≥ 1.100.0, postext-pdf ≥ 1.100.0 · provada amb 1.100.0, postext-pdf 1.100.0 el 2026-12-02
- Pàgines: [1](https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/es/p01.webp?v=d38f31fe), [2](https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/es/p02.webp?v=d38f31fe), [3](https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/es/p03.webp?v=d38f31fe), [4](https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/es/p04.webp?v=d38f31fe)
- Obre al Sandbox: https://postext.dev/ca/sandbox#recipe=cyrillic-specimen-twelve-languages&lang=es (.postext: https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/es/cyrillic-specimen-twelve-languages.postext)
- Última actualització: 2026-12-02
- Altres idiomes: [en](https://postext.dev/en/cookbook/cyrillic-specimen-twelve-languages.md), [es](https://postext.dev/es/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), [fr](https://postext.dev/fr/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 poques paraules

El full de mostres d'una foneria amb un article en dotze llengües ciríl·liques, del rus al mongol. Cada passatge parteix segons la seva llengua; el búlgar, el serbi i el macedoni ensenyen les lletres que dibuixen d'una altra manera.

## Què compondràs

Un mostrari de 205 × 260 mm en quatre pàgines. La coberta és un mur de dotze rajoles, cadascuna amb una lletra pròpia d'un alfabet. Dues pàgines encarades apleguen dotze fitxes, sis llengües eslaves a l'esquerra i kazakh, kirguís, tàtar, baixkir, tadjik i mongol a la dreta: el nom, les lletres especials en vermelló, l'article 1 de la Declaració Universal dels Drets Humans en columnes justificades, un vers d'un autor de la llengua i l'alfabet. L'última pàgina mostra les formes locals a cos gran i el mot «biblioteca» partit en les dotze.

**Aquesta recepta respon a:**

- Com componc diverses llengües ciríl·liques en un document, cadascuna amb les seves particions i formes?
- Com aconsegueixo una bona justificació i partició de mots en textos en castellà, francès o alemany?

## La resposta curta

```js
// script.js, línies 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 } },
];
```

## Ingredients

**Ensenya**

- [Les llengües d'alfabet ciríl·lic com a llengua del document](https://postext.dev/ca/docs/cyrillic-layout.md#començar-un-llibre-en-ciríllic): locale 'ru', 'uk', 'be', 'bg', 'sr', 'mk', 'kk', 'ky', 'tt', 'ba', 'tg' o 'mn' dona al llibre la partició de mots, els peus, els títols de taula, les notes, els números en lletra, els formats de plec i el sentit del llom de la seva llengua.
- [Partició de mots i llengua del document](https://postext.dev/ca/docs/justification.md#llengües-compatibles): Partició de mots amb patrons de TeX en vint-i-una llengües, el grec i les d'alfabet ciríl·lic entre elles, segons el locale del document, que fixa també els textos de continuació de les taules i la llengua del PDF etiquetat.
- [Fragments en l'altra direcció](https://postext.dev/ca/docs/arabic-layout.md#aïllaments): :rtl[…] i :ltr[…] aïllen un fragment de l'altra direcció dins d'una línia (un nom de producte llatí en àrab, un títol àrab en una frase anglesa), amb un lang opcional; els aïlladors Unicode U+2066–2069 escrits al text funcionen igual.

**També fa servir**

- [Paraules que no se separen a final de línia](https://postext.dev/ca/docs/cyrillic-layout.md#paraules-que-van-juntes)
- [Tipografia del text](https://postext.dev/ca/docs/configuration-text.md#text-de-cos)
- [Estils de paràgraf](https://postext.dev/ca/docs/configuration-styles.md#estils-de-paràgraf)
- [Estils de caràcter](https://postext.dev/ca/docs/document-format-inline.md#estils-de-caràcter)
- [Tabuladors i farciments](https://postext.dev/ca/docs/configuration-text.md#tabulacions)
- [Obertures dissenyades](https://postext.dev/ca/docs/configuration-headings.md#extensió-i-disseny-avançat)
- [Estils de títol](https://postext.dev/ca/docs/configuration-styles.md#estils-dencapçalament)
- [Atributs de títol](https://postext.dev/ca/docs/document-format.md#atributs-dencapçalament)
- [Textos, filets i caixes als dissenys de pàgina](https://postext.dev/ca/docs/configuration-headers-footers.md#capçaleres-i-peus)
- [Bandes a sang i pestanyes](https://postext.dev/ca/docs/configuration-headers-footers.md#posicionament-delements)
- [Cobertes, portades i colofons](https://postext.dev/ca/docs/configuration-styles.md#estils-dencapçalament)
- [Marges simètrics](https://postext.dev/ca/docs/configuration-page-layout.md#marges-simètrics)
- [Color del paper](https://postext.dev/ca/docs/configuration-page-layout.md#pàgina)
- [Paleta de color semàntica](https://postext.dev/ca/docs/configuration-fonts-colors-viewers.md#paleta-de-colors)
- [Exportació a PDF](https://postext.dev/ca/docs/configuration-pdf-output.md#generació-de-pdf)
- [Fonts incrustades al PDF](https://postext.dev/ca/docs/configuration-pdf-output.md#per-què-un-proveïdor-de-fonts)
- [Columnes en un requadre o al text](https://postext.dev/ca/docs/document-format-directives.md#columns)
- [Filet de columna](https://postext.dev/ca/docs/configuration-page-layout.md#filet-de-columna)
- [Capçaleres per secció](https://postext.dev/ca/docs/configuration-styles.md#estils-dencapçalament)

**La configuració d'un cop d'ull**

- [`bodyText`](https://postext.dev/ca/docs/configuration-text.md#text-de-cos), [`characterStyles`](https://postext.dev/ca/docs/configuration-styles.md#estils-de-caràcter), [`colorPalette`](https://postext.dev/ca/docs/configuration-fonts-colors-viewers.md#paleta-de-colors), [`footer`](https://postext.dev/ca/docs/configuration-headers-footers.md#capçaleres-i-peus), [`header`](https://postext.dev/ca/docs/configuration-headers-footers.md#capçaleres-i-peus), [`headingStyles`](https://postext.dev/ca/docs/configuration-styles.md#estils-dencapçalament), [`headings`](https://postext.dev/ca/docs/configuration-headings.md#encapçalaments), [`layout`](https://postext.dev/ca/docs/configuration-page-layout.md#disposició), [`locale`](https://postext.dev/ca/docs/configuration-language.md#partició-de-mots), [`page`](https://postext.dev/ca/docs/configuration-page-layout.md#pàgina), [`paragraphStyles`](https://postext.dev/ca/docs/configuration-styles.md#estils-de-paràgraf)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/ca/docs/configuration-programmatic-usage.md#carregar-les-fonts-abans-de-compondre), [`decompressWoff2`](https://postext.dev/ca/docs/configuration-pdf-output.md#proveïdor-de-fonts-al-navegador-fontsource--woff2), [`renderPageToCanvas`](https://postext.dev/ca/docs/configuration-programmatic-usage.md#renderitzar-una-pàgina-en-un-mapa-de-bits), [`renderToPdf`](https://postext.dev/ca/docs/configuration-pdf-output.md#generació-de-pdf)

**Tipus de lletra**

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

## Elaboració

### 1 · Dir dues vegades la llengua de cada passatge

El codi és [la resposta curta](https://postext.dev/ca/cookbook/cyrillic-specimen-twelve-languages.md#la-resposta-curta) de més amunt. `lang` en un bloc `:::paragraphs` declara la llengua del seu text: tria els [patrons que en parteixen els mots](https://postext.dev/ca/docs/cyrillic-layout.md#partició-de-mots-en-dotze-llengües), i el text es mesura, es pinta i s'incrusta amb les formes que la lletra guarda per a aquella llengua, i hi queda etiquetat al PDF i a l'HTML. Un tram dins d'una línia pren un aïllant, `:ltr[…]{lang=bg}`. Les columnes fan 54 mm: es pot partir a dues lletres i una línia admet fins a 20 ‰ d'espaiat.

### 2 · Un títol amb quatre dades

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

El codi, el nombre de lletres i les lletres que el rus no té viatgen al títol: `## Українська {code="uk" letters="33 буквы" special="Ґ Є І Ї"}`. El disseny els imprimeix sota un filet gruixut, i `minHeight` dona a totes les fitxes el mateix cap, de manera que els textos d'una fila comencen a la mateixa línia.

### 3 · Un mur de lletres

```js
// script.js, línies 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 dotze lletres de la coberta són els atributs `l1` a `l12` del seu títol, i el disseny construeix una caixa i un text per a cadascuna a partir d'una llista de tintes. Canviar una lletra és canviar el Markdown. Les rajoles es col·loquen des de la cantonada de la pàgina i arriben al tall.

### 4 · Formes locals, fila a fila

```js
// script.js, línies 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 mateixa cadena passa per la lletra en rus i en búlgar; en cursiva, en rus, serbi i macedoni. Source Serif 4 té els tres jocs. Uns tabuladors alineen les files, i cadascuna és un aïllant en la seva llengua. [Èmfasi i formes locals](https://postext.dev/ca/docs/cyrillic-layout.md#èmfasi-accents-i-vers) enumera les lletres que canvien.

## La recepta completa

Un sol fitxer, compost a partir de la carpeta de la recepta amb el text d'exemple i el kit comú del Receptari ja inclosos; construeix la seva pròpia pàgina. Per executar-lo, posa'l en un `<script type="module">` d'una pàgina buida o enganxa'l al tauler JS d'un pen nou de CodePen (com a mòdul). Importa postext des d'esm.sh, així que no cal instal·lar ni compilar res.

- Carpeta de la recepta: 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 = 'es'; // @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"}
Compuesto en Source Serif 4 y Source Sans 3 (SIL OFL) · Textos: DUDH, artículo 1, y versos de los autores citados, dominio público
:::
`].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 ───────────────────────────────────────────────────────────────────────
```

## Errors freqüents

- La lletra ha de tenir les formes. PT Serif no en té cap per a aquestes llengües; Vollkorn i Lora tenen les búlgares i les sèrbies. Amb una lletra que no en té, l'aïllant encara parteix i etiqueta el text, però les lletres es queden russes.
- També ha de tenir les lletres. Ә, Ғ, Ң, Ҙ, Ҷ i Ӯ són al fitxer `cyrillic-ext` de cada família, que carrega `kitCyrillicFonts`; a Literata i Spectral els en falten algunes.

## Crèdits

- Recepta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Text: 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 ([font](http://efele.net/udhr/assemblies/first_article_all.txt)), domini públic
- Text: Article 1 in Bashkir: United Nations ([font](https://www.omniglot.com/writing/bashkir.htm)), domini públic
- Text: Opening lines and sayings of Pushkin, Shevchenko, Kupala, Vazov, Vuk Karadžić, Racin, Abai, Toktogul, Tukay, Akmulla, Rudaki and Natsagdorj: The authors named, domini públic
- Text: The titles, the alphabets and the colophon: Postext Cookbook, original
- Tipus de lletra: Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)
- Codi: MIT · Contingut d'exemple: MIT

## Relacionades

- [Núm. 210 · Abai i cinc poetes de l'estepa, antologia kazakha](https://postext.dev/ca/cookbook/abai-kazakh-anthology.md): Antologia de vuit pàgines en sis llengües ciríl·liques: un llibre kazakh, un poema per llengua, glosses al peu i ornament de catifa de feltre. · Nivell 2 (Intermedi) · Poesia
- [Núm. 201 · Una novel·la grega amb partició monotònica](https://postext.dev/ca/cookbook/monotonic-greek-novel.md): El primer capítol de «Η τιμή και το χρήμα» de Theotokis en un llibre de 13,5 × 20,5 cm: patrons del grec monotònic, cometes «» i versals sense accent. · Nivell 2 (Intermedi) · Narrativa, teatre i prosa literària
- [Núm. 153 · Una pàgina retolada en sis llengües](https://postext.dev/ca/cookbook/one-page-six-languages.md): Una pàgina de còmic amb divisió i dibuixos fixos, retolada amb un guió per llengua: el locale tria la lletra; el japonès va vertical i, com l'àrab, al revés. · Nivell 3 (Avançat) · Còmics
