# Poemas ucranianos em edição de presente

> Três poemas de Shevchenko em 130 × 200 mm: estrofes centradas, notas com asterisco por página, datas embaixo e faixas de ponto-cruz em código.

- Versão HTML: https://postext.dev/pt/cookbook/kobzar-ukrainian-poems
- Receita Nº 208 · Tipo e texto · Nível 2 (Intermediário) · Saídas: Canvas, PDF
- Gêneros: Poesia
- 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/kobzar-ukrainian-poems/en/p01.webp?v=1e5a4dab), [2](https://postext.dev/cookbook/kobzar-ukrainian-poems/en/p02.webp?v=1e5a4dab), [3](https://postext.dev/cookbook/kobzar-ukrainian-poems/en/p03.webp?v=1e5a4dab), [4](https://postext.dev/cookbook/kobzar-ukrainian-poems/en/p04.webp?v=1e5a4dab), [5](https://postext.dev/cookbook/kobzar-ukrainian-poems/en/p05.webp?v=1e5a4dab), [6](https://postext.dev/cookbook/kobzar-ukrainian-poems/en/p06.webp?v=1e5a4dab)
- PDF: https://postext.dev/cookbook/kobzar-ukrainian-poems/en/kobzar-ukrainian-poems.pdf?v=1e5a4dab
- Abrir no Sandbox: https://postext.dev/pt/sandbox#recipe=kobzar-ukrainian-poems&lang=en (.postext: https://postext.dev/cookbook/kobzar-ukrainian-poems/en/kobzar-ukrainian-poems.postext)
- Última atualização: 2026-12-02
- Outros idiomas: [en](https://postext.dev/en/cookbook/kobzar-ukrainian-poems.md), [es](https://postext.dev/es/cookbook/kobzar-ukrainian-poems.md), [ca](https://postext.dev/ca/cookbook/kobzar-ukrainian-poems.md), [de](https://postext.dev/de/cookbook/kobzar-ukrainian-poems.md), [el](https://postext.dev/el/cookbook/kobzar-ukrainian-poems.md), [fr](https://postext.dev/fr/cookbook/kobzar-ukrainian-poems.md), [it](https://postext.dev/it/cookbook/kobzar-ukrainian-poems.md), [ru](https://postext.dev/ru/cookbook/kobzar-ukrainian-poems.md), [zh](https://postext.dev/zh/cookbook/kobzar-ukrainian-poems.md), [ja](https://postext.dev/ja/cookbook/kobzar-ukrainian-poems.md), [ar](https://postext.dev/ar/cookbook/kobzar-ukrainian-poems.md)

## Em poucas palavras

Um livrinho de presente com poemas ucranianos de Taras Shevchenko: uma folha de rosto vermelha com bordado, uma faixa sobre o título de cada poema e notas breves com asterisco.

## O que você vai compor

Seis páginas de uma edição de presente do *Кобзар* de Taras Shevchenko, em 130 × 200 mm, o formato 84 × 108/32 já refilado: uma folha de rosto vermelho-cereja com faixas de ponto-cruz, uma nota sobre o texto e três poemas. De «Причинна» vem o célebre começo, «Реве та стогне Дніпр широкий»; «Заповіт» e «Садок вишневий коло хати» vêm inteiros. Cada poema abre sob uma faixa de pontos vermelhos e pretos. Os versos são Vollkorn 11 sobre 15,5 pt; os títulos, Yeseva One, um tipo grosso com as formas redondas da arte do livro de Kiev por volta de 1917. Datas e lugares ficam em itálico sob os poemas e as notas levam asterisco. A nota sobre o texto segue a língua da edição; os poemas ficam em ucraniano.

**Esta receita responde a:**

- Como componho um livro de poemas em ucraniano, com estrofes, datas e notas?
- Como componho poesia: um verso por linha, espaço entre estrofes, recuo deslocado nos versos que quebram e sem hifenização?

## A resposta curta

```js
// script.js, linhas 36–52
// locale 'uk' is the language of the hyphenation, the ties (no line of the note parts «і», «в»,
// «на» from its word) and the footnotes, which start again on every page, indented. The
// apostrophe is typed ’ (U+2019): сем’ї, кров’ю stay whole words.
const LOCALE = 'uk';
// A poem is one :::verse block, written as it is printed, a blank line between two stanzas. A
// poem longer than its page goes on overleaf after a whole stanza or between two lines.
const verse = { align: 'center', hang: em(2) }; // bodyText.verse: centred on its longest line
// The note's mark follows its word: «півні[^1] не співали».
// Asterisks count a page's notes: *, **, ***, the custom of a book with few of them.
const footnotes = { numberFormat: 'symbols', fontFamily: TEXT, fontSize: pt(8.2),
  lineHeight: pt(11), color: col('muted'),
  separator: { enabled: true, width: 0.2, lineWidth: pt(0.5), color: col('cherry') } };
// The date and the place, in italics under the poem, drawn in to 16 mm from the
// right edge, under the ends of the lines.
const date = { id: 'date', fontSize: pt(9.2), color: col('muted'), textAlign: 'right',
  italic: true, endIndent: mm(16), firstLineIndent: pt(0), marginTop: pt(LEAD),
  hyphenation: false };
```

## Ingredientes

**Ensina**

- [Verso linha a linha](https://postext.dev/pt/docs/document-format-directives.md#verse): :::verse compõe um poema como foi escrito: um verso por linha de Markdown, linhas em branco entre estrofes, espaços iniciais como recuo; um verso longo demais se parte com recuo pendente ou à direita depois de um colchete, nunca separado da sua linha em uma quebra de página, e as estrofes curtas podem ficar inteiras.
- [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.
- [Notas de rodapé](https://postext.dev/pt/docs/document-format-notes-references.md#notas-de-rodapé): Notas citadas com [^id] e compostas no pé da coluna que as cita, ou depois do capítulo, numeradas por capítulo ou ao longo do livro todo.

**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)
- [Hifenização e idioma do documento](https://postext.dev/pt/docs/justification.md#idiomas-compatíveis)
- [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)
- [Capítulos sem número](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título)
- [Imagens nos designs de página](https://postext.dev/pt/docs/configuration-headers-footers.md#elementos-de-imagem)
- [Textos, fios e caixas nos designs de página](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés)
- [Capas, folhas de rosto e colofões](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título)
- [Estilos de parágrafo](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-parágrafo)
- [Metadados do documento](https://postext.dev/pt/docs/document-format.md#front-matter)
- [Cabeços e fólios](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés)
- [Cabeços por tipo de página](https://postext.dev/pt/docs/configuration-headers-footers.md#elementos-de-texto)
- [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)
- [Figuras e tabelas como recursos](https://postext.dev/pt/docs/document-format-resources.md#recursos)
- [Geometria por seção](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título)
- [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), [`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), [`footnotes`](https://postext.dev/pt/docs/configuration-notes-references.md#notas-de-rodapé), [`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), [`registerResourceImage`](https://postext.dev/pt/docs/architecture.md#superfície-da-api), [`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**

- Vollkorn (OFL-1.1), Yeseva One (OFL-1.1)

## Preparo

### 1 · O locale ucraniano e um bloco de versos

O código é [a resposta curta](https://postext.dev/pt/cookbook/kobzar-ukrainian-poems.md#a-resposta-curta) acima. `locale: 'uk'` escolhe a hifenização e as junções do ucraniano, recomeça as notas em cada página e as recua ([composição em cirílico](https://postext.dev/pt/docs/cyrillic-layout.md)). Cada poema é um bloco `:::verse` ([diretivas](https://postext.dev/pt/docs/document-format-directives.md)) escrito como se imprime, com uma linha em branco entre estrofes. `align: 'center'` centra o bloco pelo verso mais longo e todos começam na mesma borda. `[^1]` vem logo após a palavra, e `numberFormat: 'symbols'` a marca * ([notas](https://postext.dev/pt/docs/configuration-notes-references.md)). `:::paragraphs{style="date"}` compõe a data.

### 2 · 84 × 108/32, 28 linhas

```js
// script.js, linhas 56–63
const [TRIM_W, TRIM_H, TOP, INNER, OUTER, LINES] = [130, 200, 22, 19, 21, 28]; // mm, lines
const page = {
  sizePreset: '84x108/32', dpi: 150, backgroundColor: col('paper'),
  margins: { top: mm(TOP), bottom: mm(TRIM_H - TOP - LINES * LINE), left: mm(INNER),
    right: mm(OUTER), mirror: true },
};
const MEASURE = TRIM_W - INNER - OUTER; // mm: 90
const SHIFT = (INNER - OUTER) / 2; // mm: the text block's centre is off the page's centre
```

`sizePreset: '84x108/32'` é um formato de folha soviético e ucraniano, refilado a 130 × 200 mm. A margem de pé é o que 28 linhas deixam, então a mancha sempre termina em uma linha inteira. As margens externas são maiores que as internas e trocam com `mirror`. `SHIFT` centra cabeços e fólios sobre o texto, que fica a 1 mm do meio da página.

### 3 · Uma página vermelha e uma faixa por poema

```js
// script.js, linhas 67–98
const none = { header: { elements: [] }, footer: { elements: [] } };
// No margins on that page: the ground and the bands reach the trim on all four sides.
const flush = { span: 'page',
  margins: { top: mm(0), bottom: mm(0), left: mm(0), right: mm(0) } };
const titlePage = { id: 'title-page', ...none, ...flush, marginBottom: pt(0),
  breakBefore: { enabled: true, parity: 'odd' },
  advancedDesign: { enabled: true, minHeight: mm(TRIM_H), slot: { elements: [
    { kind: 'box', id: 'ground', style: { backgroundColor: col('cherry') },
      placement: { ...at('page', 'top-left'), size: { width: 'fill', height: mm(TRIM_H) } } },
    image('head', 'linen', { ...at('page', 'top-left'), size: { width: mm(TRIM_W) } }),
    image('foot', 'linen', { ...at('page', 'bottom-left'), size: { width: mm(TRIM_W) } }),
    text('author', '{author}', DISPLAY, 13, 'paper', at('page', 'top', 0, 58), wide),
    text('title', '{titleText}', DISPLAY, 58, 'paper', at('page', 'top', 0, 67)),
    text('subtitle', '{subtitle}', TEXT, 14, 'paper', at('page', 'top', 0, 96), italic),
    image('star', 'star', { ...at('page', 'top', 0, 116), size: { width: mm(22) } }),
    text('place', '{attr.place}', DISPLAY, 10, 'paper', at('page', 'bottom', 0, -32), wide),
  ] } } };
const poem = { id: 'poem', breakBefore: { enabled: true, parity: 'any' }, marginBottom: pt(0),
  numbered: false, advancedDesign: { enabled: true, minHeight: pt(7 * LEAD), slot: { elements: [
    image('band', 'band', { ...at('container', 'top', 0, -TOP + 14),
      size: { width: mm(MEASURE) } }),
    text('title', '{titleText}', DISPLAY, 16, 'cherry', at('container', 'top', 0, 14)),
    text('kicker', '{attr.kicker}', TEXT, 9.5, 'muted', at('#title', 'below', 0, 1.5), italic),
  ] } } };
// The note stands low on the verso behind the title page, under a star.
const notePage = { id: 'note-page', ...none, breakBefore: { enabled: true, parity: 'any' },
  marginBottom: pt(0), advancedDesign: { enabled: true, minHeight: pt(15 * LEAD), slot: {
    elements: [
      image('star', 'redstar', { ...at('container', 'top', 0, 10 * LINE),
        size: { width: mm(13) } }),
      text('label', '{titleText}', DISPLAY, 10, 'cherry', at('container', 'top', 0, 13.2 * LINE)),
    ] } } };
```

`# Кобзар {style="title-page" place="Київ"}` enche a página 1: com `span: 'page'` e sem margens, o desenho chega ao corte e toma o autor e o subtítulo do frontmatter. `# Заповіт {style="poem" kicker="…"}` dá a cada poema a faixa, o título e uma linha em itálico; `minHeight` de sete linhas faz todos começarem na mesma altura.

### 4 · Um bordado contado em uma grade

```js
// script.js, linhas 102–141
// Every stitch is an ×, so the pattern is counted, not drawn: the rose is the cells of a petal,
// b from 1 to 4 and a from b + 1 to b + 4, mirrored into its eight octants; a lozenge with a
// cross in it fills the gap every 24 stitches. Red and black threads on the paper, linen on red.
const [PERIOD, HALF] = [24, 11]; // stitches: one rose to the next, the middle row to the edge
const rose = (x, y) => { const [b, a] = [Math.abs(x), Math.abs(y)].sort((p, q) => p - q);
  return b >= 1 && b <= 4 && a >= b + 1 && a <= b + 4; };
function thread(x, y) { // 'A' the main thread, 'B' the second, '' bare cloth
  const u = ((x % PERIOD) + PERIOD) % PERIOD; // 0 at the middle of a rose
  const [dx, v] = [u > PERIOD / 2 ? u - PERIOD : u, Math.abs(y)];
  const r = Math.abs(u - PERIOD / 2) + v; // from the middle of the lozenge
  if (v === HALF) return 'B';
  if (v === HALF - 1) return x % 2 === 0 ? 'A' : '';
  if (rose(dx, y)) return 'A';
  if (r === 5 || r === 0) return 'B';
  if (r === 2 && (y === 0 || u === PERIOD / 2)) return 'A';
  // Small pyramids above and below the lozenge, hanging from the border.
  return Math.abs(u - PERIOD / 2) + (9 - v) <= 2 && v <= 9 ? 'B' : '';
}
function stitches(x0, x1, y0, y1, colours, cellAt = thread) { // one path per thread, 1 unit a cell
  const d = { A: '', B: '' };
  for (let y = y0; y <= y1; y++) {
    for (let x = x0; x <= x1; x++) {
      const t = cellAt(x, y);
      if (t) d[t] += `M${x - x0 + 0.14} ${y - y0 + 0.14}l.72 .72m0 -.72l-.72 .72`;
    }
  }
  const [w, h] = [x1 - x0 + 1, y1 - y0 + 1];
  return { width: w * 10, height: h * 10,
    markup: `<svg xmlns="http://www.w3.org/2000/svg" width="${w * 10}" height="${h * 10}" `
      + `viewBox="0 0 ${w} ${h}" fill="none" stroke-width=".4" stroke-linecap="round">`
      + `<path d="${d.A}" stroke="${palette[colours[0]]}"/>`
      + `<path d="${d.B}" stroke="${palette[colours[1]]}"/></svg>` };
}
const whole = (x, y) => (rose(x, y) ? 'A' : Math.abs(x) + Math.abs(y) === 0 ? 'B' : '');
const ART = {
  linen: stitches(-72, 72, -HALF, HALF, ['paper', 'paper']), // the width of the title page
  band: stitches(-60, 60, -HALF, HALF, ['cherry', 'ink']), // over a poem, at the measure
  star: stitches(-8, 8, -8, 8, ['paper', 'paper'], whole),
  redstar: stitches(-8, 8, -8, 8, ['cherry', 'ink'], whole),
};
```

As faixas são SVG feitos de pontos ×, um traçado por fio. Uma pétala são as casas com b de 1 a 4 e a de b + 1 a b + 4, levadas aos oito octantes por valores absolutos; um losango e duas pirâmides preenchem o vão a cada 24 casas. 121 pontos ocupam a medida e 145 a página, e no meio fica sempre uma rosa inteira.

## 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/kobzar-ukrainian-poems

### script.js

```js
// ═══ Postext Cookbook · Nº 208 · Shevchenko's poems in a gift edition of the Kobzar ══════
// https://postext.dev/en/cookbook/kobzar-ukrainian-poems
// Code: MIT · Text: T. Shevchenko, 1837–1847 (PD, litopys.org.ua) · Embroidery: drawn in code
// Fonts: Vollkorn, Yeseva One (SIL OFL 1.1) · Needs postext ≥ 1.100.0
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the note on the text ('en' | 'es' | 'ru')
const RECIPE = 'kobzar-ukrainian-poems';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// The red and black thread of a Dnipro embroidery on linen-coloured paper, and the round, dark
// capitals of the Kyiv book art of the 1910s and 1920s.
const palette = {
  ink: '#231b18', // the poems, the black thread
  cherry: '#a3221f', // the title page, the titles, the red thread
  muted: '#6f5e52', // notes, dates, running heads
  paper: '#fbf5e8', // the page, the linen thread on the red
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = Object.entries({ ...palette, 'main-color': palette.cherry })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const [TEXT, DISPLAY] = ['Vollkorn', 'Yeseva One']; // both with ґ є і ї
const [BODY, LEAD, LINE] = [11, 15.5, (15.5 * 25.4) / 72]; // pt, pt, and a line in mm: 5.47
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const text = (id, content, family, size, color, placement, extra = {}) => ({ kind: 'text', id,
  content, fontFamily: family, fontSize: pt(size), color: col(color), align: 'center',
  lineHeight: 1.15, overflow: 'wrap', ...extra,
  placement: { ...placement, size: { width: 'fill' } } });
const [wide, italic] = [{ letterSpacing: pt(1) }, { italic: true }];
const image = (id, resourceId, placement) => ({ kind: 'image', id, resourceId, placement });

// #region answer: the Ukrainian locale, a :::verse block a poem, its date and its notes
// locale 'uk' is the language of the hyphenation, the ties (no line of the note parts «і», «в»,
// «на» from its word) and the footnotes, which start again on every page, indented. The
// apostrophe is typed ’ (U+2019): сем’ї, кров’ю stay whole words.
const LOCALE = 'uk';
// A poem is one :::verse block, written as it is printed, a blank line between two stanzas. A
// poem longer than its page goes on overleaf after a whole stanza or between two lines.
const verse = { align: 'center', hang: em(2) }; // bodyText.verse: centred on its longest line
// The note's mark follows its word: «півні[^1] не співали».
// Asterisks count a page's notes: *, **, ***, the custom of a book with few of them.
const footnotes = { numberFormat: 'symbols', fontFamily: TEXT, fontSize: pt(8.2),
  lineHeight: pt(11), color: col('muted'),
  separator: { enabled: true, width: 0.2, lineWidth: pt(0.5), color: col('cherry') } };
// The date and the place, in italics under the poem, drawn in to 16 mm from the
// right edge, under the ends of the lines.
const date = { id: 'date', fontSize: pt(9.2), color: col('muted'), textAlign: 'right',
  italic: true, endIndent: mm(16), firstLineIndent: pt(0), marginTop: pt(LEAD),
  hyphenation: false };
// #endregion

// #region page: 84 × 108/32, the sheet format of a book of poems, 28 lines of 15.5 pt
const [TRIM_W, TRIM_H, TOP, INNER, OUTER, LINES] = [130, 200, 22, 19, 21, 28]; // mm, lines
const page = {
  sizePreset: '84x108/32', dpi: 150, backgroundColor: col('paper'),
  margins: { top: mm(TOP), bottom: mm(TRIM_H - TOP - LINES * LINE), left: mm(INNER),
    right: mm(OUTER), mirror: true },
};
const MEASURE = TRIM_W - INNER - OUTER; // mm: 90
const SHIFT = (INNER - OUTER) / 2; // mm: the text block's centre is off the page's centre
// #endregion

// #region openers: a red title page, and a stitched band over the title of each poem
const none = { header: { elements: [] }, footer: { elements: [] } };
// No margins on that page: the ground and the bands reach the trim on all four sides.
const flush = { span: 'page',
  margins: { top: mm(0), bottom: mm(0), left: mm(0), right: mm(0) } };
const titlePage = { id: 'title-page', ...none, ...flush, marginBottom: pt(0),
  breakBefore: { enabled: true, parity: 'odd' },
  advancedDesign: { enabled: true, minHeight: mm(TRIM_H), slot: { elements: [
    { kind: 'box', id: 'ground', style: { backgroundColor: col('cherry') },
      placement: { ...at('page', 'top-left'), size: { width: 'fill', height: mm(TRIM_H) } } },
    image('head', 'linen', { ...at('page', 'top-left'), size: { width: mm(TRIM_W) } }),
    image('foot', 'linen', { ...at('page', 'bottom-left'), size: { width: mm(TRIM_W) } }),
    text('author', '{author}', DISPLAY, 13, 'paper', at('page', 'top', 0, 58), wide),
    text('title', '{titleText}', DISPLAY, 58, 'paper', at('page', 'top', 0, 67)),
    text('subtitle', '{subtitle}', TEXT, 14, 'paper', at('page', 'top', 0, 96), italic),
    image('star', 'star', { ...at('page', 'top', 0, 116), size: { width: mm(22) } }),
    text('place', '{attr.place}', DISPLAY, 10, 'paper', at('page', 'bottom', 0, -32), wide),
  ] } } };
const poem = { id: 'poem', breakBefore: { enabled: true, parity: 'any' }, marginBottom: pt(0),
  numbered: false, advancedDesign: { enabled: true, minHeight: pt(7 * LEAD), slot: { elements: [
    image('band', 'band', { ...at('container', 'top', 0, -TOP + 14),
      size: { width: mm(MEASURE) } }),
    text('title', '{titleText}', DISPLAY, 16, 'cherry', at('container', 'top', 0, 14)),
    text('kicker', '{attr.kicker}', TEXT, 9.5, 'muted', at('#title', 'below', 0, 1.5), italic),
  ] } } };
// The note stands low on the verso behind the title page, under a star.
const notePage = { id: 'note-page', ...none, breakBefore: { enabled: true, parity: 'any' },
  marginBottom: pt(0), advancedDesign: { enabled: true, minHeight: pt(15 * LEAD), slot: {
    elements: [
      image('star', 'redstar', { ...at('container', 'top', 0, 10 * LINE),
        size: { width: mm(13) } }),
      text('label', '{titleText}', DISPLAY, 10, 'cherry', at('container', 'top', 0, 13.2 * LINE)),
    ] } } };
// #endregion

// #region embroidery: an eight-petalled rose and a lozenge, counted on a grid of crosses
// Every stitch is an ×, so the pattern is counted, not drawn: the rose is the cells of a petal,
// b from 1 to 4 and a from b + 1 to b + 4, mirrored into its eight octants; a lozenge with a
// cross in it fills the gap every 24 stitches. Red and black threads on the paper, linen on red.
const [PERIOD, HALF] = [24, 11]; // stitches: one rose to the next, the middle row to the edge
const rose = (x, y) => { const [b, a] = [Math.abs(x), Math.abs(y)].sort((p, q) => p - q);
  return b >= 1 && b <= 4 && a >= b + 1 && a <= b + 4; };
function thread(x, y) { // 'A' the main thread, 'B' the second, '' bare cloth
  const u = ((x % PERIOD) + PERIOD) % PERIOD; // 0 at the middle of a rose
  const [dx, v] = [u > PERIOD / 2 ? u - PERIOD : u, Math.abs(y)];
  const r = Math.abs(u - PERIOD / 2) + v; // from the middle of the lozenge
  if (v === HALF) return 'B';
  if (v === HALF - 1) return x % 2 === 0 ? 'A' : '';
  if (rose(dx, y)) return 'A';
  if (r === 5 || r === 0) return 'B';
  if (r === 2 && (y === 0 || u === PERIOD / 2)) return 'A';
  // Small pyramids above and below the lozenge, hanging from the border.
  return Math.abs(u - PERIOD / 2) + (9 - v) <= 2 && v <= 9 ? 'B' : '';
}
function stitches(x0, x1, y0, y1, colours, cellAt = thread) { // one path per thread, 1 unit a cell
  const d = { A: '', B: '' };
  for (let y = y0; y <= y1; y++) {
    for (let x = x0; x <= x1; x++) {
      const t = cellAt(x, y);
      if (t) d[t] += `M${x - x0 + 0.14} ${y - y0 + 0.14}l.72 .72m0 -.72l-.72 .72`;
    }
  }
  const [w, h] = [x1 - x0 + 1, y1 - y0 + 1];
  return { width: w * 10, height: h * 10,
    markup: `<svg xmlns="http://www.w3.org/2000/svg" width="${w * 10}" height="${h * 10}" `
      + `viewBox="0 0 ${w} ${h}" fill="none" stroke-width=".4" stroke-linecap="round">`
      + `<path d="${d.A}" stroke="${palette[colours[0]]}"/>`
      + `<path d="${d.B}" stroke="${palette[colours[1]]}"/></svg>` };
}
const whole = (x, y) => (rose(x, y) ? 'A' : Math.abs(x) + Math.abs(y) === 0 ? 'B' : '');
const ART = {
  linen: stitches(-72, 72, -HALF, HALF, ['paper', 'paper']), // the width of the title page
  band: stitches(-60, 60, -HALF, HALF, ['cherry', 'ink']), // over a poem, at the measure
  star: stitches(-8, 8, -8, 8, ['paper', 'paper'], whole),
  redstar: stitches(-8, 8, -8, 8, ['cherry', 'ink'], whole),
};
// #endregion

// Running heads: the poet on the verso, the poem on the recto; folios in the display face.
const head = (parity, content) => ({ kind: 'text', id: `head-${parity}`, parity, content,
  pages: 'body', align: 'center', fontFamily: TEXT, italic: true, fontSize: pt(9),
  color: col('muted'), placement: at('page', 'top', parity === 'odd' ? SHIFT : -SHIFT, 12) });
const header = { elements: [head('even', '{author}'), head('odd', '{chapterTitle}')] };
const folio = (parity) => ({ kind: 'text', id: `folio-${parity}`, parity, content: '{pageNumber}',
  align: 'center', fontFamily: DISPLAY, fontSize: pt(9.5), color: col('cherry'),
  placement: at('page', 'bottom', parity === 'odd' ? SHIFT : -SHIFT, -10) });
const footer = { elements: [folio('even'), folio('odd')] };

const config = () => ({
  locale: LOCALE, // written out, never LANG: the poems are Ukrainian in every edition
  colorPalette, page, footnotes, header, footer,
  layout: { layoutType: 'single' }, // the default is two columns
  bodyText: { fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    firstLineIndent: em(1.5), minWordSpacing: 0.8, maxWordSpacing: 1.6, verse },
  headings: { fontFamily: DISPLAY, fontWeight: 400,
    levels: [{ level: 1, breakBefore: { enabled: true, parity: 'any' } }] },
  headingStyles: [titlePage, notePage, poem],
  paragraphStyles: [date,
    // The note is in the edition's language: :::paragraphs{lang=…} divides it by its patterns.
    { id: 'note', fontSize: pt(9.2), lineHeight: pt(13), color: col('ink'),
      italicColor: col('ink'), firstLineIndent: em(1.5) },
    { id: 'colophon', fontSize: pt(7.6), lineHeight: pt(10.4), color: col('muted'),
      textAlign: 'center', firstLineIndent: pt(0), marginTop: pt(LEAD),
      hyphenation: false },
  ],
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The title page and the note (content.<lang>.md), then the poems (content.text.<lang>.md).
const markdown = [String.raw`---
title: "Кобзар"
subtitle: "Вибрані поезії"
author: "Тарас Шевченко"
---

# Кобзар {style="title-page" place="Київ"}

# A note on the text {style="note-page"}

:::paragraphs{style="note" lang="en"}
Taras Shevchenko (1814–1861) wrote *Причинна* (*The Bewitched Girl*) in St Petersburg while still a serf, *Заповіт* (*Testament*) ill in Pereiaslav, and the cherry orchard in a cell of the Third Department, weeks before ten years of exile as a soldier. The opening of the ballad and the two poems, whole, follow the text of the academic edition (Kyiv, 2003), which keeps the poet’s *тілько*, *сем’я*, *отойді*. The notes were written for this edition.
:::

:::paragraphs{style="colophon"}
Set in Vollkorn and Yeseva One (SIL OFL) · Text: T. Shevchenko, public domain · Embroidery drawn in code
:::
`, String.raw`# Причинна {style="poem" kicker="Початок балади"}

:::verse
Реве та стогне Дніпр широкий,
Сердитий вітер завива,
Додолу верби гне високі,
Горами хвилю підійма.
І блідний місяць на ту пору
Із хмари де-де виглядав,
Неначе човен в синім морі
То виринав, то потопав.
Ще треті півні[^1] не співали,
Ніхто нігде не гомонів,
Сичі в гаю перекликались,
Та ясен раз у раз скрипів.

В таку добу під горою,
Біля того гаю,
Що чорніє над водою,
Щось біле блукає.
:::

:::paragraphs{style="date"}
1837, С.-Петербург
:::

[^1]: Третій спів півнів, удосвіта: тоді зникає нечиста сила.

# Заповіт {style="poem" kicker="Як умру, то поховайте"}

:::verse
Як умру, то поховайте
Мене на могилі[^2]
Серед степу широкого
На Вкраїні милій,
Щоб лани широкополі,
І Дніпро, і кручі
Було видно, було чути,
Як реве ревучий.

Як понесе з України
У синєє море
Кров ворожу… отойді я
І лани і гори —
Все покину, і полину
До самого Бога
Молитися… а до того
Я не знаю Бога.

Поховайте та вставайте,
Кайдани порвіте
І вражою злою кров’ю
Волю окропіте.
І мене в сем’ї великій,
В сем’ї вольній, новій,
Не забудьте пом’янути
Незлим тихим словом.
:::

:::paragraphs{style="date"}
25 грудня 1845, Переяслав
:::

[^2]: Тут: на кургані, степовому насипі над давнім похованням.

# Садок вишневий коло хати {style="poem" kicker="З циклу «В казематі»"}

:::verse
Садок вишневий коло хати,
Хрущі над вишнями гудуть.
Плугатарі з плугами йдуть,
Співають, ідучи, дівчата,
А матері вечерять ждуть.

Сем’я вечеря коло хати,
Вечірня зіронька встає.
Дочка вечерять подає,
А мати хоче научати,
Так соловейко не дає.

Поклала мати коло хати
Маленьких діточок своїх,
Сама заснула коло їх.
Затихло все, тілько дівчата
Та соловейко не затих.
:::

:::paragraphs{style="date"}
19–30 травня 1847, С.-Петербург
:::
`].join('\n\n');
const resources = Object.entries(ART).map(([id, { width, height }]) => ({ id, typeId: 'figure',
  kind: 'svg', createdAt: 0, updatedAt: 0, svg: { fileId: `${id}.svg`, width, height } }));

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { // every face the pages paint, loaded before the first build
  Vollkorn: ['400', '400i'], // TEXT: the poems, the notes, the note on the text, the heads
  'Yeseva One': ['400'], // DISPLAY: titles and folios
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
for (const [id, { markup }] of Object.entries(ART)) await loadSvg(`${id}.svg`, markup);
const doc = await buildDocumentWithFonts({ markdown, resources }, config(),
  kitCyrillicFonts(FONTS));
showPages(doc, { title: 'Кобзар' });
offerPdf(() => renderToPdf(doc, { fontProvider: cyrillicPdfProvider, resourceBytes: imageBytes }),
  `${RECIPE}.pdf`);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ─── Kit · images v3 ── recipes with pictures · postext.dev/cookbook
/** Registers a photo or PNG for the canvas and keeps its bytes for the PDF.
 *  fetch → ImageBitmap never taints the canvas (a plain cross-origin <img> would). */
async function loadImage(fileId, url) {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`Image not found (${res.status}): ${url}`);
  const bytes = new Uint8Array(await res.arrayBuffer());
  registerResourceImage(fileId, await createImageBitmap(new Blob([bytes])));
  (loadImage.bytes ??= new Map()).set(fileId, bytes);
}

/** Registers SVG markup as a vector image, its fonts inside (inlineSvgFonts, ≥ 1.25).
 *  `options` go to registerResourceImage: { singleInk: true } tints it on the canvas. */
async function loadSvg(fileId, svg, options) {
  if (typeof inlineSvgFonts === 'function') svg = await inlineSvgFonts(svg, svgFaces);
  const img = new Image();
  img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
  await img.decode();
  registerResourceImage(fileId, img, options);
  (loadImage.bytes ??= new Map()).set(fileId, new TextEncoder().encode(svg));
}

/** A face's Fontsource files: nearest weight; latin + what the SVG sets. */
async function svgFaces(family, weight, style, { codePoints = [] } = {}) {
  const [id, m] = [fontsourceId(family), await fontsourceMeta(family)];
  const w = m?.weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a)) ?? weight;
  const s = m?.styles.includes(style) === false ? 'normal' : style;
  return Promise.all(['latin', ...kitSubsetsFor(String.fromCodePoint(...codePoints), m)].map(async (x) => new Uint8Array(
    await (await fetch(`${await fontsourceAt(id)}files/${id}-${x}-${w}-${s}.woff2`)).arrayBuffer())));
}

/** renderToPdf({ resourceBytes: imageBytes }) */
function imageBytes(fileId) { return loadImage.bytes?.get(fileId); }

/** renderToHtml({ resourceImageUrl: imageUrl }) */
function imageUrl(fileId) {
  const bytes = imageBytes(fileId);
  if (!bytes) return undefined;
  imageUrl.urls ??= new Map();
  if (!imageUrl.urls.has(fileId)) {
    const type = /\.svg$/i.test(fileId) ? 'image/svg+xml' : /\.png$/i.test(fileId) ? 'image/png' : 'image/jpeg';
    imageUrl.urls.set(fileId, URL.createObjectURL(new Blob([bytes], { type })));
  }
  return imageUrl.urls.get(fileId);
}

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

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

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

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

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

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

## Erros comuns

- **Um estilo de título herda a quebra de página do seu nível.** Uma entrada de headingStyles recebe do seu nível de título todos os campos que não define, inclusive breakBefore. Um sumário ou um colofão com estilo sobre um H1 depois de um :::pagebreak herda a paridade 'odd' e cai depois de uma página em branco. Dê a esse estilo breakBefore: { enabled: false }.

- Digite o apóstrofo ’ (U+2019) em сем’ї e з’їли. Um ' reto se lê como o sinal de pés.
- Um estilo de título define a própria quebra: dê a `poem` o seu `breakBefore` ou o poema segue o anterior.
- `hyphenation` em um estilo de parágrafo é um booleano. Texto em outra língua leva `:::paragraphs{lang="pt"}`, que traz também os padrões dessa língua.
- Confira se um tipo de título tem ґ, є, і e ї antes de escolhê-lo; muitos tipos cirílicos param no russo.

## Créditos

- Receita: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Texto: Причинна (1837), lines 1–16, after the text of the Collected Works in six volumes, vol. 1 (Kyiv, 2003): Taras Shevchenko ([fonte](http://litopys.org.ua/shevchenko/shev103.htm)), domínio público
- Texto: Заповіт (1845), whole, after the same edition, vol. 1: Taras Shevchenko ([fonte](http://litopys.org.ua/shevchenko/shev146.htm)), domínio público
- Texto: Садок вишневий коло хати (1847), whole, after the same edition, vol. 2: Taras Shevchenko ([fonte](http://litopys.org.ua/shevchenko/shev201.htm)), domínio público
- Texto: The note on the text, the footnotes and the colophon: Postext Cookbook, original
- Tipos: Vollkorn (OFL-1.1), Yeseva One (OFL-1.1)
- Código: MIT · Conteúdo de exemplo: MIT

## Relacionadas

- [Nº 015 · Poemas compostos verso a verso](https://postext.dev/pt/cookbook/poetry-collection.md): Cada poema é um bloco :::verse escrito como se imprime: os recuos de 1918 são espaços iniciais e os versos quebrados pendem 2 em do verso. · Nível 2 (Intermediário) · Poesia
- [Nº 062 · Poemas com forma: Easter Wings, de Herbert, verso a verso](https://postext.dev/pt/cookbook/shaped-verse.md): Easter Wings e The Altar, de George Herbert, em texto centralizado, um parágrafo por verso, para que o comprimento dos versos desenhe as duas figuras. · Nível 1 (Básico) · Poesia
- [Nº 188 · Hot stamping dourado numa capa azul-escura](https://postext.dev/pt/cookbook/gold-foil-poetry-cover.md): O dourado como cor especial com acabamento: chapa própria no PDF, brilho no Folio, e um cartão azul e um papel creme que não levam tinta. · Nível 3 (Avançado) · Poesia
