# ウクライナ語の詩を贈り物の本に

> シェフチェンコの詩3編を130 × 200 mmで。中央寄せの連、ページごとの星印の注、詩の下の日付、コードで描いた刺繍の帯。

- HTML版: https://postext.dev/ja/cookbook/kobzar-ukrainian-poems
- レシピ No. 208 · 文字と本文 · 難易度 2 (中級) · 出力: Canvas, PDF
- ジャンル: 詩歌
- 必要なもの postext ≥ 1.100.0, postext-pdf ≥ 1.100.0 · テスト環境 1.100.0, postext-pdf 1.100.0 ／テスト日 2026-12-02
- ページ: [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
- Sandboxで開く: https://postext.dev/ja/sandbox#recipe=kobzar-ukrainian-poems&lang=en (.postext: https://postext.dev/cookbook/kobzar-ukrainian-poems/en/kobzar-ukrainian-poems.postext)
- 最終更新: 2026-12-02
- 他の言語: [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), [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), [ar](https://postext.dev/ar/cookbook/kobzar-ukrainian-poems.md)

## かんたんな説明

タラス・シェフチェンコのウクライナ語の詩を集めた小さな贈り物の本。刺繍をあしらった赤い扉、各詩の題の上に刺繍の帯、星印の短い注が付きます。

## できあがり

タラス・シェフチェンコの詩集『コブザール』（*Кобзар*）の贈り物版6ページです。判型は84 × 108/32を断ち落とした130 × 200 mmで、クロスステッチの帯を付けたさくらんぼ色の扉、本文についての注記、3編の詩が並びます。«Причинна»は名高い冒頭«Реве та стогне Дніпр широкий»を、«Заповіт»と«Садок вишневий коло хати»は全文を収めました。どの詩も赤と黒の刺繍の帯の下から始まります。詩はVollkorn 11/15.5 pt、題はYeseva One。1917年ごろのキーウの書物芸術を思わせる丸く太い書体です。日付と場所は詩の下に斜体で置き、注は星印です。注記の言語は版ごとに変わり、詩はウクライナ語のままです。

**このレシピが答える問い:**

- ウクライナ語の詩集を、連・日付・注付きで組むには？
- 詩を組むには（1行に1詩行、連の間のアキ、折り返した行のぶら下げインデント、ハイフネーションなし）？

## 手短な答え

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

## 材料

**学べること**

- [行ごとの詩](https://postext.dev/ja/docs/document-format-directives.md#verse): :::verseは詩を書いたとおりに組みます。Markdownの1行が詩の1行、連のあいだは空行、行頭の空白は字下げです。長すぎる行はぶら下げるか角括弧の後ろで行末側に寄せて折り返し、頁の区切りで元の行と離れず、短い連は分けずに保てます。
- [文書の言語としてのキリル文字の諸言語](https://postext.dev/ja/docs/cyrillic-layout.md#キリル文字の本の始め方): localeを'ru'、'uk'、'be'、'bg'、'sr'、'mk'、'kk'、'ky'、'tt'、'ba'、'tg'、'mn'のいずれかにすると、その言語のハイフネーション、キャプション、表題、注、数詞、全紙判型、背文字の向きになります。
- [脚注](https://postext.dev/ja/docs/document-format-notes-references.md#脚注): [^id]で参照する注です。参照した段の下端か章の後に置き、章ごと、または本全体の通し番号を振ります。

**ほかに使うもの**

- [行末で分けない語](https://postext.dev/ja/docs/cyrillic-layout.md#分けない語)
- [ハイフネーションと文書の言語](https://postext.dev/ja/docs/justification.md#対応するロケール)
- [デザインした章扉](https://postext.dev/ja/docs/configuration-headings.md#幅と詳細デザイン)
- [見出しスタイル](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [見出しの属性](https://postext.dev/ja/docs/document-format.md#見出しの属性)
- [番号のない章](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [ページデザインの画像](https://postext.dev/ja/docs/configuration-headers-footers.md#画像要素)
- [ページデザインのテキスト・罫・ボックス](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル)
- [表紙、扉、奥付](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [段落スタイル](https://postext.dev/ja/docs/configuration-styles.md#段落スタイル)
- [文書のメタデータ](https://postext.dev/ja/docs/document-format.md#フロントマター)
- [柱とノンブル](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル)
- [ページの役割ごとの柱](https://postext.dev/ja/docs/configuration-headers-footers.md#テキスト要素)
- [見開きの余白](https://postext.dev/ja/docs/configuration-page-layout.md#見開きの余白)
- [用紙の色](https://postext.dev/ja/docs/configuration-page-layout.md#ページ)
- [セマンティックカラーパレット](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット)
- [PDFの書き出し](https://postext.dev/ja/docs/configuration-pdf-output.md#pdfの生成)
- [PDFに埋め込むフォント](https://postext.dev/ja/docs/configuration-pdf-output.md#なぜフォントプロバイダーが必要か)
- [リソースとしての図と表](https://postext.dev/ja/docs/document-format-resources.md#リソース)
- [節ごとのページ構成](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [節ごとの柱](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)

**設定の一覧**

- [`bodyText`](https://postext.dev/ja/docs/configuration-text.md#本文), [`colorPalette`](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット), [`footer`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`footnotes`](https://postext.dev/ja/docs/configuration-notes-references.md#脚注), [`header`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`headingStyles`](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル), [`headings`](https://postext.dev/ja/docs/configuration-headings.md#見出し), [`layout`](https://postext.dev/ja/docs/configuration-page-layout.md#レイアウト), [`locale`](https://postext.dev/ja/docs/configuration-language.md#ハイフネーション), [`page`](https://postext.dev/ja/docs/configuration-page-layout.md#ページ), [`paragraphStyles`](https://postext.dev/ja/docs/configuration-styles.md#段落スタイル)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#レイアウトの前にフォントを読み込む), [`decompressWoff2`](https://postext.dev/ja/docs/configuration-pdf-output.md#ブラウザー向けフォントプロバイダーfontsource--woff2), [`registerResourceImage`](https://postext.dev/ja/docs/architecture.md#apiの概要), [`renderPageToCanvas`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#ページをビットマップに描画する), [`renderToPdf`](https://postext.dev/ja/docs/configuration-pdf-output.md#pdfの生成)

**書体**

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

## 作り方

### 1 · ウクライナ語のlocaleと詩のブロック

コードは上の[手短な答え](https://postext.dev/ja/cookbook/kobzar-ukrainian-poems.md#手短な答え)です。`locale: 'uk'`はウクライナ語の分綴と語の結び付けを選び、注をページごとに数え直して字下げします（[キリル文字の組版](https://postext.dev/ja/docs/cyrillic-layout.md)）。詩は1編が1つの`:::verse`ブロックで（[ディレクティブ](https://postext.dev/ja/docs/document-format-directives.md)）、印刷どおりに書き、連の間に空行を置きます。`align: 'center'`は最も長い行でブロックを中央に寄せ、各行は同じ端から始まります。`[^1]`は語の直後に置き、`numberFormat: 'symbols'`が*にします（[注](https://postext.dev/ja/docs/configuration-notes-references.md)）。`:::paragraphs{style="date"}`が日付を組みます。

### 2 · 84 × 108/32、28行

```js
// script.js, 行 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'`はソ連とウクライナの紙取りの判型で、断裁して130 × 200 mmになります。地の余白は28行の残りなので、版面はいつも行の区切りで終わります。小口側の余白はのど側より広く、`mirror`で入れ替わります。`SHIFT`は柱とノンブルを、ページの中心から1 mmずれた本文の上に揃えます。

### 3 · 赤いページと、詩ごとの帯

```js
// script.js, 行 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="Київ"}`が1ページ目を占めます。`span: 'page'`と余白なしでデザインは断ち端まで届き、著者と副題はfrontmatterから取ります。`# Заповіт {style="poem" kicker="…"}`は詩に帯と題と斜体の1行を付け、7行の`minHeight`でどの詩も同じ高さから始まります。

### 4 · 格子で数えた刺繍

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

帯は×の縫い目でできたSVGで、糸ごとに1本のパスです。花びらは、bが1から4、aがb + 1からb + 4の升目で、絶対値により8方向へ写します。24升ごとに菱形と2つの小さな三角で隙間を埋めます。版面の幅は121目、ページは145目なので、中央にはいつも花が1輪まるごと入ります。

## レシピの全体

レシピのフォルダーから合成した1つのファイルで、サンプルのテキストとレシピ集の共通キットを埋め込んであり、自分でページを組み立てます。動かすには、空のページの`<script type="module">`に入れるか、新しいCodePenのpenのJSパネルに貼り付けます（モジュールとして）。esm.shからpostextを読み込むので、インストールもビルドも要りません。

- レシピのフォルダー: 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 ───────────────────────────────────────────────────────────────────────
```

## よくあるつまずき

- **見出しスタイルはその階層の改ページを受け継ぐ.** headingStylesの項目は、指定しなかったフィールドをすべて見出しの階層から受け継ぎ、breakBeforeも例外ではありません。:::pagebreakのあとのH1に付けた目次や奥付のスタイルはparity 'odd'を受け継ぎ、白ページの後ろに置かれます。こうしたスタイルにはbreakBefore: { enabled: false }を指定してください。

- сем’їやз’їлиのアポストロフィは’（U+2019）で打ちます。まっすぐな'は印刷ではフィートの記号に見えます。
- 見出しスタイルは改ページを自分で決めます。`poem`に`breakBefore`を与えないと、詩が前の詩に続きます。
- 段落スタイルの`hyphenation`は真偽値です。別の言語の文は`:::paragraphs{lang="ja"}`にすると、その言語の分綴パターンも付きます。
- 見出し書体を選ぶ前に、ґ、є、і、їがあるか確かめます。ロシア語までしかないキリル書体は多くあります。

## クレジット

- レシピ: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- テキスト: Причинна (1837), lines 1–16, after the text of the Collected Works in six volumes, vol. 1 (Kyiv, 2003): Taras Shevchenko ([出典](http://litopys.org.ua/shevchenko/shev103.htm)), パブリックドメイン
- テキスト: Заповіт (1845), whole, after the same edition, vol. 1: Taras Shevchenko ([出典](http://litopys.org.ua/shevchenko/shev146.htm)), パブリックドメイン
- テキスト: Садок вишневий коло хати (1847), whole, after the same edition, vol. 2: Taras Shevchenko ([出典](http://litopys.org.ua/shevchenko/shev201.htm)), パブリックドメイン
- テキスト: The note on the text, the footnotes and the colophon: Postext Cookbook, オリジナル
- 書体: Vollkorn (OFL-1.1), Yeseva One (OFL-1.1)
- コード: MIT · サンプルの内容: MIT

## 関連レシピ

- [No. 015 · 詩を1行ずつ組む](https://postext.dev/ja/cookbook/poetry-collection.md): 各詩は印刷されるとおりに書いた:::verseブロックです。1918年版のインデントは行頭の空白、折り返しはその行から2 emぶら下げ、連の間は空行で区切ります。 · 難易度 2 (中級) · 詩歌
- [No. 062 · 形の詩：ハーバートの『Easter Wings』を1行ずつ中央に](https://postext.dev/ja/cookbook/shaped-verse.md): ジョージ・ハーバートの『Easter Wings』と『The Altar』を、詩の1行を1段落として本文で中央そろえに組み、行の長さで2つの形を描きます。 · 難易度 1 (初級) · 詩歌
- [No. 188 · 濃紺の表紙に金の箔押し](https://postext.dev/ja/cookbook/gold-foil-poetry-cover.md): 金箔を加工付きの特色にします。PDFでは専用の版になり、Folioでは光り、紺の厚紙とクリームの紙はインキを刷りません。 · 難易度 3 (上級) · 詩歌
