# アバイと草原の五詩人、カザフ語の選集

> 六つのキリル文字言語による8ページの選集。カザフ語の本に、言語ごとの詩、ページ下の語注、フェルト敷物の文様。

- HTML版: https://postext.dev/ja/cookbook/abai-kazakh-anthology
- レシピ No. 210 · 完成した出版物 · 難易度 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/abai-kazakh-anthology/en/p01.webp?v=ae6c047c), [2](https://postext.dev/cookbook/abai-kazakh-anthology/en/p02.webp?v=ae6c047c), [3](https://postext.dev/cookbook/abai-kazakh-anthology/en/p03.webp?v=ae6c047c), [4](https://postext.dev/cookbook/abai-kazakh-anthology/en/p04.webp?v=ae6c047c), [5](https://postext.dev/cookbook/abai-kazakh-anthology/en/p05.webp?v=ae6c047c), [6](https://postext.dev/cookbook/abai-kazakh-anthology/en/p06.webp?v=ae6c047c), [7](https://postext.dev/cookbook/abai-kazakh-anthology/en/p07.webp?v=ae6c047c), [8](https://postext.dev/cookbook/abai-kazakh-anthology/en/p08.webp?v=ae6c047c)
- Sandboxで開く: https://postext.dev/ja/sandbox#recipe=abai-kazakh-anthology&lang=en (.postext: https://postext.dev/cookbook/abai-kazakh-anthology/en/abai-kazakh-anthology.postext)
- 最終更新: 2026-12-02
- 他の言語: [en](https://postext.dev/en/cookbook/abai-kazakh-anthology.md), [es](https://postext.dev/es/cookbook/abai-kazakh-anthology.md), [ca](https://postext.dev/ca/cookbook/abai-kazakh-anthology.md), [de](https://postext.dev/de/cookbook/abai-kazakh-anthology.md), [el](https://postext.dev/el/cookbook/abai-kazakh-anthology.md), [fr](https://postext.dev/fr/cookbook/abai-kazakh-anthology.md), [it](https://postext.dev/it/cookbook/abai-kazakh-anthology.md), [pt](https://postext.dev/pt/cookbook/abai-kazakh-anthology.md), [ru](https://postext.dev/ru/cookbook/abai-kazakh-anthology.md), [zh](https://postext.dev/zh/cookbook/abai-kazakh-anthology.md), [ar](https://postext.dev/ar/cookbook/abai-kazakh-anthology.md)

## かんたんな説明

アバイに始まり、キルギス語、タタール語、バシキール語、モンゴル語、タジク語の詩へ続く小さな選集です。難しい語はページの下にカザフ語で説明し、文様は草原のフェルト敷物から取りました。

## できあがり

『Дала үні』（草原の声）は145 × 215 mm、8ページの小冊子です。表紙は羊の角の文様のタイルによるフェルト敷物で、その下に書名と目次が入ります。アバイの「第一の言葉」と「八行詩」の最初の連が見開きを占め、キルギス語、タタール語、バシキール語、モンゴル語、タジク語の詩が1ページずつ続きます。それぞれ詩人の色の帯に、ローマ数字、題、名、生没年、言語を入れました。古い語や外来の語はページの下にカザフ語で注を付けます。本文はAlegreya、題はPiazzollaです。奥付だけが版の言語に合わせて変わります。

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

- カザフ語、キルギス語、タタール語、バシキール語、モンゴル語、タジク語の選集を組むには？

## 手短な答え

```js
// script.js, 行 41–59
// The book is Kazakh: its hyphenation, the ties (a dash opens no line, a number keeps its unit)
// and its notes, which start again on every page with an indent of 1.5 em.
const LOCALE = 'kk';
// A poem in another language is a :::verse block that names it: the poem is shaped by that
// language and tagged with it in the PDF and the HTML, :::verse{lang=ky}.
// ky Kyrgyz, tt Tatar, ba Bashkir, mn Mongolian, tg Tajik. Two spaces at the head of a line
// draw it in, as in the third and sixth lines of «Сегіз аяқ».
const verse = { align: 'center', hang: em(2), keepStanzas: 8 }; // bodyText.verse
const bodyText = {
  fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('red'),
  textAlign: 'justify', firstLineIndent: em(1.5), minWordSpacing: 0.75, maxWordSpacing: 1.7,
  maxJustifyTracking: 15,
  hyphenation: { leftMin: 2, rightMin: 2 }, verse,
};
// The glosses are Kazakh, whatever the language of the word: жеме — сөгіс, кінә.
const footnotes = { fontFamily: TEXT, fontSize: pt(8.8), lineHeight: pt(11.5),
  color: col('muted'), separator: { enabled: true, width: 0.2, lineWidth: pt(0.6),
    color: col('gold') } };
```

## 材料

**学べること**

- [文書の言語としてのキリル文字の諸言語](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-directives.md#verse): :::verseは詩を書いたとおりに組みます。Markdownの1行が詩の1行、連のあいだは空行、行頭の空白は字下げです。長すぎる行はぶら下げるか角括弧の後ろで行末側に寄せて折り返し、頁の区切りで元の行と離れず、短い連は分けずに保てます。
- [脚注](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-notes-references.md#目次)
- [番号付き見出し](https://postext.dev/ja/docs/configuration-headings.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-headers-footers.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/document-format.md#フロントマター)
- [番号のない章](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [見開きの余白](https://postext.dev/ja/docs/configuration-page-layout.md#見開きの余白)
- [字下げ、行そろえ、段落間隔](https://postext.dev/ja/docs/configuration-text.md#本文)
- [セマンティックカラーパレット](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット)
- [PDFの書き出し](https://postext.dev/ja/docs/configuration-pdf-output.md#pdfの生成)
- [用紙の色](https://postext.dev/ja/docs/configuration-page-layout.md#ページ)
- [段落スタイル](https://postext.dev/ja/docs/configuration-styles.md#段落スタイル)
- [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#見出しスタイル)

**設定の一覧**

- [`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#段落スタイル), [`toc`](https://postext.dev/ja/docs/configuration-notes-references.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の生成)

**書体**

- Alegreya (OFL-1.1), Alegreya Sans (OFL-1.1), Piazzolla (OFL-1.1)

## 作り方

### 1 · カザフ語の本に五言語の詩

コードは上の[手短な答え](https://postext.dev/ja/cookbook/abai-kazakh-anthology.md#手短な答え)です。`locale: 'kk'`が本の[分綴](https://postext.dev/ja/docs/cyrillic-layout.md#12言語のハイフネーション)、[分けない語](https://postext.dev/ja/docs/cyrillic-layout.md#分けない語)、[注](https://postext.dev/ja/docs/cyrillic-layout.md#ページごとに番号を振る注)を決めます。注はページごとに番号を振り直し、1.5 em下げます。ほかの詩はそれぞれ`:::verse{lang=ky}`とし、その言語で組み、PDFとHTMLにも言語を標識します。`align: 'center'`はいちばん長い行を基準に詩を中央へ置き、`keepStanzas: 8`は連を1ページに収め、行頭の二つの空白が字下げになります。

### 2 · 詩人の色のフェルト帯

```js
// script.js, 行 63–84
// # Үлгү ырлар {tone="blue" author="Тоқтоғұл Сатылғанов" when="1864–1933" tongue="қырғызша"}
const PANEL = 56; // mm: the panel's height, from the head of the page
const opener = { enabled: true, minHeight: mm(PANEL - TOP + 8), slot: { elements: [
  image('panel', 'panel-{attr.tone}', { ...at('page', 'top-left'), size: { width: mm(TRIM_W) } }),
  text('number', '{number}', DISPLAY, 17, 700, 'cream', at('container', 'top-left', 0, -10)),
  text('title', '{titleText}', DISPLAY, 21, 800, 'cream',
    { ...at('container', 'top-left', 0, -2.5), ...fill }),
  text('author', '{attr.author}', SANS, 12, 700, 'cream', at('container', 'top-left', 0, 11)),
  text('when', '{attr.when} · {attr.tongue}', SANS, 11, 400, 'cream',
    { ...at('container', 'top-right', 0, 11.3) }, { align: 'right' }),
] } };
// A second piece by the same poet goes on in the page, under a narrower border.
const runOn = { id: 'run-on', breakBefore: { enabled: false }, marginTop: pt(LEAD),
  marginBottom: pt(0), advancedDesign: { enabled: true, minHeight: pt(3.6 * LEAD), slot: {
    elements: [
      image('strip', 'strip', { ...at('container', 'top-left'), ...fill }),
      text('number', '{number}', DISPLAY, 13, 700, 'red', at('container', 'top-left', 0, 9)),
      text('title', '{titleText}', DISPLAY, 17, 800, 'red',
        at('container', 'top-left', 9, 7.8)),
      text('tongue', '{attr.tongue}', SANS, 10, 400, 'muted',
        at('container', 'top-right', 0, 10), { align: 'right' }),
    ] } } };
```

見出しが帯に刷る内容を持ちます：`# Үлгү ырлар {tone="blue" author="Тоқтоғұл Сатылғанов" when="1864–1933" tongue="қырғызша"}`。`panel-{attr.tone}`が絵柄を指すので、一つのデザインが四色に使えます。同じ`author`は目次とフッターにも入ります。`numberingTemplate: '{1:I}'`はローマ数字を作ります。同じ詩人の二作目は、改ページせず細い縁飾りの付く`run-on`スタイルです。

### 3 · 表紙に置く目次

```js
// script.js, 行 88–106
const none = { numbered: false, toc: false, header: { elements: [] }, footer: { elements: [] } };
const RUG = 2 * (TRIM_W / 4); // mm: two rows of four tiles
const cover = { id: 'cover', ...none, marginBottom: pt(0), advancedDesign: { enabled: true,
  minHeight: mm(RUG - TOP + 41), slot: { elements: [
    image('rug', 'rug', { ...at('page', 'top-left'), size: { width: mm(TRIM_W) } }),
    text('title', '{titleText}', DISPLAY, 42, 800, 'red',
      at('page', 'top-left', INNER, RUG + 9)),
    text('subtitle', '{subtitle}', SANS, 13, 400, 'ink', at('#title', 'below', 0, 0.5)),
  ] } } };
const toc = {
  levels: [{ level: 1, fontFamily: DISPLAY, fontSize: pt(11), color: col('ink'),
    numberFontWeight: 700, numberColor: col('red'), numberWidth: mm(8), numberGap: mm(2),
    marginBottom: pt(2.5) }],
  pageNumber: { fontFamily: SANS, fontSize: pt(10), fontWeight: 700, color: col('red'),
    width: mm(5) },
  leader: { char: '. ', gap: mm(2) },
  subtitle: { enabled: true, attr: 'author', italic: false, fontFamily: SANS, fontSize: pt(9),
    color: col('muted') },
};
```

表紙の見出しは`minHeight`で敷物と書名の場所を取り、`:::toc`が本文の流れに続きます。`toc.subtitle`は各見出しの`author`を題の下に刷ります。表紙は番号も付かず、目次にも載りません。

### 4 · 半円で描く羊の角

```js
// script.js, 行 110–144
// A pair of horns is two half circles a side, radius 10 and then 6, on a stem; four pairs round
// a diamond make the tile, and a row of pairs, one up and one down, the border. The width of
// the stroke leaves as much ground as wool, so either colour can be read as the figure.
const horn = (side, sweep) => `M50 20 A10 10 0 0 ${sweep} ${50 + side * 20} 20 `
  + `A6 6 0 0 ${sweep} ${50 + side * 8} 20`;
const pair = `M50 40 V20 ${horn(-1, 0)} ${horn(1, 1)}`;
const horns = (colour, turn, w = 5.6) => `<path d="${pair}" transform="${turn}" fill="none" `
  + `stroke="${colour}" stroke-width="${w}" stroke-linecap="round" stroke-linejoin="round"/>`;
const shape = (d, colour, turn = '') => `<path d="${d}" fill="${colour}" transform="${turn}"/>`;
const tile = (x, y, ground, wool, spark) => `<g transform="translate(${x} ${y})">`
  + shape('M0 0H100V100H0Z', ground)
  + [0, 90, 180, 270].map((a) => horns(wool, `rotate(${a} 50 50)`)
    + shape('M0 0H17L0 17Z', spark, `rotate(${a} 50 50)`)).join('')
  + shape('M50 35L65 50L50 65L35 50Z', wool) + shape('M50 43L57 50L50 57L43 50Z', spark)
  + '</g>';
const UNIT = 50; // a pair of horns and its gap, in the border's units
const border = (n, colour, y) => Array.from({ length: n }, (_, i) => horns(colour, i % 2
  ? `translate(${i * UNIT - 25} ${y + 43}) scale(1 -1)`
  : `translate(${i * UNIT - 25} ${y - 3})`)).join('');
const teeth = (n, step, y, h, colour) => shape(Array.from({ length: n }, (_, i) =>
  `M${i * step} ${y}h${step}l${-step / 2} ${h}Z`).join(''), colour);
const svg = (w, h, body) => ({ width: w, height: h, markup: `<svg xmlns="http://www.w3.org/2000/`
  + `svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${body}</svg>` });
const { cream, gold } = palette;
const panel = (tone) => svg(600, 231.7, // the trim's width, 12 pairs of horns
  shape('M0 0H600V231.7H0Z', palette[tone]) + border(12, cream, 174)
  + shape('M0 160H600V163H0Z', cream) + teeth(48, 12.5, 222.7, 9, gold));
const rug = ['red', 'blue', 'green', 'ochre', 'blue', 'ochre', 'red', 'green'];
const ART = {
  rug: svg(400, 200, rug.map((tone, i) => tile((i % 4) * 100, Math.floor(i / 4) * 100,
    palette[tone], cream, gold)).join('')),
  strip: svg(1000, 60, shape('M0 0H1000V60H0Z', palette.red) + border(20, cream, 10)),
  ...Object.fromEntries(['red', 'blue', 'green', 'ochre']
    .map((tone) => [`panel-${tone}`, panel(tone)])),
};
```

角は半径10と6の半円二つで、共通の軸から出ます。四対を菱形のまわりに回すとタイル、対を上下交互に並べると縁飾りです。線とすき間の幅が近いのは、フェルト同士がはまり合うシルダックと同じです。

## レシピの全体

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

- レシピのフォルダー: https://github.com/drnachio/postext/tree/main/cookbook/abai-kazakh-anthology

### script.js

```js
// ═══ Postext Cookbook · Nº 210 · A Kazakh anthology of six languages of the steppe ═══
// https://postext.dev/en/cookbook/abai-kazakh-anthology
// Code: MIT · Text: Abai, Toktogul, Tukay, Akmulla, Natsagdorj, Rudaki (PD) · Ornament: code
// Fonts: Alegreya, Alegreya Sans, Piazzolla (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 colophon ('en' | 'es' | 'ru')
const RECIPE = 'abai-kazakh-anthology';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// The dyed felts of a shyrdak, the mosaic rug of the yurt: madder, indigo, pine and bark, all
// cut against undyed wool.
const palette = {
  ink: '#2a1d17', // text, brown-black wool
  red: '#9c2a26', // madder: Abai, Rudaki, the note marks
  blue: '#1f4e79', // indigo: Toktogul, Natsagdorj
  green: '#2f5d3a', // pine: Tukay
  ochre: '#8a5010', // bark: Akmulla
  gold: '#dba544', // the small triangles and diamonds
  cream: '#f5ecda', // the paper and the undyed wool
  muted: '#6b5647', // languages, dates, notes
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = Object.entries({ ...palette, 'main-color': palette.red })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
// All three hold ә ғ қ ң ө ұ ү һ, ҙ ҫ ҡ and ҷ ҳ ӣ ӯ in their cyrillic-ext files.
const [TEXT, SANS, DISPLAY] = ['Alegreya', 'Alegreya Sans', 'Piazzolla'];
const [BODY, LEAD] = [11, 14.5]; // pt
const [TRIM_W, TRIM_H, TOP, INNER, OUTER] = [145, 215, 22, 21, 19]; // mm: 60 × 90/16
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const text = (id, content, fontFamily, size, fontWeight, color, placement, extra = {}) => ({
  kind: 'text', id, content, fontFamily, fontSize: pt(size), fontWeight, color: col(color),
  align: 'left', lineHeight: 1.1, overflow: 'wrap', placement, ...extra });
const fill = { size: { width: 'fill' } };
const image = (id, resourceId, placement) => ({ kind: 'image', id, resourceId, placement });

// #region answer: a Kazakh document, with each poem named in its own language
// The book is Kazakh: its hyphenation, the ties (a dash opens no line, a number keeps its unit)
// and its notes, which start again on every page with an indent of 1.5 em.
const LOCALE = 'kk';
// A poem in another language is a :::verse block that names it: the poem is shaped by that
// language and tagged with it in the PDF and the HTML, :::verse{lang=ky}.
// ky Kyrgyz, tt Tatar, ba Bashkir, mn Mongolian, tg Tajik. Two spaces at the head of a line
// draw it in, as in the third and sixth lines of «Сегіз аяқ».
const verse = { align: 'center', hang: em(2), keepStanzas: 8 }; // bodyText.verse
const bodyText = {
  fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('red'),
  textAlign: 'justify', firstLineIndent: em(1.5), minWordSpacing: 0.75, maxWordSpacing: 1.7,
  maxJustifyTracking: 15,
  hyphenation: { leftMin: 2, rightMin: 2 }, verse,
};
// The glosses are Kazakh, whatever the language of the word: жеме — сөгіс, кінә.
const footnotes = { fontFamily: TEXT, fontSize: pt(8.8), lineHeight: pt(11.5),
  color: col('muted'), separator: { enabled: true, width: 0.2, lineWidth: pt(0.6),
    color: col('gold') } };
// #endregion

// #region opener: a felt panel in the poet's colour, named by the heading's attributes
// # Үлгү ырлар {tone="blue" author="Тоқтоғұл Сатылғанов" when="1864–1933" tongue="қырғызша"}
const PANEL = 56; // mm: the panel's height, from the head of the page
const opener = { enabled: true, minHeight: mm(PANEL - TOP + 8), slot: { elements: [
  image('panel', 'panel-{attr.tone}', { ...at('page', 'top-left'), size: { width: mm(TRIM_W) } }),
  text('number', '{number}', DISPLAY, 17, 700, 'cream', at('container', 'top-left', 0, -10)),
  text('title', '{titleText}', DISPLAY, 21, 800, 'cream',
    { ...at('container', 'top-left', 0, -2.5), ...fill }),
  text('author', '{attr.author}', SANS, 12, 700, 'cream', at('container', 'top-left', 0, 11)),
  text('when', '{attr.when} · {attr.tongue}', SANS, 11, 400, 'cream',
    { ...at('container', 'top-right', 0, 11.3) }, { align: 'right' }),
] } };
// A second piece by the same poet goes on in the page, under a narrower border.
const runOn = { id: 'run-on', breakBefore: { enabled: false }, marginTop: pt(LEAD),
  marginBottom: pt(0), advancedDesign: { enabled: true, minHeight: pt(3.6 * LEAD), slot: {
    elements: [
      image('strip', 'strip', { ...at('container', 'top-left'), ...fill }),
      text('number', '{number}', DISPLAY, 13, 700, 'red', at('container', 'top-left', 0, 9)),
      text('title', '{titleText}', DISPLAY, 17, 800, 'red',
        at('container', 'top-left', 9, 7.8)),
      text('tongue', '{attr.tongue}', SANS, 10, 400, 'muted',
        at('container', 'top-right', 0, 10), { align: 'right' }),
    ] } } };
// #endregion

// #region cover: the rug over the title, and the contents under it
const none = { numbered: false, toc: false, header: { elements: [] }, footer: { elements: [] } };
const RUG = 2 * (TRIM_W / 4); // mm: two rows of four tiles
const cover = { id: 'cover', ...none, marginBottom: pt(0), advancedDesign: { enabled: true,
  minHeight: mm(RUG - TOP + 41), slot: { elements: [
    image('rug', 'rug', { ...at('page', 'top-left'), size: { width: mm(TRIM_W) } }),
    text('title', '{titleText}', DISPLAY, 42, 800, 'red',
      at('page', 'top-left', INNER, RUG + 9)),
    text('subtitle', '{subtitle}', SANS, 13, 400, 'ink', at('#title', 'below', 0, 0.5)),
  ] } } };
const toc = {
  levels: [{ level: 1, fontFamily: DISPLAY, fontSize: pt(11), color: col('ink'),
    numberFontWeight: 700, numberColor: col('red'), numberWidth: mm(8), numberGap: mm(2),
    marginBottom: pt(2.5) }],
  pageNumber: { fontFamily: SANS, fontSize: pt(10), fontWeight: 700, color: col('red'),
    width: mm(5) },
  leader: { char: '. ', gap: mm(2) },
  subtitle: { enabled: true, attr: 'author', italic: false, fontFamily: SANS, fontSize: pt(9),
    color: col('muted') },
};
// #endregion

// #region art: ram's horns, the қошқар мүйіз of the felt rugs, from half circles
// A pair of horns is two half circles a side, radius 10 and then 6, on a stem; four pairs round
// a diamond make the tile, and a row of pairs, one up and one down, the border. The width of
// the stroke leaves as much ground as wool, so either colour can be read as the figure.
const horn = (side, sweep) => `M50 20 A10 10 0 0 ${sweep} ${50 + side * 20} 20 `
  + `A6 6 0 0 ${sweep} ${50 + side * 8} 20`;
const pair = `M50 40 V20 ${horn(-1, 0)} ${horn(1, 1)}`;
const horns = (colour, turn, w = 5.6) => `<path d="${pair}" transform="${turn}" fill="none" `
  + `stroke="${colour}" stroke-width="${w}" stroke-linecap="round" stroke-linejoin="round"/>`;
const shape = (d, colour, turn = '') => `<path d="${d}" fill="${colour}" transform="${turn}"/>`;
const tile = (x, y, ground, wool, spark) => `<g transform="translate(${x} ${y})">`
  + shape('M0 0H100V100H0Z', ground)
  + [0, 90, 180, 270].map((a) => horns(wool, `rotate(${a} 50 50)`)
    + shape('M0 0H17L0 17Z', spark, `rotate(${a} 50 50)`)).join('')
  + shape('M50 35L65 50L50 65L35 50Z', wool) + shape('M50 43L57 50L50 57L43 50Z', spark)
  + '</g>';
const UNIT = 50; // a pair of horns and its gap, in the border's units
const border = (n, colour, y) => Array.from({ length: n }, (_, i) => horns(colour, i % 2
  ? `translate(${i * UNIT - 25} ${y + 43}) scale(1 -1)`
  : `translate(${i * UNIT - 25} ${y - 3})`)).join('');
const teeth = (n, step, y, h, colour) => shape(Array.from({ length: n }, (_, i) =>
  `M${i * step} ${y}h${step}l${-step / 2} ${h}Z`).join(''), colour);
const svg = (w, h, body) => ({ width: w, height: h, markup: `<svg xmlns="http://www.w3.org/2000/`
  + `svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${body}</svg>` });
const { cream, gold } = palette;
const panel = (tone) => svg(600, 231.7, // the trim's width, 12 pairs of horns
  shape('M0 0H600V231.7H0Z', palette[tone]) + border(12, cream, 174)
  + shape('M0 160H600V163H0Z', cream) + teeth(48, 12.5, 222.7, 9, gold));
const rug = ['red', 'blue', 'green', 'ochre', 'blue', 'ochre', 'red', 'green'];
const ART = {
  rug: svg(400, 200, rug.map((tone, i) => tile((i % 4) * 100, Math.floor(i / 4) * 100,
    palette[tone], cream, gold)).join('')),
  strip: svg(1000, 60, shape('M0 0H1000V60H0Z', palette.red) + border(20, cream, 10)),
  ...Object.fromEntries(['red', 'blue', 'green', 'ochre']
    .map((tone) => [`panel-${tone}`, panel(tone)])),
};
// #endregion

const folio = (id, content, parity, edge, x, extra) => text(id, content, SANS, 9.5, 400, 'muted',
  at('page', edge, x, -11), { parity, ...extra });
const right = { align: 'right' };
const bold = { fontWeight: 700, color: col('red') };
const footer = { elements: [ // the title on the verso, the poet on the recto
  folio('even-folio', '{pageNumber}', 'even', 'bottom-left', OUTER, bold),
  folio('even-title', '{title}', 'even', 'bottom-left', OUTER + 9),
  folio('odd-author', '{attr.author}', 'odd', 'bottom-right', -OUTER - 9, right),
  folio('odd-folio', '{pageNumber}', 'odd', 'bottom-right', -OUTER, { ...right, ...bold }),
] };
const config = () => ({
  locale: LOCALE, // written out, never LANG: the book is Kazakh in every edition
  colorPalette, bodyText, footnotes, toc, footer, header: { elements: [] },
  page: { sizePreset: '60x90/16', dpi: 150, backgroundColor: col('cream'), margins: {
    top: mm(TOP), bottom: mm(22), left: mm(INNER), right: mm(OUTER), mirror: true } },
  layout: { layoutType: 'single' },
  headings: { fontFamily: DISPLAY, fontWeight: 800, color: col('red'), levels: [
    { level: 1, numberingTemplate: '{1:I}', advancedDesign: opener, marginBottom: pt(0),
      breakBefore: { enabled: true, parity: 'any' } }] },
  headingStyles: [cover, runOn],
  paragraphStyles: [{ id: 'colophon', fontFamily: SANS, fontSize: pt(8.2), lineHeight: pt(11),
    color: col('muted'), textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD),
    hyphenation: { locale: LANG, enabled: false } }],
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The anthology (content.text.<lang>.md), then its colophon in the edition's language.
const markdown = [String.raw`---
title: "Дала үні"
subtitle: "Алты тілдегі шағын антология"
---

# Дала үні {style="cover"}

:::toc

# Бірінші сөз {tone="red" author="Абай Құнанбайұлы" when="1845–1904" tongue="қазақша"}

Бұл жасқа келгенше жақсы өткіздік пе, жаман өткіздік пе, әйтеуір бірталай өмірімізді өткіздік: алыстық, жұлыстық, айтыстық, тартыстық — әурешілікті көре-көре келдік. Енді жер ортасы жасқа келдік: қажыдық, жалықтық; қылып жүрген ісіміздің баянсызын, байлаусызын көрдік, бәрі қоршылық[^1] екенін білдік. Ал, енді қалған өмірімізді қайтіп, не қылып өткіземіз? Соны таба алмай өзім де қайранмын.

Ел бағу? Жоқ, елге бағым жоқ. Бағусыз дертке ұшырайын деген кісі бақпаса, не албыртқан, көңілі басылмаған жастар бағамын демесе, бізді құдай сақтасын!

Мал бағу? Жоқ, баға алмаймын. Балалар өздеріне керегінше өздері бағар. Енді қартайғанда қызығын өзің түгел көре алмайтұғын, ұры, залым, тілемсектердің азығын бағып беремін деп, қалған аз ғана өмірімді қор қылар жайым жоқ.

Ғылым бағу? Жоқ, ғылым бағарға да ғылым сөзін сөйлесер адам жоқ. Білгеніңді кімге үйретерсің, білмегеніңді кімнен сұрарсың? Елсіз-күнсізде кездемені жайып салып, қолына кезін[^2] алып отырғанның не пайдасы бар? Мұңдасып шер тарқатысар кісі болмаған соң, ғылым өзі — бір тез қартайтатұғын күйік.

Софылық[^3] қылып, дін бағу? Жоқ, ол да болмайды, оған да тыныштық керек. Не көңілде, не көрген күніңде бір тыныштық жоқ, осы елге, осы жерде не қылған софылық?

Балаларды бағу? Жоқ, баға алмаймын. Бағар едім, қалайша бағудың мәнісін де білмеймін, не болсын деп бағам, қай елге қосайын, қай харекетке[^4] қосайын? Балаларымның өзіне ілгері өмірінің, білімінің пайдасын тыныштықпенен көрерлік орын тапқаным жоқ, қайда бар, не қыл дерімді біле алмай отырмын, не бол деп бағам? Оны да ермек қыла алмадым.

Ақыры ойладым: осы ойыма келген нәрселерді қағазға жаза берейін, ақ қағаз бен қара сияны ермек қылайын, кімде-кім ішінен керекті сөз тапса, жазып алсын, я оқысын, керегі жоқ десе, өз сөзім өзімдікі дедім де, ақыры осыған байладым, енді мұнан басқа ешбір жұмысым жоқ.

# Сегіз аяқ {style="run-on" author="Абай Құнанбайұлы" tongue="қазақша, үзінді"}

:::verse
Алыстан сермеп,
Жүректен тербеп,
  Шымырлап бойға жайылған.
Қиуадан шауып,
Қисынын тауып,
  Тағыны[^5] жетіп қайырған —
Толғауы тоқсан қызыл тіл,
Сөйлеймін десең өзің біл.
:::

# Үлгү ырлар {tone="blue" author="Тоқтоғұл Сатылғанов" when="1864–1933" tongue="қырғызша, үзінді"}

:::verse{lang=ky}
Дайранын көркү кемеде,
Баланын көркү энеде,
Акыл айтсаң тыңшабай,
Акмактын көркү жемеде[^6].

Бычактын көркү кынында,
Жылкынын сыны кулунда,
Азамат болсоң, эр жигит,
Ардактуу иштен корунба.

Шибердин[^7] көркү — мал менен,
Жылкынын көркү — жал менен.
Жылдыздай жанган кара көз,
Жигиттин көркү — жар менен.

Булбулдун көркү гүлдө бар,
Ырчынын көркү үндө бар,
Ак шумкар учса асманга,
Амалың болсо үндөп ал!
:::

# Туган тел {tone="green" author="Ғабдолла Тоқай" when="1886–1913" tongue="татарша"}

:::verse{lang=tt}
И туган тел, и матур тел, әткәм-әнкәмнең теле!
Дөньяда күп нәрсә белдем син туган тел аркылы.

Иң элек бу тел белән әнкәм бишектә[^8] көйләгән,
Аннары төннәр буе әбкәм[^9] хикәят сөйләгән.

И туган тел! Һәрвакытта ярдәмең берлән синең,
Кечкенәдән аңлашылган шатлыгым, кайгым минем.

И туган тел! Синдә булган иң элек кылган догам:
Ярлыкагыл[^10], дип, үзем һәм әткәм-әнкәмне, ходам!
:::

# Башҡорттарым, уҡыу кәрәк! {tone="ochre" author="Мифтахетдин Ақмолла" when="1831–1895" tongue="башқұртша, үзінді"}

:::verse{lang=ba}
Башҡорттарым, уҡыу кәрәк, уҡыу кәрәк!
Арабыҙҙа наҙандар күп, уҡыу һирәк.
Аңғыра айыуҙан Уралдағы ҡурҡҡандай,
Эй, туғандар, наҙанлыҡтан ҡурҡыу кәрәк!

Илтифат ит[^11]: уҡыуҙалыр шәрафәттәр,
Яһиллыҡтан[^12] килә ятыр ҙур афәттәр.
Уҡығандар күктә осор, һыуҙа йөҙөр,
Юҡтыр унда әүлиәлек, кәрамәттәр.

Уҡығанға был донъяла жәләл булыр,
Харам тигән күп шәйҙәр хәләл булыр.
Ырыҫ, дәүләт шишмәһен асам тиһәң,
Ғилем-һөнәр берҙән-бер әмәл булыр.

Алтыға берҙе ҡушып, һан ун булмай,
Сәғәтте алға бороп, төн көн булмай.
Белемлелек — арыҫландан көслө батыр,
Шуға атланмай, һинең төшөң һис өн булмай.
:::

# Миний нутаг {tone="blue" author="Дашдоржийн Нацагдорж" when="1906–1937" tongue="моңғолша, үзінді"}

:::verse{lang=mn}
Хэнтий, Хангай, Соёны өндөр сайхан нуруунууд
Хойд зүгийн чимэг болсон ой хөвч уулнууд
Мэнэн, Шарга, Номины өргөн их говиуд[^13]
Өмнө зүгийн манлай болсон элсэн манхан далайнууд
  Энэ бол миний төрсөн нутаг
  Монголын сайхан орон

Хэрлэн, Онон, Туулын тунгалаг ариун мөрнүүд
Хотол олны эм болсон горхи, булаг рашаанууд[^14]
Хөвсгөл, Увс, Буйрын гүн цэнхэр нуурууд
Хүн малын ундаа болсон тойром бүрд уснууд
  Энэ бол миний төрсөн нутаг
  Монголын сайхан орон

Орхон, Сэлэнгэ, Хөхийн онц сайхан голууд
Уурхай баялгийн охь болсон олон уул даваанууд
Хуучин хөшөө дурсгал, хот балгадын сууринууд
Хол газраа одсон харгуй дардан замууд
  Энэ бол миний төрсөн нутаг
  Монголын сайхан орон
:::

# Бӯи ҷӯи Мӯлиён {tone="red" author="Әбу Абдаллаһ Рудаки" when="858–941" tongue="тәжікше"}

:::verse{lang=tg}
Бӯи ҷӯи Мӯлиён[^15] ояд ҳаме,
Ёди ёри меҳрубон ояд ҳаме.

Реги Омуву дурушти роҳи ӯ,
Зери поям парниён[^16] ояд ҳаме.

Оби Ҷайҳун[^17] бо ҳама паҳноварӣ
Хинги[^18] моро то миён ояд ҳаме.

Эй Бухоро, шод бошу дер зӣ,
Мир наздат шодмон ояд ҳаме.

Мир моҳ асту Бухоро осмон,
Моҳ сӯи осмон ояд ҳаме.

Мир сарв асту Бухоро бӯстон,
Сарв сӯи бӯстон ояд ҳаме.
:::

[^1]: Қоршылық: қорлық.

[^2]: Кез: ескі ұзындық өлшемі.

[^3]: Софылық: сопылық.

[^4]: Харекет: әрекет, кәсіп.

[^5]: Тағы: жабайы аң.

[^6]: Жеме: сөгіс, кінә.

[^7]: Шибер: шүйгін шалғын.

[^8]: Бишек: бесік.

[^9]: Әбкәм: әжем.

[^10]: Ярлыкагыл: жарылқа.

[^11]: Илтифат ит: назар аудар.

[^12]: Яһиллыҡ: надандық.

[^13]: Говь: шөл дала.

[^14]: Рашаан: шипалы бұлақ.

[^15]: Мӯлиён: Бұхара маңындағы арық пен бақтар.

[^16]: Парниён: жібек мата.

[^17]: Ҷайҳун, Ому: Әмудария.

[^18]: Хинг: боз ат.
`, String.raw`:::paragraphs{style="colophon"}
Set in Alegreya, Alegreya Sans and Piazzolla (SIL OFL) · Texts: public domain, from wikisource.org and the editions credited
:::
`].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 use, with the cyrillic-ext files its letters need
  Alegreya: ['400'],
  'Alegreya Sans': ['400', '700'],
  Piazzolla: ['700', '800'],
};

// ─── 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 ───────────────────────────────────────────────────────────────────────
```

## よくあるつまずき

- 書体は一文字ずつ確かめてから選んでください。AlegreyaとPiazzollaはә ғ қ ң ө ұ ү һ ҙ ҫ ҡ ҳ ҷ ӣ ӯを持ちますが、Literata、Spectral、Old Standardには欠けるものがあります。文字は`kitCyrillicFonts`が読み込む`cyrillic-ext`ファイルにあります。
- `tone`のない見出しは絵柄を指さず、帯は空になります。どの詩にも四つのうち一つを付けてください。

## クレジット

- レシピ: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- テキスト: «Бірінші сөз» (1890): Abai Qunanbaiuly ([出典](https://abai.kz/post/12154)), パブリックドメイン
- テキスト: «Сегіз аяқ», first stanza: Abai Qunanbaiuly ([出典](https://wikisource.org/wiki/Сегіз_аяқ)), パブリックドメイン
- テキスト: «Үлгү ырлар», four stanzas of seven: Toktogul Satylganov ([出典](https://wikisource.org/wiki/Үлгү_ырлар)), パブリックドメイン
- テキスト: «Туган тел» (1909): Ğabdulla Tukay ([出典](https://wikisource.org/wiki/Туган_тел_(Тукай))), パブリックドメイン
- テキスト: «Башҡорттарым, уҡыу кәрәк!», four stanzas: Miftahetdin Akmulla ([出典](https://wikisource.org)), パブリックドメイン
- テキスト: «Миний нутаг», first three stanzas, spelling after several modern editions: Dashdorjiin Natsagdorj ([出典](https://mn.wikipedia.org/wiki/Миний_Нутаг)), パブリックドメイン
- テキスト: «Бӯи ҷӯи Мӯлиён» in Tajik Cyrillic: Rudaki ([出典](https://tg.wikipedia.org/wiki/Рӯдакӣ)), パブリックドメイン
- テキスト: The title, the glosses and the colophon: Postext Cookbook, オリジナル
- 書体: Alegreya (OFL-1.1), Alegreya Sans (OFL-1.1), Piazzolla (OFL-1.1)
- コード: MIT · サンプルの内容: MIT

## 関連レシピ

- [No. 209 · 十二のキリル文字言語を一つの書体見本に](https://postext.dev/ja/cookbook/cyrillic-specimen-twelve-languages.md): 4ページの書体見本。同じ条文を十二のキリル文字の言語で組み、それぞれの規則で分綴し、それぞれの字形で示します。 · 難易度 2 (中級) · カタログ
- [No. 030 · 著者名入りのアンソロジー](https://postext.dev/ja/cookbook/anthology-with-bylines.md): 歩くことをめぐる3編の随筆。見出しに著者・年・掲載誌を書き、章扉はその3つを、偶数ページの柱と目次は著者名を印字します。 · 難易度 2 (中級) · 小説・戯曲・文芸
- [No. 015 · 詩を1行ずつ組む](https://postext.dev/ja/cookbook/poetry-collection.md): 各詩は印刷されるとおりに書いた:::verseブロックです。1918年版のインデントは行頭の空白、折り返しはその行から2 emぶら下げ、連の間は空行で区切ります。 · 難易度 2 (中級) · 詩歌
