# Poèmes ukrainiens dans une édition cadeau

> Trois poèmes de Chevtchenko en 130 × 200 mm : strophes centrées, notes à astérisque par page, dates dessous et frises au point de croix codées.

- Version HTML: https://postext.dev/fr/cookbook/kobzar-ukrainian-poems
- Recette Nº 208 · Caractères et texte · Niveau 2 (Intermédiaire) · Sorties: Canvas, PDF
- Genres: Poésie
- Nécessite postext ≥ 1.100.0, postext-pdf ≥ 1.100.0 · testée avec 1.100.0, postext-pdf 1.100.0 le 2026-12-02
- Pages: [1](https://postext.dev/cookbook/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
- Ouvrir dans le Sandbox: https://postext.dev/fr/sandbox#recipe=kobzar-ukrainian-poems&lang=en (.postext: https://postext.dev/cookbook/kobzar-ukrainian-poems/en/kobzar-ukrainian-poems.postext)
- Dernière mise à jour: 2026-12-02
- Autres langues: [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), [it](https://postext.dev/it/cookbook/kobzar-ukrainian-poems.md), [pt](https://postext.dev/pt/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)

## En bref

Un petit livre cadeau de poèmes ukrainiens de Taras Chevtchenko : une page de titre rouge brodée, une frise au-dessus du titre de chaque poème et de brèves notes à astérisque.

## Ce que vous allez composer

Six pages d’une édition cadeau du *Кобзар* de Taras Chevtchenko, en 130 × 200 mm, le format 84 × 108/32 une fois rogné : une page de titre rouge cerise avec des frises au point de croix, une note sur le texte et trois poèmes. De « Причинна », on lit le célèbre début, « Реве та стогне Дніпр широкий » ; « Заповіт » et « Садок вишневий коло хати » sont entiers. Chaque poème s’ouvre sous une frise de points rouges et noirs. Les vers sont en Vollkorn 11 sur 15,5 pt, les titres en Yeseva One, un caractère gras aux formes rondes du livre d’art de Kiev vers 1917. Dates et lieux sont en italique sous les poèmes, et les notes portent des astérisques. La note sur le texte suit la langue de l’édition ; les poèmes restent en ukrainien.

**Cette recette répond à:**

- Comment composer un livre de poèmes en ukrainien, avec strophes, dates et notes ?
- Comment composer de la poésie : un vers par ligne, blancs entre les strophes, retraits suspendus pour les vers renvoyés, sans césure ?

## La réponse courte

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

## Ingrédients

**Enseigne**

- [Vers ligne à ligne](https://postext.dev/fr/docs/document-format-directives.md#verse): :::verse compose un poème tel qu’il est écrit : un vers par ligne de Markdown, des lignes vides entre les strophes, les espaces de début comme retraits ; un vers trop long passe à la ligne avec un retrait suspendu ou au fer à droite derrière un crochet, jamais séparé de son vers à un saut de page, et les strophes courtes peuvent rester entières.
- [Les langues en cyrillique comme langue du document](https://postext.dev/fr/docs/cyrillic-layout.md#commencer-un-livre-en-cyrillique): locale 'ru', 'uk', 'be', 'bg', 'sr', 'mk', 'kk', 'ky', 'tt', 'ba', 'tg' ou 'mn' donne au livre la césure, les légendes, les titres de tableau, les notes, les nombres en lettres, les formats de feuille et le sens du dos de sa langue.
- [Notes de bas de page](https://postext.dev/fr/docs/document-format-notes-references.md#notes-de-bas-de-page): Des notes appelées avec [^id] et composées au pied de la colonne qui les cite, ou après le chapitre, numérotées par chapitre ou sur tout le livre.

**Utilise aussi**

- [Mots maintenus ensemble en fin de ligne](https://postext.dev/fr/docs/cyrillic-layout.md#mots-gardés-ensemble)
- [Césure et langue du document](https://postext.dev/fr/docs/justification.md#langues-prises-en-charge)
- [Ouvertures composées](https://postext.dev/fr/docs/configuration-headings.md#étendue-et-maquette-avancée)
- [Styles de titre](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)
- [Attributs de titre](https://postext.dev/fr/docs/document-format.md#attributs-de-titre)
- [Chapitres non numérotés](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)
- [Images dans les maquettes de page](https://postext.dev/fr/docs/configuration-headers-footers.md#éléments-image)
- [Texte, filets et boîtes dans les maquettes de page](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page)
- [Couvertures, pages de titre et colophons](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)
- [Styles de paragraphe](https://postext.dev/fr/docs/configuration-styles.md#styles-de-paragraphe)
- [Métadonnées du document](https://postext.dev/fr/docs/document-format.md#en-tête-yaml)
- [Titres courants et folios](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page)
- [Titres courants selon le rôle de la page](https://postext.dev/fr/docs/configuration-headers-footers.md#éléments-de-texte)
- [Marges en miroir](https://postext.dev/fr/docs/configuration-page-layout.md#marges-en-miroir)
- [Couleur du papier](https://postext.dev/fr/docs/configuration-page-layout.md#page)
- [Palette de couleurs sémantique](https://postext.dev/fr/docs/configuration-fonts-colors-viewers.md#palette-de-couleurs)
- [Export PDF](https://postext.dev/fr/docs/configuration-pdf-output.md#générer-des-pdf)
- [Polices intégrées au PDF](https://postext.dev/fr/docs/configuration-pdf-output.md#pourquoi-un-fournisseur-de-polices)
- [Figures et tableaux comme ressources](https://postext.dev/fr/docs/document-format-resources.md#ressources)
- [Géométrie de section](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)
- [Titres courants par section](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)

**La configuration en un coup d’œil**

- [`bodyText`](https://postext.dev/fr/docs/configuration-text.md#texte-courant), [`colorPalette`](https://postext.dev/fr/docs/configuration-fonts-colors-viewers.md#palette-de-couleurs), [`footer`](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page), [`footnotes`](https://postext.dev/fr/docs/configuration-notes-references.md#notes-de-bas-de-page), [`header`](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page), [`headingStyles`](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre), [`headings`](https://postext.dev/fr/docs/configuration-headings.md#titres), [`layout`](https://postext.dev/fr/docs/configuration-page-layout.md#mise-en-page), [`locale`](https://postext.dev/fr/docs/configuration-language.md#césure), [`page`](https://postext.dev/fr/docs/configuration-page-layout.md#page), [`paragraphStyles`](https://postext.dev/fr/docs/configuration-styles.md#styles-de-paragraphe)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/fr/docs/configuration-programmatic-usage.md#charger-les-polices-avant-la-mise-en-page), [`decompressWoff2`](https://postext.dev/fr/docs/configuration-pdf-output.md#fournisseur-de-polices-dans-le-navigateur-fontsource--woff2), [`registerResourceImage`](https://postext.dev/fr/docs/architecture.md#surface-de-lapi), [`renderPageToCanvas`](https://postext.dev/fr/docs/configuration-programmatic-usage.md#rendre-une-page-en-bitmap), [`renderToPdf`](https://postext.dev/fr/docs/configuration-pdf-output.md#générer-des-pdf)

**Caractères**

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

## Préparation

### 1 · La locale ukrainienne et un bloc de vers

Le code est [la réponse courte](https://postext.dev/fr/cookbook/kobzar-ukrainian-poems.md#la-réponse-courte) ci-dessus. `locale: 'uk'` choisit la coupure et les liaisons de l’ukrainien, recompte les notes à chaque page et les renfonce ([composition en cyrillique](https://postext.dev/fr/docs/cyrillic-layout.md)). Chaque poème est un bloc `:::verse` ([directives](https://postext.dev/fr/docs/document-format-directives.md)) écrit comme il s’imprime, une ligne vide entre deux strophes. `align: 'center'` centre le bloc sur son plus long vers et tous partent du même bord. `[^1]` suit son mot, et `numberFormat: 'symbols'` l’appelle * ([notes](https://postext.dev/fr/docs/configuration-notes-references.md)). `:::paragraphs{style="date"}` compose la date.

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

```js
// script.js, lignes 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'` est un format de feuille soviétique et ukrainien, rogné à 130 × 200 mm. La marge de pied est ce que laissent 28 lignes, si bien que le bloc finit toujours sur une ligne pleine. Les marges extérieures sont plus larges que les intérieures et permutent avec `mirror`. `SHIFT` centre titres courants et folios sur le texte, décalé de 1 mm du milieu de la page.

### 3 · Une page rouge, puis une frise par poème

```js
// script.js, lignes 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="Київ"}` remplit la page 1 : avec `span: 'page'` et sans marges, son dessin atteint la coupe et prend l’auteur et le sous-titre dans le frontmatter. `# Заповіт {style="poem" kicker="…"}` donne à chaque poème la frise, le titre et une ligne d’italique ; un `minHeight` de sept lignes les fait tous commencer à la même hauteur.

### 4 · Une broderie comptée sur une grille

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

Les frises sont des SVG faits de points ×, un tracé par fil. Un pétale, ce sont les cases où b va de 1 à 4 et a de b + 1 à b + 4, portées dans les huit octants par des valeurs absolues ; un losange et deux pyramides comblent l’espace toutes les 24 cases. 121 points couvrent la justification et 145 la page, si bien qu’une rose entière occupe toujours le milieu.

## La recette complète

Un seul fichier, composé à partir du dossier de la recette avec le texte d’exemple et le kit commun des Recettes déjà inclus ; il construit sa propre page. Pour l’exécuter, placez-le dans un `<script type="module">` d’une page vide ou collez-le dans le panneau JS d’un nouveau pen CodePen (en tant que module). Il importe postext depuis esm.sh : il n’y a rien à installer ni à compiler.

- Dossier de la recette: https://github.com/drnachio/postext/tree/main/cookbook/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 ───────────────────────────────────────────────────────────────────────
```

## Erreurs fréquentes

- **Un style de titre hérite du saut de page de son niveau.** Une entrée headingStyles reprend de son niveau de titre chaque champ qu’elle omet, breakBefore compris. Une page de table des matières ou un colophon mis en forme sur un H1 après un :::pagebreak hérite de la parité 'odd' et atterrit derrière une page blanche. Donnez à un tel style breakBefore: { enabled: false }.

- Tapez l’apostrophe ’ (U+2019) dans сем’ї et з’їли. Une ' droite se lit comme le signe des pieds.
- Un style de titre fixe son propre saut : donnez à `poem` son `breakBefore`, sinon le poème suit le précédent.
- `hyphenation` dans un style de paragraphe est un booléen. Un texte dans une autre langue prend `:::paragraphs{lang="fr"}`, qui apporte aussi les motifs de cette langue.
- Vérifiez qu’un caractère de titrage possède ґ, є, і et ї avant de le choisir ; beaucoup de caractères cyrilliques s’arrêtent au russe.

## Crédits

- Recette: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Texte: Причинна (1837), lines 1–16, after the text of the Collected Works in six volumes, vol. 1 (Kyiv, 2003): Taras Shevchenko ([source](http://litopys.org.ua/shevchenko/shev103.htm)), domaine public
- Texte: Заповіт (1845), whole, after the same edition, vol. 1: Taras Shevchenko ([source](http://litopys.org.ua/shevchenko/shev146.htm)), domaine public
- Texte: Садок вишневий коло хати (1847), whole, after the same edition, vol. 2: Taras Shevchenko ([source](http://litopys.org.ua/shevchenko/shev201.htm)), domaine public
- Texte: The note on the text, the footnotes and the colophon: Postext Cookbook, original
- Caractères: Vollkorn (OFL-1.1), Yeseva One (OFL-1.1)
- Code: MIT · Contenu d’exemple: MIT

## Recettes liées

- [Nº 015 · Des poèmes composés vers à vers](https://postext.dev/fr/cookbook/poetry-collection.md): Chaque poème est un bloc :::verse écrit tel qu’imprimé : retraits de 1918 en espaces de tête, renvois pendant 2 em plus loin, ligne blanche entre strophes. · Niveau 2 (Intermédiaire) · Poésie
- [Nº 062 · Vers figurés : Easter Wings de Herbert, centré vers à vers](https://postext.dev/fr/cookbook/shaped-verse.md): Easter Wings et The Altar de George Herbert composés en texte courant centré, un paragraphe par vers : la longueur des lignes dessine les deux figures. · Niveau 1 (Débutant) · Poésie
- [Nº 188 · Dorure à chaud sur une couverture bleu nuit](https://postext.dev/fr/cookbook/gold-foil-poetry-cover.md): La dorure comme ton direct avec une finition : sa propre plaque dans le PDF, l’éclat dans Folio, et une carte bleue et un vélin crème sans encre. · Niveau 3 (Avancé) · Poésie
