# Doze idiomas cirílicos em um mostruário tipográfico

> Um mostruário de quatro páginas: um artigo em doze idiomas cirílicos, cada um dividido por suas regras e com suas formas locais.

- Versão HTML: https://postext.dev/pt/cookbook/cyrillic-specimen-twelve-languages
- Receita Nº 209 · Tipo e texto · Nível 2 (Intermediário) · Saídas: Canvas, PDF
- Gêneros: Catálogos
- Requer postext ≥ 1.100.0, postext-pdf ≥ 1.100.0 · testada com 1.100.0, postext-pdf 1.100.0 em 2026-12-02
- Páginas: [1](https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/en/p01.webp?v=5029f9ce), [2](https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/en/p02.webp?v=5029f9ce), [3](https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/en/p03.webp?v=5029f9ce), [4](https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/en/p04.webp?v=5029f9ce)
- Abrir no Sandbox: https://postext.dev/pt/sandbox#recipe=cyrillic-specimen-twelve-languages&lang=en (.postext: https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/en/cyrillic-specimen-twelve-languages.postext)
- Última atualização: 2026-12-02
- Outros idiomas: [en](https://postext.dev/en/cookbook/cyrillic-specimen-twelve-languages.md), [es](https://postext.dev/es/cookbook/cyrillic-specimen-twelve-languages.md), [ca](https://postext.dev/ca/cookbook/cyrillic-specimen-twelve-languages.md), [de](https://postext.dev/de/cookbook/cyrillic-specimen-twelve-languages.md), [el](https://postext.dev/el/cookbook/cyrillic-specimen-twelve-languages.md), [fr](https://postext.dev/fr/cookbook/cyrillic-specimen-twelve-languages.md), [it](https://postext.dev/it/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)

## Em poucas palavras

A folha de amostras de uma fundição com o mesmo artigo em doze idiomas escritos em cirílico, do russo ao mongol. Cada trecho divide as palavras segundo o seu idioma; búlgaro, sérvio e macedônio mostram as letras que desenham de outro jeito.

## O que você vai compor

Um mostruário de 205 × 260 mm em quatro páginas. A capa é um muro de doze ladrilhos, cada um com uma letra própria de um alfabeto. Duas páginas lado a lado reúnem doze fichas, seis idiomas eslavos à esquerda e cazaque, quirguiz, tártaro, basquir, tadjique e mongol à direita: o nome, as letras especiais em vermelhão, o artigo 1 da Declaração Universal dos Direitos Humanos em colunas justificadas, um verso de um autor do idioma e o alfabeto. A última página mostra as formas locais em corpo grande e a palavra “biblioteca” dividida nos doze.

**Esta receita responde a:**

- Como componho vários idiomas cirílicos num documento, cada um com sua hifenização e suas formas?
- Como consigo boa justificação e hifenização em textos em espanhol, francês ou alemão?

## A resposta curta

```js
// script.js, linhas 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

**Ensina**

- [Idiomas de alfabeto cirílico como idioma do documento](https://postext.dev/pt/docs/cyrillic-layout.md#como-começar-um-livro-em-cirílico): locale 'ru', 'uk', 'be', 'bg', 'sr', 'mk', 'kk', 'ky', 'tt', 'ba', 'tg' ou 'mn' dá ao livro a hifenização, as legendas, os títulos de tabela, as notas, os números por extenso, os formatos de folha e o sentido da lombada do seu idioma.
- [Hifenização e idioma do documento](https://postext.dev/pt/docs/justification.md#idiomas-compatíveis): Hifenização com padrões do TeX em vinte e um idiomas, entre eles o grego e os de alfabeto cirílico, escolhida pelo locale do documento, que também define os textos de continuação das tabelas e o idioma do PDF com tags.
- [Trechos na outra direção](https://postext.dev/pt/docs/arabic-layout.md#isolamentos): :rtl[…] e :ltr[…] isolam um trecho da outra direção dentro de uma linha (um nome de produto latino em árabe, um título árabe em uma frase em inglês), com um lang opcional; os isolantes Unicode U+2066–2069 digitados no texto funcionam do mesmo jeito.

**Também usa**

- [Palavras que não se separam no fim da linha](https://postext.dev/pt/docs/cyrillic-layout.md#palavras-que-ficam-juntas)
- [Tipografia do texto](https://postext.dev/pt/docs/configuration-text.md#texto-do-corpo)
- [Estilos de parágrafo](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-parágrafo)
- [Estilos de caractere](https://postext.dev/pt/docs/document-format-inline.md#estilos-de-caractere)
- [Paradas de tabulação e pontilhados](https://postext.dev/pt/docs/configuration-text.md#paradas-de-tabulação)
- [Aberturas desenhadas](https://postext.dev/pt/docs/configuration-headings.md#largura-e-design-avançado)
- [Estilos de título](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título)
- [Atributos de título](https://postext.dev/pt/docs/document-format.md#atributos-de-título)
- [Textos, fios e caixas nos designs de página](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés)
- [Faixas sangradas e guias laterais](https://postext.dev/pt/docs/configuration-headers-footers.md#posicionamento-de-elementos)
- [Capas, folhas de rosto e colofões](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título)
- [Margens espelhadas](https://postext.dev/pt/docs/configuration-page-layout.md#margens-espelhadas)
- [Cor do papel](https://postext.dev/pt/docs/configuration-page-layout.md#página)
- [Paleta de cores semântica](https://postext.dev/pt/docs/configuration-fonts-colors-viewers.md#paleta-de-cores)
- [Exportação para PDF](https://postext.dev/pt/docs/configuration-pdf-output.md#geração-de-pdf)
- [Fontes incorporadas ao PDF](https://postext.dev/pt/docs/configuration-pdf-output.md#por-que-um-provedor-de-fontes)
- [Colunas num boxe ou no texto](https://postext.dev/pt/docs/document-format-directives.md#columns)
- [Fio entre colunas](https://postext.dev/pt/docs/configuration-page-layout.md#fio-entre-colunas)
- [Cabeços por seção](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título)

**A configuração em resumo**

- [`bodyText`](https://postext.dev/pt/docs/configuration-text.md#texto-do-corpo), [`characterStyles`](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-caractere), [`colorPalette`](https://postext.dev/pt/docs/configuration-fonts-colors-viewers.md#paleta-de-cores), [`footer`](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés), [`header`](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés), [`headingStyles`](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título), [`headings`](https://postext.dev/pt/docs/configuration-headings.md#títulos), [`layout`](https://postext.dev/pt/docs/configuration-page-layout.md#diagramação), [`locale`](https://postext.dev/pt/docs/configuration-language.md#hifenização), [`page`](https://postext.dev/pt/docs/configuration-page-layout.md#página), [`paragraphStyles`](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-parágrafo)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/pt/docs/configuration-programmatic-usage.md#carregar-as-fontes-antes-da-diagramação), [`decompressWoff2`](https://postext.dev/pt/docs/configuration-pdf-output.md#provedor-de-fontes-no-navegador-fontsource--woff2), [`renderPageToCanvas`](https://postext.dev/pt/docs/configuration-programmatic-usage.md#renderizar-uma-página-como-bitmap), [`renderToPdf`](https://postext.dev/pt/docs/configuration-pdf-output.md#geração-de-pdf)

**Tipos**

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

## Preparo

### 1 · Nomear duas vezes o idioma de cada trecho

O código é [a resposta curta](https://postext.dev/pt/cookbook/cyrillic-specimen-twelve-languages.md#a-resposta-curta) acima. `lang` em um bloco `:::paragraphs` declara o idioma do seu texto: escolhe os [padrões que dividem suas palavras](https://postext.dev/pt/docs/cyrillic-layout.md#hifenização-em-doze-idiomas), e o texto é medido, pintado e incorporado com as formas que a fonte guarda para esse idioma, e fica marcado com ele no PDF e no HTML. Um trecho dentro de uma linha usa um isolado, `:ltr[…]{lang=bg}`. As colunas têm 54 mm: divide-se a partir de duas letras e uma linha aceita até 20 ‰ de espacejamento.

### 2 · Um título, quatro dados

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

O código, o número de letras e as letras que o russo não tem viajam no título: `## Українська {code="uk" letters="33 буквы" special="Ґ Є І Ї"}`. O desenho os imprime sob um fio grosso, e `minHeight` dá a todas as fichas a mesma cabeça, de modo que os textos de uma fileira começam na mesma linha.

### 3 · Um muro de letras

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

As doze letras da capa são os atributos `l1` a `l12` do seu título, e o desenho monta uma caixa e um texto para cada uma a partir de uma lista de tintas. Trocar uma letra é trocar o Markdown. Os ladrilhos partem do canto da página e chegam ao corte.

### 4 · Formas locais, linha a linha

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

A mesma sequência passa pela fonte em russo e depois em búlgaro; em itálico, em russo, sérvio e macedônio. Source Serif 4 tem os três conjuntos. Tabulações alinham as linhas, e cada uma é um isolado em seu idioma. [Ênfase e formas locais](https://postext.dev/pt/docs/cyrillic-layout.md#ênfase-acentos-e-verso) lista as letras que mudam.

## A receita completa

Um único arquivo, composto a partir da pasta da receita com o texto de exemplo e o kit comum das Receitas já incluídos; ele monta a própria página. Para executá-lo, coloque-o em um `<script type="module">` de uma página vazia ou cole-o no painel JS de um pen novo do CodePen (como módulo). Ele importa o postext do esm.sh, então não há nada para instalar nem compilar.

- Pasta da receita: https://github.com/drnachio/postext/tree/main/cookbook/cyrillic-specimen-twelve-languages

### script.js

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

const LANG = 'en'; // @lang: the language of the colophon ('en' | 'es' | 'ru')
const RECIPE = 'cyrillic-specimen-twelve-languages';

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ─── Kit ── helpers shared by every Cookbook recipe · postext.dev/cookbook ─────

// ─── Kit · core v1 ── the same in every recipe · postext.dev/cookbook
function mm(value) { return { value, unit: 'mm' }; }
function pt(value) { return { value, unit: 'pt' }; }
function em(value) { return { value, unit: 'em' }; }
/** The sample language's string: t({ en: 'Figure', es: 'Figura' }). */
function t(strings) { return strings[LANG] ?? Object.values(strings)[0]; }
/** A file in this recipe's assets folder, served from the Postext repo by jsDelivr. */
function asset(file) { return `https://cdn.jsdelivr.net/gh/drnachio/postext@main/cookbook/${RECIPE}/assets/${file}`; }

// ─── Kit · fonts v3 ── the same in every recipe · postext.dev/cookbook
// Postext loads the faces a config asks for before layout and asks the kit
// for Fontsource's files, the ones the PDF embeds too.

/** buildDocumentWithFonts' options: the resolver, and FONTS' faces loaded
 *  with the config's. FONTS = { 'Family Name': ['400', '400i', '700'] }. */
function kitFonts(FONTS = {}) {
  const faces = Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) =>
    ({ family, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' })));
  return { resolve: fontsourceResolver, faces };
}

/** A face's files with their ranges: latin, then latin-ext and greek when
 *  `text` needs them (kitSubsetsFor). Null for a face Fontsource lacks. */
async function fontsourceResolver(family, weight, style, { text = '' } = {}) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  if (meta && !(await fontsourceWeights(family, style)).includes(weight)) return null;
  kitStatus('Loading fonts…');
  const at = await fontsourceAt(id);
  return ['latin', ...kitSubsetsFor(text, meta)].map((subset) => ({
    source: `${at}files/${id}-${subset}-${weight}-${style}.woff2`,
    unicodeRange: kitRanges()[subset],
  }));
}

/** Each file's unicode-range (a function: the kit runs after the pen's code). */
function kitRanges() {
  return {
    latin: 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,'
      + 'U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD',
    'latin-ext': 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,'
      + 'U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF',
    greek: 'U+0370-03FF',
  };
}

/** For the cjk, arabic and comics blocks: loads `faces` (as FONTS) for the
 *  sample `text`; `optional` skips a face Fontsource lacks. Files are added in
 *  the order asked, the last winning a shared character. Resolves to the count. */
async function loadFonts(faces, text = '', { optional = false } = {}) {
  kitStatus('Loading fonts…');
  const ranges = kitRanges();
  const jobs = [];
  for (const [family, specs] of Object.entries(faces)) {
    const id = fontsourceId(family);
    const todo = [...new Set(specs)].map((spec) => [parseInt(spec, 10), spec.endsWith('i') ? 'italic' : 'normal'])
      .filter(([weight, style]) => !hasFace(family, weight, style)); // before any await
    const at = fontsourceAt(id);
    const meta = optional || /[^\0-ÿ]/u.test(text) ? await fontsourceMeta(family) : null;
    const subsets = ['latin', ...kitSubsetsFor(text, meta)];
    for (const [weight, style] of todo) {
      if (optional && !(meta && (await fontsourceWeights(family, style)).includes(weight))) continue;
      for (const subset of subsets) {
        const url = `${await at}files/${id}-${subset}-${weight}-${style}.woff2`;
        const face = new FontFace(family, `url(${url}) format('woff2')`,
          { weight: String(weight), style, unicodeRange: ranges[subset] });
        jobs.push(face.load().catch(() => {
          if (subset === 'latin' && !optional) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
        }));
      }
    }
  }
  const ready = await Promise.all(jobs).catch((error) => { kitFail(error); throw error; });
  return ready.filter((face) => face && document.fonts.add(face)).length;
}

/** A loaded FontFace covers this face (fonts.check() says yes to any family). */
function hasFace(family, weight, style) {
  for (const face of document.fonts) {
    if (face.status !== 'loaded' || face.style !== style) continue;
    if (face.family.replace(/^["']|["']$/g, '') !== family) continue;
    const [low, high = low] = face.weight.split(' ').map(Number);
    if (weight >= low && weight <= high) return true;
  }
  return false;
}

/** The files beyond latin `text` needs that `meta`'s family ships. */
function kitSubsetsFor(text, meta) {
  return [[/[Ā-˿ᴀ-ᶿḀ-ỿ†ℓⱠ-Ɀ꜠-ꟿ]/u, 'latin-ext'], [/[Ͱ-Ͽ]/u, 'greek']]
    .filter(([re, x]) => re.test(text) && meta?.subsets?.includes(x)).map(([, x]) => x);
}

/** Fontsource's id for a family: 'Source Serif 4' → 'source-serif-4'. */
function fontsourceId(family) { return family.toLowerCase().replace(/\s+/g, '-'); }

/** A package's folder at the one version @5 names now (#766). */
function fontsourceAt(id, u = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@`) {
  return (fontsourceAt.c ??= {})[id] ??= fetch(u + '5/package.json').then((r) => r.json())
    .then((p) => p.version || 5, () => 5).then((v) => `${u}${v}/`);
}

/** The family's Fontsource metadata (weights, styles, subsets), or null. */
function fontsourceMeta(family, id = fontsourceId(family)) {
  return (fontsourceMeta.c ??= {})[id] ??= fetch(`https://api.fontsource.org/v1/fonts/${id}`)
    .then((res) => (res.ok ? res.json() : null), () => null);
}

/** The weights the package ships in `style`: the API pairs none (no Libre
 *  Caslon 700 italic file), so italics are read from latin-italic.css. */
function fontsourceWeights(family, style, id = fontsourceId(family)) {
  return (fontsourceWeights.c ??= {})[id + style] ??= fontsourceMeta(family).then(async (m) => {
    if (!m?.styles.includes(style)) return m ? [] : [400, 700];
    const css = style === 'italic' ? await fetch(`${await fontsourceAt(id)}latin-italic.css`).then((r) => (r.ok ? r.text() : ''), () => '') : '';
    const w = [...css.matchAll(/weight: (\d+)/g)].map((x) => +x[1]);
    return w.length ? w : m.weights;
  });
}

// ─── Kit · viewer v2 ── the same in every recipe · postext.dev/cookbook
/** The pages as spreads on a dark desk, page 1 alone, then verso | recto,
 *  each painted when it scrolls near. Other options go to renderPageToCanvas. */
function showPages(docs, { title, width = 460, ...render } = {}) {
  const root = viewer(title);
  const pages = [docs].flat().flatMap((doc) =>
    doc.pages.map((page) => ({ doc, page, n: (doc.pageIndexOffset ?? 0) + page.index })));
  const spreads = [];
  let verso = null;
  for (const p of pages) {
    if (p.n % 2 === 1) { if (verso) spreads.push([verso, null]); verso = p; }
    else { spreads.push([verso, p]); verso = null; }
  }
  if (verso) spreads.push([verso, null]);
  const density = Math.min(window.devicePixelRatio || 1, 2);
  showPages.painter?.disconnect();
  const painter = new IntersectionObserver((entries) => {
    for (const { isIntersecting, target } of entries) {
      if (!isIntersecting) continue;
      painter.unobserve(target);
      const { doc, page } = target.postext;
      renderPageToCanvas(page, doc, target, { ...render, scale: (width * density) / page.width });
    }
  }, { rootMargin: '800px' });
  showPages.painter = painter;
  root.replaceChildren(...spreads.map((pair) => {
    const spread = document.createElement('div');
    spread.className = 'pt-spread';
    for (const p of pair) {
      const figure = document.createElement('figure');
      if (p) {
        const label = p.page.pageLabel || String(p.n + 1);
        const canvas = document.createElement('canvas');
        canvas.postext = p;
        canvas.style.aspectRatio = `${p.page.width} / ${p.page.height}`;
        canvas.setAttribute('role', 'img');
        canvas.setAttribute('aria-label', `Page ${label}`);
        const folio = document.createElement('figcaption');
        folio.textContent = label;
        figure.append(canvas, folio);
        painter.observe(canvas);
      } else figure.className = 'pt-blank';
      spread.append(figure);
    }
    return spread;
  }));
  kitStatus(`${pages.length} ${pages.length === 1 ? 'page' : 'pages'}`);
  document.documentElement.dataset.postext = 'ready';
  return pages.length;
}

/** The desk, the bar and the error reporting, created once. */
function viewer(title) {
  if (!document.getElementById('pt-kit')) {
    document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit">
      :root { color-scheme: dark; }
      body { margin: 0; background: #0e1014; color: #b9bcc4; font: 13px/1.45 system-ui, sans-serif; }
      #pt-bar { position: sticky; top: 0; z-index: 1; display: flex; flex-wrap: wrap; align-items: center;
        gap: 6px 16px; padding: 10px 16px; background: rgb(14 16 20 / .92); backdrop-filter: blur(6px);
        border-bottom: 1px solid #23262d; }
      #pt-bar strong { color: #f4f1ea; font-weight: 600; }
      #pt-actions { display: flex; gap: 12px; margin-left: auto; }
      #pt-actions a, #pt-actions button { color: #d8a21a; font: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
      #pages { display: grid; justify-items: center; gap: 48px; padding: 32px 16px 72px; }
      .pt-spread { display: flex; }
      .pt-spread figure { margin: 0; width: min(460px, 44vw); }
      .pt-spread canvas { display: block; width: 100%; background: #fff;
        box-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figure:first-child canvas { box-shadow: inset -14px 0 14px -14px rgb(0 0 0 / .18), 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figcaption { margin-top: 10px; text-align: center; font: 600 10px/1 system-ui, sans-serif;
        letter-spacing: .18em; text-transform: uppercase; color: #6c7079; }
      .pt-blank { visibility: hidden; }
      @media (max-width: 760px) {
        .pt-spread { flex-direction: column; gap: 32px; }
        .pt-spread figure { width: min(460px, 92vw); }
        .pt-blank { display: none; }
      }
    </style>`);
    document.body.insertAdjacentHTML('afterbegin',
      '<header id="pt-bar"><strong id="pt-title"></strong><span id="pt-status" role="status"></span><span id="pt-actions"></span></header>');
    document.getElementById('pt-title').textContent = document.title || 'Postext';
    addEventListener('error', (event) => kitFail(event.error ?? event.message));
    addEventListener('unhandledrejection', (event) => kitFail(event.reason));
  }
  if (title) document.getElementById('pt-title').textContent = title;
  return document.getElementById('pages')
    ?? document.body.appendChild(Object.assign(document.createElement('main'), { id: 'pages' }));
}

function kitStatus(text) {
  viewer();
  document.getElementById('pt-status').textContent = text;
}

function kitFail(error) {
  document.documentElement.dataset.postext = 'error';
  kitStatus(`Error: ${error?.message ?? error}`);
}

// ─── Kit · pdf v3 ── the same in every recipe that exports a PDF
/** The Fontsource files the screen used, as TrueType, with their range and
 *  place: the nearest weight the family ships in that style, upright with no italic;
 *  latin, then what its letters need (kitSubsetsFor). */
async function fontsourceProvider(family, weight, style, request) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  const s = style === 'italic' && meta && !meta.styles.includes('italic') ? 'normal' : style;
  const shipped = meta ? await fontsourceWeights(family, s) : [];
  const weights = shipped.length ? shipped : [400, 700];
  const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const text = String.fromCodePoint(...(request?.codePoints ?? []));
  const files = await Promise.all(['latin', ...kitSubsetsFor(text, meta)].map(async (subset, order) => {
    const res = await fetch(`${await fontsourceAt(id)}files/${id}-${subset}-${w}-${s}.woff2`);
    if (!res.ok) throw new Error(`Fontsource has no ${family} ${w} ${s} ${subset}`);
    return Object.assign(await decompressWoff2(new Uint8Array(await res.arrayBuffer())),
      { unicodeRange: kitRanges()[subset], order });
  }));
  return files.length === 1 ? files[0] : files;
}

/** A "Build the PDF" button; then "Open the PDF" (a new tab: CodePen's frame
 *  shows no PDFs) and a download link. */
function offerPdf(makePdf, filename) {
  viewer();
  const button = Object.assign(document.createElement('button'), { type: 'button', textContent: 'Build the PDF' });
  button.dataset.postextPdf = filename;
  button.addEventListener('click', async () => {
    button.disabled = true;
    button.textContent = 'Building the PDF…';
    try {
      const bytes = await makePdf();
      const url = URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }));
      const size = `${Math.max(1, Math.round(bytes.length / 1024))} KB`;
      button.replaceWith(
        Object.assign(document.createElement('a'), { href: url, target: '_blank', rel: 'noopener', textContent: 'Open the PDF ↗' }),
        Object.assign(document.createElement('a'), { href: url, download: filename, textContent: `Download ${filename} · ${size}` }));
    } catch (error) {
      button.disabled = false;
      button.textContent = 'Build the PDF';
      kitFail(error);
    }
  });
  document.getElementById('pt-actions').append(button);
}

// ─── Kit · cyrillic v1 ── Cyrillic faces · postext.dev/cookbook
// Fontsource ships a family's Cyrillic letters in files of their own:
// `cyrillic` holds the Russian, Ukrainian, Belarusian, Bulgarian, Serbian and
// Macedonian alphabets, the stress mark and №; `cyrillic-ext` the letters of
// Kazakh, Kyrgyz, Tatar, Bashkir, Tajik and Mongolian. The fonts block loads
// latin, latin-ext and greek; this one adds these.

/** The unicode-ranges Fontsource's stylesheets declare the two files with (a
 *  function: the kit runs after the pen's code). */
function cyrillicRanges() {
  return {
    cyrillic: 'U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116',
    'cyrillic-ext': 'U+0460-052F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F',
  };
}

/** The Cyrillic files `text` needs that `meta`'s family ships. */
function cyrillicSubsetsFor(text, meta) {
  return [[/[́Ѐ-џҐґҰұ№]/u, 'cyrillic'],
    [/[Ѡ-ҏҒ-үҲ-ԯᲀ-ᲊ₴ⷠ-ⷿꙀ-ꚟ]/u, 'cyrillic-ext']]
    .filter(([re, x]) => re.test(text) && meta?.subsets?.includes(x)).map(([, x]) => x);
}

/** kitFonts(FONTS) for a pen in Cyrillic: the fonts block's files, then the
 *  Cyrillic ones `text` needs. A family without them fails, so that no page
 *  is set in a fallback face unseen; list in `latin` the families that set
 *  Latin text alone. */
function kitCyrillicFonts(FONTS = {}, latin = []) {
  return { ...kitFonts(FONTS), resolve: async (family, weight, style, request = {}) => {
    const files = await fontsourceResolver(family, weight, style, request);
    const meta = await fontsourceMeta(family);
    if (!files || latin.includes(family)) return files;
    if (/\p{Script=Cyrillic}/u.test(request.text ?? '') && !meta?.subsets?.includes('cyrillic')) {
      throw new Error(`${family} has no Cyrillic letters at Fontsource`);
    }
    const at = await fontsourceAt(fontsourceId(family));
    return [...files, ...cyrillicSubsetsFor(request.text ?? '', meta).map((subset) => ({
      source: `${at}files/${fontsourceId(family)}-${subset}-${weight}-${style}.woff2`,
      unicodeRange: cyrillicRanges()[subset],
    }))];
  } };
}

/** fontsourceProvider (the pdf block) with the Cyrillic files a face's
 *  letters need, after its others, as the screen added them. */
async function cyrillicPdfProvider(family, weight, style, request) {
  const first = await fontsourceProvider(family, weight, style, request);
  const files = Array.isArray(first) ? first : [first];
  const meta = await fontsourceMeta(family);
  const text = String.fromCodePoint(...(request?.codePoints ?? []));
  const subsets = cyrillicSubsetsFor(text, meta);
  if (!subsets.length) return first;
  const s = style === 'italic' && !meta.styles.includes('italic') ? 'normal' : style;
  const w = (await fontsourceWeights(family, s)).reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const at = await fontsourceAt(fontsourceId(family));
  const more = await Promise.all(subsets.map(async (subset, i) => {
    const url = `${at}files/${fontsourceId(family)}-${subset}-${w}-${s}.woff2`;
    const res = await fetch(url);
    if (!res.ok) throw new Error(`Fontsource file ${url} (${res.status})`);
    return Object.assign(await decompressWoff2(new Uint8Array(await res.arrayBuffer())),
      { unicodeRange: cyrillicRanges()[subset], order: files.length + i });
  }));
  return [...files, ...more];
}

// ─── /Kit ───────────────────────────────────────────────────────────────────────
```

## Erros comuns

- A fonte precisa ter as formas. PT Serif não tem nenhuma para esses idiomas; Vollkorn e Lora têm as búlgaras e as sérvias. Sem elas, o isolado ainda divide e marca o texto, mas as letras continuam russas.
- Também precisa ter as letras. Ә, Ғ, Ң, Ҙ, Ҷ e Ӯ estão no arquivo `cyrillic-ext` da família, que `kitCyrillicFonts` carrega; faltam algumas em Literata e Spectral.

## Créditos

- Receita: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Texto: 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 ([fonte](http://efele.net/udhr/assemblies/first_article_all.txt)), domínio público
- Texto: Article 1 in Bashkir: United Nations ([fonte](https://www.omniglot.com/writing/bashkir.htm)), domínio público
- Texto: Opening lines and sayings of Pushkin, Shevchenko, Kupala, Vazov, Vuk Karadžić, Racin, Abai, Toktogul, Tukay, Akmulla, Rudaki and Natsagdorj: The authors named, domínio público
- Texto: The titles, the alphabets and the colophon: Postext Cookbook, original
- Tipos: Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)
- Código: MIT · Conteúdo de exemplo: MIT

## Relacionadas

- [Nº 210 · Abai e cinco poetas da estepe, antologia cazaque](https://postext.dev/pt/cookbook/abai-kazakh-anthology.md): Antologia de oito páginas em seis idiomas cirílicos: um livro cazaque, um poema por idioma, glosas no rodapé e ornamento de tapete de feltro. · Nível 2 (Intermediário) · Poesia
- [Nº 201 · Um romance grego com hifenização monotônica](https://postext.dev/pt/cookbook/monotonic-greek-novel.md): O primeiro capítulo de «Η τιμή και το χρήμα», de Theotokis, num livro de 13,5 × 20,5 cm: padrões do grego monotônico, aspas «» e versais sem acento. · Nível 2 (Intermediário) · Ficção, teatro e prosa literária
- [Nº 153 · Uma página letreirada em seis idiomas](https://postext.dev/pt/cookbook/one-page-six-languages.md): Página de quadrinhos com divisão e desenhos fixos, letreirada por idioma: o locale escolhe a fonte; o japonês é vertical e, como o árabe, parte da direita. · Nível 3 (Avançado) · Quadrinhos
