# 阿拜与草原五诗人：哈萨克语选集

> 八页的六语西里尔选集：一本哈萨克语的书，每种语言一首诗，页脚有注解，纹样取自毛毡地毯。

- HTML版本: https://postext.dev/zh/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)
- 在沙盒中打开: https://postext.dev/zh/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), [ja](https://postext.dev/ja/cookbook/abai-kazakh-anthology.md), [ar](https://postext.dev/ar/cookbook/abai-kazakh-anthology.md)

## 简单来说

一本小选集，以阿拜开篇，接着是吉尔吉斯语、鞑靼语、巴什基尔语、蒙古语和塔吉克语的诗。难词在页脚用哈萨克语解释，纹样来自草原的毛毡地毯。

## 成品一览

《Дала үні》（草原之声），一册145 × 215 mm、八页的小书。封面是由羊角纹瓷砖组成的毛毡地毯，下面是书名和目录。阿拜的《第一言》和《八行诗》的首节占一个对开页；吉尔吉斯语、鞑靼语、巴什基尔语、蒙古语和塔吉克语各占一页，上方色块用诗人的颜色，内有罗马数字、诗题、姓名、生卒年和语言。古词和外来词在页脚用哈萨克语作注。正文用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/zh/docs/cyrillic-layout.md#开始一本西里尔文书): locale设为'ru'、'uk'、'be'、'bg'、'sr'、'mk'、'kk'、'ky'、'tt'、'ba'、'tg'或'mn'时，书籍采用该语言的断词、题注、表题、脚注、数词、全张开本和书脊文字方向。
- [逐行排诗](https://postext.dev/zh/docs/document-format-directives.md#verse): :::verse按书写原样排诗：Markdown的一行就是一行诗，诗节之间空行，行首空格为缩进；过长的诗行以悬挂缩进转行，或在方括号后靠右排，分页时绝不与本行分开，短诗节可以保持完整。
- [脚注](https://postext.dev/zh/docs/document-format-notes-references.md#脚注): 用[^id]引用的注释，排在引用它的那一栏底部，或排在章末，按章或全书连续编号。

**还用到**

- [行末不分开的词语](https://postext.dev/zh/docs/cyrillic-layout.md#连在一起的词)
- [断词与文档语言](https://postext.dev/zh/docs/justification.md#支持的语言)
- [目录](https://postext.dev/zh/docs/configuration-notes-references.md#目录)
- [编号标题](https://postext.dev/zh/docs/configuration-headings.md#按级别覆盖)
- [设计过的章首页](https://postext.dev/zh/docs/configuration-headings.md#通栏与高级设计)
- [标题样式](https://postext.dev/zh/docs/configuration-styles.md#标题样式)
- [标题属性](https://postext.dev/zh/docs/document-format.md#标题属性)
- [页面设计中的图片](https://postext.dev/zh/docs/configuration-headers-footers.md#图像元素)
- [页面设计中的文字、线条和框](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚)
- [书眉与页码](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚)
- [封面、扉页和版权页](https://postext.dev/zh/docs/configuration-styles.md#标题样式)
- [文档元数据](https://postext.dev/zh/docs/document-format.md#前置元数据)
- [不编号的章](https://postext.dev/zh/docs/configuration-styles.md#标题样式)
- [对称页边距](https://postext.dev/zh/docs/configuration-page-layout.md#对称页边距)
- [缩进、对齐与段落间距](https://postext.dev/zh/docs/configuration-text.md#正文)
- [语义调色板](https://postext.dev/zh/docs/configuration-fonts-colors-viewers.md#调色板)
- [导出PDF](https://postext.dev/zh/docs/configuration-pdf-output.md#生成pdf)
- [纸张颜色](https://postext.dev/zh/docs/configuration-page-layout.md#页面)
- [段落样式](https://postext.dev/zh/docs/configuration-styles.md#段落样式)
- [嵌入PDF的字体](https://postext.dev/zh/docs/configuration-pdf-output.md#为什么需要字体提供函数)
- [作为资源的图和表](https://postext.dev/zh/docs/document-format-resources.md#资源)
- [分节书眉](https://postext.dev/zh/docs/configuration-styles.md#标题样式)

**配置一览**

- [`bodyText`](https://postext.dev/zh/docs/configuration-text.md#正文), [`colorPalette`](https://postext.dev/zh/docs/configuration-fonts-colors-viewers.md#调色板), [`footer`](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚), [`footnotes`](https://postext.dev/zh/docs/configuration-notes-references.md#脚注), [`header`](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚), [`headingStyles`](https://postext.dev/zh/docs/configuration-styles.md#标题样式), [`headings`](https://postext.dev/zh/docs/configuration-headings.md#标题), [`layout`](https://postext.dev/zh/docs/configuration-page-layout.md#版式), [`locale`](https://postext.dev/zh/docs/configuration-language.md#断词), [`page`](https://postext.dev/zh/docs/configuration-page-layout.md#页面), [`paragraphStyles`](https://postext.dev/zh/docs/configuration-styles.md#段落样式), [`toc`](https://postext.dev/zh/docs/configuration-notes-references.md#目录)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/zh/docs/configuration-programmatic-usage.md#排版前加载字体), [`decompressWoff2`](https://postext.dev/zh/docs/configuration-pdf-output.md#浏览器字体提供函数fontsource--woff2), [`registerResourceImage`](https://postext.dev/zh/docs/architecture.md#api接口), [`renderPageToCanvas`](https://postext.dev/zh/docs/configuration-programmatic-usage.md#把页面渲染为位图), [`renderToPdf`](https://postext.dev/zh/docs/configuration-pdf-output.md#生成pdf)

**字体**

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

## 做法

### 1 · 哈萨克语的书，另有五种语言的诗

代码就是上面的[简短回答](https://postext.dev/zh/cookbook/abai-kazakh-anthology.md#简短回答)。`locale: 'kk'`给全书定下[断词](https://postext.dev/zh/docs/cyrillic-layout.md#十二种语言的断词)、[连在一起的词](https://postext.dev/zh/docs/cyrillic-layout.md#连在一起的词)和[脚注](https://postext.dev/zh/docs/cyrillic-layout.md#按页编号的脚注)：脚注每页重新编号，缩进1.5 em。其他每首诗都是一个`:::verse{lang=ky}`，按本语言排字，并在PDF和HTML里标明语言。`align: 'center'`按最长一行居中，`keepStanzas: 8`让一节诗留在同一页，行首两个空格表示缩进。

### 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，共用一根柄。四对绕菱形旋转成瓷砖；一排角对上下交替成边饰。笔画和间隙宽度相近，就像shyrdak毡毯，两块毛毡互相嵌合。

## 完整食谱

一个文件，由食谱文件夹合成，示例文本和排版食谱的公共工具包都已内联；它自己排出页面。要运行它，把它放进空白页面的`<script type="module">`，或粘贴到新建CodePen的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/zh/cookbook/cyrillic-specimen-twelve-languages.md): 四页字样册：同一条文用十二种西里尔字母语言排出，各按自己的规则断词，并使用自己的本地字形。 · 难度 2 (中级) · 目录册
- [No. 030 · 带作者署名的文集](https://postext.dev/zh/cookbook/anthology-with-bylines.md): 三篇关于散步的随笔，标题带有作者、年份和刊物：章首页三项都印，左页书眉和目录印作者。 · 难度 2 (中级) · 小说、戏剧与文学散文
- [No. 015 · 逐行排诗](https://postext.dev/zh/cookbook/poetry-collection.md): 每首诗是一个照印刷样子书写的:::verse块：1918年版的缩进写成行首空格，转行比本行悬挂2 em，空行分隔诗节。 · 难度 2 (中级) · 诗歌
