# Doce lenguas cirílicas en un muestrario tipográfico

> Un muestrario de cuatro páginas: un artículo en doce lenguas cirílicas, cada una partida por sus reglas y dibujada con sus formas locales.

- Versión HTML: https://postext.dev/es/cookbook/cyrillic-specimen-twelve-languages
- Receta N.º 209 · Texto y tipografía · Nivel 2 (Intermedio) · Salidas: Canvas, PDF
- Géneros: Catálogos
- Requiere postext ≥ 1.100.0, postext-pdf ≥ 1.100.0 · probada con 1.100.0, postext-pdf 1.100.0 el 2026-12-02
- Páginas: [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)
- Abrir en el Sandbox: https://postext.dev/es/sandbox#recipe=cyrillic-specimen-twelve-languages&lang=es (.postext: https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/es/cyrillic-specimen-twelve-languages.postext)
- Última actualización: 2026-12-02
- Otros idiomas: [en](https://postext.dev/en/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), [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 pocas palabras

La hoja de muestras de una fundición con el mismo artículo en doce lenguas escritas en cirílico, del ruso al mongol. Cada pasaje parte según su lengua; el búlgaro, el serbio y el macedonio enseñan las letras que dibujan de otra manera.

## Lo que vas a componer

Un muestrario de 205 × 260 mm en cuatro páginas. La cubierta es un muro de doce teselas, cada una con una letra propia de un alfabeto. Dos páginas enfrentadas reúnen doce fichas, seis lenguas eslavas a la izquierda y kazajo, kirguís, tártaro, baskir, tayiko y mongol a la derecha: el nombre, las letras especiales en bermellón, el artículo 1 de la Declaración Universal de Derechos Humanos en columnas justificadas, un verso de un autor de la lengua y el alfabeto. La última página muestra las formas locales a gran tamaño y la palabra «biblioteca» partida en las doce.

**Esta receta responde a:**

- ¿Cómo compongo varias lenguas cirílicas en un documento, cada una con sus particiones y sus formas de letra?
- ¿Cómo consigo una buena justificación y separación silábica en textos en español, francés o alemán?

## La respuesta corta

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

## Ingredientes

**Enseña**

- [Los idiomas de alfabeto cirílico como idioma del documento](https://postext.dev/es/docs/cyrillic-layout.md#empezar-un-libro-en-cirílico): locale 'ru', 'uk', 'be', 'bg', 'sr', 'mk', 'kk', 'ky', 'tt', 'ba', 'tg' o 'mn' da al libro la separación silábica, los pies, los títulos de tabla, las notas, los números en letra, los formatos de pliego y el sentido del lomo de su idioma.
- [Separación silábica e idioma del documento](https://postext.dev/es/docs/justification.md#idiomas-admitidos): Separación silábica con patrones de TeX en veintiún idiomas, el griego y los de alfabeto cirílico entre ellos, según el locale del documento, que fija también los textos de continuación de las tablas y el idioma del PDF etiquetado.
- [Fragmentos en la otra dirección](https://postext.dev/es/docs/arabic-layout.md#aislamientos): :rtl[…] y :ltr[…] aíslan un fragmento de la otra dirección dentro de una línea (un nombre de producto latino en árabe, un título árabe en una frase inglesa), con un lang opcional; los aislantes Unicode U+2066–2069 escritos en el texto funcionan igual.

**También usa**

- [Palabras que no se separan a final de línea](https://postext.dev/es/docs/cyrillic-layout.md#palabras-que-van-juntas)
- [Tipografía del texto](https://postext.dev/es/docs/configuration-text.md#texto-base)
- [Estilos de párrafo](https://postext.dev/es/docs/configuration-styles.md#estilos-de-párrafo)
- [Estilos de carácter](https://postext.dev/es/docs/document-format-inline.md#estilos-de-carácter)
- [Tabuladores y rellenos](https://postext.dev/es/docs/configuration-text.md#tabulaciones)
- [Aperturas diseñadas](https://postext.dev/es/docs/configuration-headings.md#apertura-a-toda-página-y-diseño-avanzado)
- [Estilos de título](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)
- [Atributos de título](https://postext.dev/es/docs/document-format.md#atributos-de-encabezado)
- [Textos, filetes y cajas en los diseños de página](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies)
- [Bandas a sangre y pestañas](https://postext.dev/es/docs/configuration-headers-footers.md#colocación-de-elementos)
- [Cubiertas, portadas y colofones](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)
- [Márgenes simétricos](https://postext.dev/es/docs/configuration-page-layout.md#márgenes-simétricos-espejo)
- [Color del papel](https://postext.dev/es/docs/configuration-page-layout.md#página)
- [Paleta de color semántica](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores)
- [Exportación a PDF](https://postext.dev/es/docs/configuration-pdf-output.md#generación-de-pdf)
- [Fuentes incrustadas en el PDF](https://postext.dev/es/docs/configuration-pdf-output.md#por-qué-un-proveedor-de-fuentes)
- [Columnas en un recuadro o en el texto](https://postext.dev/es/docs/document-format-directives.md#columns)
- [Filete de columna](https://postext.dev/es/docs/configuration-page-layout.md#filete-de-columna)
- [Cabeceras por sección](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)

**La configuración de un vistazo**

- [`bodyText`](https://postext.dev/es/docs/configuration-text.md#texto-base), [`characterStyles`](https://postext.dev/es/docs/configuration-styles.md#estilos-de-carácter), [`colorPalette`](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores), [`footer`](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies), [`header`](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies), [`headingStyles`](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado), [`headings`](https://postext.dev/es/docs/configuration-headings.md#encabezados), [`layout`](https://postext.dev/es/docs/configuration-page-layout.md#disposición), [`locale`](https://postext.dev/es/docs/configuration-language.md#separación-silábica), [`page`](https://postext.dev/es/docs/configuration-page-layout.md#página), [`paragraphStyles`](https://postext.dev/es/docs/configuration-styles.md#estilos-de-párrafo)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/es/docs/configuration-programmatic-usage.md#cargar-las-fuentes-antes-de-componer), [`decompressWoff2`](https://postext.dev/es/docs/configuration-pdf-output.md#proveedor-de-fuentes-en-el-navegador-fontsource--woff2), [`renderPageToCanvas`](https://postext.dev/es/docs/configuration-programmatic-usage.md#renderizar-una-página-como-mapa-de-bits), [`renderToPdf`](https://postext.dev/es/docs/configuration-pdf-output.md#generación-de-pdf)

**Tipografías**

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

## Elaboración

### 1 · Nombrar dos veces la lengua de cada pasaje

El código es [la respuesta corta](https://postext.dev/es/cookbook/cyrillic-specimen-twelve-languages.md#la-respuesta-corta) de arriba. `lang` en un bloque `:::paragraphs` declara la lengua de su texto: elige los [patrones que parten sus palabras](https://postext.dev/es/docs/cyrillic-layout.md#separación-silábica-en-doce-idiomas), y el texto se mide, se pinta y se incrusta con las formas que la letra guarda para esa lengua, y queda etiquetado con ella en el PDF y el HTML. Un tramo dentro de una línea toma un aislante, `:ltr[…]{lang=bg}`. Las columnas miden 54 mm: se puede partir a dos letras y una línea admite hasta 20 ‰ de espaciado.

### 2 · Un título con cuatro datos

```js
// script.js, líneas 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 código, el número de letras y las letras que el ruso no tiene viajan en el título: `## Українська {code="uk" letters="33 буквы" special="Ґ Є І Ї"}`. El diseño los imprime bajo un filete grueso, y `minHeight` da a todas las fichas la misma cabeza, de modo que los textos de una fila empiezan en la misma línea.

### 3 · Un muro de letras

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

Las doce letras de la cubierta son los atributos `l1` a `l12` de su título, y el diseño construye una caja y un texto para cada una a partir de una lista de tintas. Cambiar una letra es cambiar el Markdown. Las teselas se colocan desde la esquina de la página y llegan al corte.

### 4 · Formas locales, fila a fila

```js
// script.js, líneas 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 misma cadena pasa por la letra en ruso y en búlgaro; en cursiva, en ruso, serbio y macedonio. Source Serif 4 tiene los tres juegos. Unos tabuladores alinean las filas, y cada una es un aislante en su lengua. [Énfasis y formas locales](https://postext.dev/es/docs/cyrillic-layout.md#énfasis-acentos-y-verso) enumera las letras que cambian.

## La receta completa

Un solo archivo, compuesto a partir de la carpeta de la receta con el texto de ejemplo y el kit común del Recetario ya incluidos; construye su propia página. Para ejecutarlo, ponlo en un `<script type="module">` de una página vacía o pégalo en el panel JS de un pen nuevo de CodePen (como módulo). Importa postext desde esm.sh, así que no hay nada que instalar ni compilar.

- Carpeta de la receta: 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 ───────────────────────────────────────────────────────────────────────
```

## Errores frecuentes

- La letra tiene que tener las formas. PT Serif no tiene ninguna para estas lenguas; Vollkorn y Lora tienen las búlgaras y las serbias. Con una letra sin ellas, el aislante sigue partiendo y etiquetando el texto, pero las letras se quedan rusas.
- También tiene que tener las letras. Ә, Ғ, Ң, Ҙ, Ҷ y Ӯ están en el fichero `cyrillic-ext` de cada familia, que carga `kitCyrillicFonts`; a Literata y Spectral les faltan algunas.

## Créditos

- Receta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Texto: Artículo 1 de la Declaración Universal de Derechos Humanos en once lenguas, de los textos del proyecto UDHR in XML, con cuatro erratas de los ficheros kazajo, kirguís y tártaro corregidas: United Nations ([fuente](http://efele.net/udhr/assemblies/first_article_all.txt)), dominio público
- Texto: Artículo 1 en baskir: United Nations ([fuente](https://www.omniglot.com/writing/bashkir.htm)), dominio público
- Texto: Primeros versos y dichos de Pushkin, Shevchenko, Kupala, Vázov, Vuk Karadžić, Racin, Abai, Toktogul, Tukái, Akmulla, Rudaki y Natsagdorj: The authors named, dominio público
- Texto: Los títulos, los alfabetos y el colofón: Postext Cookbook, original
- Tipografías: Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)
- Código: MIT · Contenido de ejemplo: MIT

## Relacionadas

- [N.º 210 · Abai y cinco poetas de la estepa, antología kazaja](https://postext.dev/es/cookbook/abai-kazakh-anthology.md): Antología de ocho páginas en seis lenguas cirílicas: un libro kazajo, un poema por lengua, glosas al pie y ornamento de alfombra de fieltro. · Nivel 2 (Intermedio) · Poesía
- [N.º 201 · Una novela griega con partición monotónica](https://postext.dev/es/cookbook/monotonic-greek-novel.md): El primer capítulo de «Η τιμή και το χρήμα» de Theotokis en un libro de 13,5 × 20,5 cm: patrones del griego monotónico, comillas «» y versales sin tilde. · Nivel 2 (Intermedio) · Narrativa, teatro y prosa literaria
- [N.º 153 · Una página rotulada en seis idiomas](https://postext.dev/es/cookbook/one-page-six-languages.md): Una página de cómic con división y dibujos fijos, rotulada por idioma: el locale elige la letra; el japonés va en vertical y, como el árabe, se lee al revés. · Nivel 3 (Avanzado) · Cómics
