# 按页编号脚注的俄语小说

> 《战争与和平》第一章，130 × 200毫米的版面：对话破折号，托尔斯泰自己译的法语用星号注在页脚，不该拆开的词始终连在一起，卷与部的序数用文字写出。

- HTML版本: https://postext.dev/zh/cookbook/russian-novel-notes-by-page
- 食谱 No. 205 · 字体与文字 · 难度 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/russian-novel-notes-by-page/en/p01.webp?v=fd022b38), [2](https://postext.dev/cookbook/russian-novel-notes-by-page/en/p02.webp?v=fd022b38), [3](https://postext.dev/cookbook/russian-novel-notes-by-page/en/p03.webp?v=fd022b38), [4](https://postext.dev/cookbook/russian-novel-notes-by-page/en/p04.webp?v=fd022b38), [5](https://postext.dev/cookbook/russian-novel-notes-by-page/en/p05.webp?v=fd022b38), [10](https://postext.dev/cookbook/russian-novel-notes-by-page/en/p10.webp?v=fd022b38)
- 在沙盒中打开: https://postext.dev/zh/sandbox#recipe=russian-novel-notes-by-page&lang=en (.postext: https://postext.dev/cookbook/russian-novel-notes-by-page/en/russian-novel-notes-by-page.postext)
- 最后更新: 2026-12-02
- 其他语言: [en](https://postext.dev/en/cookbook/russian-novel-notes-by-page.md), [es](https://postext.dev/es/cookbook/russian-novel-notes-by-page.md), [ca](https://postext.dev/ca/cookbook/russian-novel-notes-by-page.md), [de](https://postext.dev/de/cookbook/russian-novel-notes-by-page.md), [el](https://postext.dev/el/cookbook/russian-novel-notes-by-page.md), [fr](https://postext.dev/fr/cookbook/russian-novel-notes-by-page.md), [it](https://postext.dev/it/cookbook/russian-novel-notes-by-page.md), [pt](https://postext.dev/pt/cookbook/russian-novel-notes-by-page.md), [ru](https://postext.dev/ru/cookbook/russian-novel-notes-by-page.md), [ja](https://postext.dev/ja/cookbook/russian-novel-notes-by-page.md), [ar](https://postext.dev/ar/cookbook/russian-novel-notes-by-page.md)

## 简单来说

俄文《战争与和平》的开头，做成老式精装书的样子。法语对话在每页页脚译出，用星号标记，翻到下一页又从一个星号数起。

## 成品一览

《战争与和平》（*Война и мир*）第一卷第一部第一章全文，依据《全集》第9卷（1937年），排在130 × 200毫米的页面上，即俄国84 × 108/32开的成品尺寸。正文用Old Standard 10.5点，行距13.2点，每页34行，行长100毫米。安娜·帕夫洛夫娜和瓦西里公爵一半说法语，托尔斯泰自己的译文放在页脚，星号每页从头数起。标题用Oranienbaum，把卷和部写成*Том первый*、*Часть первая*。前面有黑与砖红两色的书名页，背面是用本版语言写的说明。

**这份食谱回答的问题:**

- 怎样排俄语小说，让星号脚注按页编号，不该拆开的词连在一起？
- 脚注怎么做？
- 怎样写对话破折号、段首的年份、价格和字面符号，而不被Markdown误读？
- 怎样设置书眉：左页放书名，右页放章名，页码在外侧？

## 简短回答

```js
// script.js, 行 45–62
// The language hyphenates by the Russian patterns, keeps a preposition with its word and a
// dash off the line start (bodyText.wordTies 'avoid'), holds the space after a dialogue's
// opening dash at its own width, counts the notes again on every page and indents their
// first line. The indents below are the Russian ones: 1,5 em, the first paragraph included.
const LOCALE = 'ru';
const bodyText = { // config().bodyText
  fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  firstLineIndent: em(1.5), indentAfterHeading: true, // the default leaves the first one flush
  hyphenation: { leftMin: 2, rightMin: 2 }, maxWordSpacing: 1.6, minWordSpacing: 0.8,
  wordTies: 'avoid', // the default in these languages
  maxJustifyTracking: 15, // room for the ties in a 100 mm line
};
const footnotes = { // config().footnotes: *, **, ***, again from * on the next page
  numberFormat: 'symbols', // locale 'ru' gives symbols: ['*'] and numbering: 'page'
  fontSize: pt(8.6), lineHeight: pt(10.6),
  separator: { width: 0.25, lineWidth: pt(0.4), color: col('ink') },
};
```

## 用料

**讲解**

- [以西里尔字母语言为文档语言](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/cyrillic-layout.md#连在一起的词): bodyText.wordTies按文档语言的规则，让短词与后面的词、名字缩写与姓氏、数字与单位不分开，破折号不出现在行首。
- [脚注](https://postext.dev/zh/docs/document-format-notes-references.md#脚注): 用[^id]引用的注释，排在引用它的那一栏底部，或排在章末，按章或全书连续编号。

**还用到**

- [断词与文档语言](https://postext.dev/zh/docs/justification.md#支持的语言)
- [最优断行（Knuth–Plass）](https://postext.dev/zh/docs/justification.md#knuth-plass通观整个段落)
- [字符样式](https://postext.dev/zh/docs/document-format-inline.md#字符样式)
- [行内反方向文字](https://postext.dev/zh/docs/arabic-layout.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-page-layout.md#页面尺寸预设)
- [书眉与页码](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚)
- [对称页边距](https://postext.dev/zh/docs/configuration-page-layout.md#对称页边距)
- [缩进、对齐与段落间距](https://postext.dev/zh/docs/configuration-text.md#正文)
- [段落样式](https://postext.dev/zh/docs/configuration-styles.md#段落样式)
- [文档元数据](https://postext.dev/zh/docs/document-format.md#前置元数据)
- [语义调色板](https://postext.dev/zh/docs/configuration-fonts-colors-viewers.md#调色板)
- [导出PDF](https://postext.dev/zh/docs/configuration-pdf-output.md#生成pdf)
- [嵌入PDF的字体](https://postext.dev/zh/docs/configuration-pdf-output.md#为什么需要字体提供函数)
- [纸张颜色](https://postext.dev/zh/docs/configuration-page-layout.md#页面)
- [按页面角色显示书眉](https://postext.dev/zh/docs/configuration-headers-footers.md#文本元素)
- [分节书眉](https://postext.dev/zh/docs/configuration-styles.md#标题样式)
- [不编号的章](https://postext.dev/zh/docs/configuration-styles.md#标题样式)

**配置一览**

- [`bodyText`](https://postext.dev/zh/docs/configuration-text.md#正文), [`characterStyles`](https://postext.dev/zh/docs/configuration-styles.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#段落样式)

**API**

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

**字体**

- Old Standard TT (OFL-1.1), Oranienbaum (OFL-1.1)

## 做法

### 1 · 设定语言和星号

代码见上面的[简短回答](https://postext.dev/zh/cookbook/russian-novel-notes-by-page.md#简短回答)。`locale: 'ru'`按俄语规则断词，让前置词、数字和破折号[与所属的词相连](https://postext.dev/zh/docs/cyrillic-layout.md#连在一起的词)，并且[按页给脚注编号](https://postext.dev/zh/docs/cyrillic-layout.md#按页编号的脚注)。`numberFormat: 'symbols'`把编号换成星号。注号按俄语习惯输入：在句号、逗号之前，在问号之后；引擎不会让句号掉到下一行。100毫米的行长对这么多的相连规则来说偏窄，所以给一点字距。每段法语放在`:ltr[…]{lang=fr}`里，按法语规则断词。

### 2 · 由纸张得出页面

```js
// script.js, 行 36–41
const [TOP, INNER, OUTER, LINES] = [22, 15, 15, 34];
const page = {
  sizePreset: '84x108/32', dpi: 150, backgroundColor: col('paper'), // the sheet of GOST 5773
  margins: { top: mm(TOP), bottom: mm(200 - TOP - LINES * LINE), // 130 × 200 mm
    left: mm(INNER), right: mm(OUTER), mirror: true },
};
```

`sizePreset: '84x108/32'`就是[GOST 5773](https://postext.dev/zh/docs/cyrillic-layout.md#开本与书脊)的130 × 200毫米。下边距由34行算出，`mirror`在偶数页把左右边距对调。

### 3 · 疏排一个词，给元音加重音

```js
// script.js, 行 66–68
// The edition's italics (грипп, рап) are spaced here, as Russian books set an emphasis
// before italics took over. A stress is U+0301 after its vowel: что́, сто́ите.
const characterStyles = [{ id: 'razryadka', name: 'Разрядка', letterSpacing: em(0.16) }];
```

当时的俄文书把词疏排以示强调。[разрядка](https://postext.dev/zh/docs/cyrillic-layout.md#强调重音与诗歌)是带`letterSpacing`的字符样式，这里用在原版排成斜体的两个词上：*грипп*和*рап*。重音是元音后面的U+0301，如*что́*、*сто́ит*。

### 4 · 用文字写卷数和部数

```js
// script.js, 行 72–90
// The Markdown has # Том, ## Часть and ### Глава; 'replace' prints the number alone. Том is
// masculine, so its ordinal asks for -masculine; Часть is feminine, the Russian default.
const level = (n, numberingTemplate, design, minHeight, extra = {}) => ({ level: n,
  numberingTemplate, numberPosition: 'replace', marginTop: pt(0), marginBottom: pt(0),
  breakBefore: { enabled: false },
  advancedDesign: { enabled: true, minHeight: pt(minHeight * LEAD), slot: { elements: design } },
  ...extra });
const levels = [
  level(1, 'Том {1:ordinal-masculine}', [
    text('volume', '{titleText}', DISPLAY, 17, at('container', 'top', 0, 2.2 * LINE),
      caps(2.4, 'red')),
    { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(0.6), color: col('red'),
      placement: { ...at('container', 'top', 0, 4.5 * LINE), size: { width: mm(18) } } },
  ], 5, { breakBefore: { enabled: true, parity: 'odd' } }),
  level(2, 'Часть {2:ordinal}', [text('part', '{titleText}', DISPLAY, 11.5,
    at('container', 'top', 0, 0.4 * LINE), caps(1.6))], 2),
  level(3, '{3:upper-roman}', [text('chapter', '{titleText}', DISPLAY, 13,
    at('container', 'top', 0, 0.9 * LINE), {})], 3),
];
```

[`{1:ordinal-masculine}`](https://postext.dev/zh/docs/cyrillic-layout.md#用字母和文字编号)和`{2:ordinal}`按文档语言把计数写成文字，`numberPosition: 'replace'`用它取代标题印出。Markdown里只有`# Том`和`## Часть`，编辑不必改写数字。

### 5 · 书眉

```js
// script.js, 行 94–106
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: TEXT, fontSize: pt(9), color: col('ink'),
  placement: at('page', edge, x, 13), ...extra });
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER),
  head('verso-author', '{author}', 'even', 'top', 0, { italic: true }),
  head('recto-title', '{title}. {chapterTitle}', 'odd', 'top', 0, { italic: true }),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER),
  { kind: 'rule', id: 'under', direction: 'horizontal', thickness: pt(0.4), color: col('ink'),
    pages: 'body', placement: { ...at('page', 'top', 0, 18), size: { width: mm(100) } } },
] };
const footer = { elements: [{ ...head('drop', '{pageNumber}', 'all', 'bottom', 0),
  pages: 'opener', placement: at('page', 'bottom', 0, -11) }] };
```

作者名在偶数页，书名和卷数在奇数页，都是斜体，下面一条细线。`pages: 'body'`让开篇没有书眉，页码落在下方。

### 6 · 双色书名页

```js
// script.js, 行 110–130
const front = (id, elements, furniture = [], extra = {}) => ({ id, numbered: false,
  runningChapter: false, breakBefore: { enabled: true, parity: 'any' }, numberPosition: 'before',
  header: { elements: furniture }, footer: { elements: [] },
  advancedDesign: { enabled: true, slot: { elements }, ...extra } });
const frame = (id, inset, width) => ({ kind: 'box', id,
  style: { borderColor: col('red'), borderWidth: pt(width) },
  placement: { ...at('page', 'top-left', inset, inset),
    size: { width: mm(130 - 2 * inset), height: mm(200 - 2 * inset) } } });
const headingStyles = [
  front('title-page', [
    text('author', '{attr.first}', DISPLAY, 17, at('page', 'top', 0, 30), caps(1.6)),
    text('title', '{titleText}', DISPLAY, 40, { ...at('page', 'top', 0, 66),
      size: { width: mm(98) } }, { ...caps(0.6, 'red'), lineHeight: 1.1 }),
    text('subtitle', '{subtitle}', TEXT, 11, at('page', 'top', 0, 92), { italic: true }),
    text('imprint', '{attr.imprint}', DISPLAY, 10, at('page', 'bottom', 0, -29), caps(1.6)),
    text('year', '{attr.year}', DISPLAY, 10, at('page', 'bottom', 0, -23)),
  ], [frame('outer', 10, 2.2), frame('inner', 12.2, 0.5)]), // the section's header: whole page
  // The note sits low on the verso of the title page, under its label.
  front('note-page', [text('label', '{titleText}', DISPLAY, 10,
    at('container', 'top', 0, 17 * LINE), caps(1.2, 'red'))], [], { minHeight: pt(19 * LEAD) }),
];
```

边框放在该节的页眉槽里，才能覆盖整页；文字来自标题和它的属性。

## 完整食谱

一个文件，由食谱文件夹合成，示例文本和排版食谱的公共工具包都已内联；它自己排出页面。要运行它，把它放进空白页面的`<script type="module">`，或粘贴到新建CodePen的JS面板里（设为模块）。它从esm.sh导入postext，不需要安装或构建。

- 食谱文件夹: https://github.com/drnachio/postext/tree/main/cookbook/russian-novel-notes-by-page

### script.js

```js
// ═══ Postext Cookbook · Nº 205 · A Russian novel with its notes counted by page ═══════
// https://postext.dev/en/cookbook/russian-novel-notes-by-page
// Code: MIT · Text: L. Tolstoy, Война и мир, I, I, I, PSS vol. 9, 1937 (PD, ru.wikisource)
// Fonts: Old Standard TT, Oranienbaum (SIL OFL 1.1) · Needs postext ≥ 1.100.0
import { buildDocumentWithFonts, renderPageToCanvas } from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the note on the text ('en' | 'es' | 'ru')
const RECIPE = 'russian-novel-notes-by-page';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// Black on a warm paper and the brick red of a title page printed in two inks, as the
// Leningrad presses of the thirties set their classics.
const palette = {
  ink: '#1e1a17', // text, the running heads, the folios
  red: '#a3301f', // the title, the frame, the volume
  muted: '#675e55', // the note on the text, the colophon
  paper: '#faf5ea', // a cream book paper
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'red (defaults)', value: { hex: palette.red, model: 'hex' } },
];
const [TEXT, DISPLAY] = ['Old Standard TT', 'Oranienbaum']; // обыкновенная; a display antiqua
const [BODY, LEAD] = [10.5, 13.2]; // pt
const LINE = (LEAD * 25.4) / 72; // mm: one line, 4.66
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const text = (id, content, fontFamily, size, placement, extra = {}) => ({ kind: 'text', id,
  content, fontFamily, fontSize: pt(size), color: col('ink'), align: 'center',
  overflow: 'wrap', placement, ...extra });
const caps = (tracking, color = 'ink') => ({ textTransform: 'uppercase',
  letterSpacing: pt(tracking), color: col(color) });

// #region page: 84 × 108/32, 130 × 200 mm trimmed; 34 lines of 13.2 pt, 100 mm wide
const [TOP, INNER, OUTER, LINES] = [22, 15, 15, 34];
const page = {
  sizePreset: '84x108/32', dpi: 150, backgroundColor: col('paper'), // the sheet of GOST 5773
  margins: { top: mm(TOP), bottom: mm(200 - TOP - LINES * LINE), // 130 × 200 mm
    left: mm(INNER), right: mm(OUTER), mirror: true },
};
// #endregion

// #region answer: what locale 'ru' brings, and the notes set with asterisks
// The language hyphenates by the Russian patterns, keeps a preposition with its word and a
// dash off the line start (bodyText.wordTies 'avoid'), holds the space after a dialogue's
// opening dash at its own width, counts the notes again on every page and indents their
// first line. The indents below are the Russian ones: 1,5 em, the first paragraph included.
const LOCALE = 'ru';
const bodyText = { // config().bodyText
  fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  firstLineIndent: em(1.5), indentAfterHeading: true, // the default leaves the first one flush
  hyphenation: { leftMin: 2, rightMin: 2 }, maxWordSpacing: 1.6, minWordSpacing: 0.8,
  wordTies: 'avoid', // the default in these languages
  maxJustifyTracking: 15, // room for the ties in a 100 mm line
};
const footnotes = { // config().footnotes: *, **, ***, again from * on the next page
  numberFormat: 'symbols', // locale 'ru' gives symbols: ['*'] and numbering: 'page'
  fontSize: pt(8.6), lineHeight: pt(10.6),
  separator: { width: 0.25, lineWidth: pt(0.4), color: col('ink') },
};
// #endregion

// #region stress: разрядка as a character style; stress marks are typed
// The edition's italics (грипп, рап) are spaced here, as Russian books set an emphasis
// before italics took over. A stress is U+0301 after its vowel: что́, сто́ите.
const characterStyles = [{ id: 'razryadka', name: 'Разрядка', letterSpacing: em(0.16) }];
// #endregion

// #region volume: Том первый, Часть первая, I, from the counters of three levels
// The Markdown has # Том, ## Часть and ### Глава; 'replace' prints the number alone. Том is
// masculine, so its ordinal asks for -masculine; Часть is feminine, the Russian default.
const level = (n, numberingTemplate, design, minHeight, extra = {}) => ({ level: n,
  numberingTemplate, numberPosition: 'replace', marginTop: pt(0), marginBottom: pt(0),
  breakBefore: { enabled: false },
  advancedDesign: { enabled: true, minHeight: pt(minHeight * LEAD), slot: { elements: design } },
  ...extra });
const levels = [
  level(1, 'Том {1:ordinal-masculine}', [
    text('volume', '{titleText}', DISPLAY, 17, at('container', 'top', 0, 2.2 * LINE),
      caps(2.4, 'red')),
    { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(0.6), color: col('red'),
      placement: { ...at('container', 'top', 0, 4.5 * LINE), size: { width: mm(18) } } },
  ], 5, { breakBefore: { enabled: true, parity: 'odd' } }),
  level(2, 'Часть {2:ordinal}', [text('part', '{titleText}', DISPLAY, 11.5,
    at('container', 'top', 0, 0.4 * LINE), caps(1.6))], 2),
  level(3, '{3:upper-roman}', [text('chapter', '{titleText}', DISPLAY, 13,
    at('container', 'top', 0, 0.9 * LINE), {})], 3),
];
// #endregion

// #region heads: the author over the versos, the novel and its volume over the rectos
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: TEXT, fontSize: pt(9), color: col('ink'),
  placement: at('page', edge, x, 13), ...extra });
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER),
  head('verso-author', '{author}', 'even', 'top', 0, { italic: true }),
  head('recto-title', '{title}. {chapterTitle}', 'odd', 'top', 0, { italic: true }),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER),
  { kind: 'rule', id: 'under', direction: 'horizontal', thickness: pt(0.4), color: col('ink'),
    pages: 'body', placement: { ...at('page', 'top', 0, 18), size: { width: mm(100) } } },
] };
const footer = { elements: [{ ...head('drop', '{pageNumber}', 'all', 'bottom', 0),
  pages: 'opener', placement: at('page', 'bottom', 0, -11) }] };
// #endregion

// #region front: the title page in two inks and, behind it, the note on the text
const front = (id, elements, furniture = [], extra = {}) => ({ id, numbered: false,
  runningChapter: false, breakBefore: { enabled: true, parity: 'any' }, numberPosition: 'before',
  header: { elements: furniture }, footer: { elements: [] },
  advancedDesign: { enabled: true, slot: { elements }, ...extra } });
const frame = (id, inset, width) => ({ kind: 'box', id,
  style: { borderColor: col('red'), borderWidth: pt(width) },
  placement: { ...at('page', 'top-left', inset, inset),
    size: { width: mm(130 - 2 * inset), height: mm(200 - 2 * inset) } } });
const headingStyles = [
  front('title-page', [
    text('author', '{attr.first}', DISPLAY, 17, at('page', 'top', 0, 30), caps(1.6)),
    text('title', '{titleText}', DISPLAY, 40, { ...at('page', 'top', 0, 66),
      size: { width: mm(98) } }, { ...caps(0.6, 'red'), lineHeight: 1.1 }),
    text('subtitle', '{subtitle}', TEXT, 11, at('page', 'top', 0, 92), { italic: true }),
    text('imprint', '{attr.imprint}', DISPLAY, 10, at('page', 'bottom', 0, -29), caps(1.6)),
    text('year', '{attr.year}', DISPLAY, 10, at('page', 'bottom', 0, -23)),
  ], [frame('outer', 10, 2.2), frame('inner', 12.2, 0.5)]), // the section's header: whole page
  // The note sits low on the verso of the title page, under its label.
  front('note-page', [text('label', '{titleText}', DISPLAY, 10,
    at('container', 'top', 0, 17 * LINE), caps(1.2, 'red'))], [], { minHeight: pt(19 * LEAD) }),
];
// #endregion

const paragraphStyles = [
  // The note is in the edition's language, hyphenated with that language's patterns.
  { id: 'note', fontSize: pt(9.5), lineHeight: pt(12.2), color: col('muted'),
    italicColor: col('muted'), firstLineIndent: em(1.5), hyphenation: { locale: LANG } },
  { id: 'colophon', fontSize: pt(8), lineHeight: pt(10.5), color: col('muted'),
    italicColor: col('muted'), textAlign: 'center', firstLineIndent: pt(0),
    marginTop: pt(LEAD), hyphenation: { enabled: false } },
];

const config = () => ({
  locale: LOCALE, // written out, never LANG: the novel is Russian in every edition
  colorPalette, page, bodyText, footnotes, characterStyles, paragraphStyles, headingStyles,
  header, footer,
  layout: { layoutType: 'single' }, // the default is two columns
  headings: { fontFamily: DISPLAY, fontWeight: 400, levels },
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The title page and the note (content.<lang>.md), then the chapter (content.text.en.md).
const markdown = [String.raw`---
title: "Война и мир"
subtitle: "Роман в четырех томах"
author: "Л. Н. Толстой"
---

# Война и мир {style="title-page" first="Лев Толстой" imprint="Postext" year="2026"}

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

:::paragraphs{style="note"}
Book I, part I, chapter I of *War and Peace* is set from the Complete Works of L. N. Tolstoy (volume 9, 1937) in the transcription of Russian Wikisource. The translations of the French at the foot of the page are Tolstoy’s own; where two of them belong to one speech, they are joined by an ellipsis. Slips of the transcription are corrected, among them Latin “pan” for “рап”. Words the edition sets in italics are spaced here; the letter ё appears only where the edition prints it.
:::

:::paragraphs{style="colophon"}
Set in Old Standard and Oranienbaum (SIL OFL)\
Text: L. N. Tolstoy, public domain, from Wikisource
:::
`, String.raw`# Том

## Часть

### Глава

— :ltr[Eh bien, mon prince. Gênes et Lucques ne sont plus que des apanages, des]{lang=fr} поместья, :ltr[de la famille Buonaparte. Non, je vous préviens, que si vous ne me dites pas, que nous avons la guerre, si vous vous permettez encore de pallier toutes les infamies, toutes les atrocités de cet Antichrist]{lang=fr} (:ltr[ma parole, j’y crois]{lang=fr}) — :ltr[je ne vous connais plus, vous n’êtes plus mon ami, vous n’êtes plus]{lang=fr} мой верный раб, :ltr[comme vous dites]{lang=fr}[^1]. Ну, здравствуйте, здравствуйте. :ltr[Je vois que je vous fais peur]{lang=fr}[^2], садитесь и рассказывайте.

Так говорила в июле 1805 года известная Анна Павловна Шерер, фрейлина и приближенная императрицы Марии Феодоровны, встречая важного и чиновного князя Василия, первого приехавшего на ее вечер. Анна Павловна кашляла несколько дней, у нее был :span[грипп]{style="razryadka"}, как она говорила (:span[грипп]{style="razryadka"} был тогда новое слово, употреблявшееся только редкими). В записочках, разосланных утром с красным лакеем, было написано без различия во всех:

«:ltr[Si vous n’avez rien de mieux à faire, M. le comte]{lang=fr} (или :ltr[mon prince]{lang=fr}), :ltr[et si la perspective de passer la soirée chez une pauvre malade ne vous effraye pas trop, je serai charmée de vous voir chez moi entre 7 et 10 heures. Annette Scherer]{lang=fr}»[^3].

— :ltr[Dieu, quelle virulente sortie]{lang=fr}![^4] — отвечал, нисколько не смутясь такою встречей, вошедший князь, в придворном, шитом мундире, в чулках, башмаках, и звездах, с светлым выражением плоского лица.

Он говорил на том изысканном французском языке, на котором не только говорили, но и думали наши деды, и с теми тихими, покровительственными интонациями, которые свойственны состаревшемуся в свете и при дворе значительному человеку. Он подошел к Анне Павловне, поцеловал ее руку, подставив ей свою надушенную и сияющую лысину, и покойно уселся на диване.

— :ltr[Avant tout dites-moi, comment vous allez, chère amie]{lang=fr}?[^5] Успокойте меня, — сказал он, не изменяя голоса и тоном, в котором из-за приличия и участия просвечивало равнодушие и даже насмешка.

— Как можно быть здоровой… когда нравственно страдаешь? Разве можно, имея чувство, оставаться спокойною в наше время? — сказала Анна Павловна. — Вы весь вечер у меня, надеюсь?

— А праздник английского посланника? Нынче середа. Мне надо показаться там, — сказал князь. — Дочь заедет за мной и повезет меня.

— Я думала, что нынешний праздник отменен. :ltr[Je vous avoue que toutes ces fêtes et tous ces feux d’artifice commencent à devenir insipides]{lang=fr}[^6].

— Ежели бы знали, что вы этого хотите, праздник бы отменили, — сказал князь, по привычке, как заведенные часы, говоря вещи, которым он и не хотел, чтобы верили.

— :ltr[Ne me tourmentez pas. Eh bien, qu’a-t-on décidé par rapport à la dépêche de Novosilzoff? Vous savez tout]{lang=fr}[^7].

— Как вам сказать? — сказал князь холодным, скучающим тоном. — :ltr[Qu’a-t-on décidé? On a décidé que Buonaparte a brûlé ses vaisseaux, et je crois que nous sommes en train de brûler les nôtres]{lang=fr}[^8].

Князь Василий говорил всегда лениво, как актер говорит роль старой пиесы. Анна Павловна Шерер, напротив, несмотря на свои сорок лет, была преисполнена оживления и порывов.

Быть энтузиасткой сделалось ее общественным положением, и иногда, когда ей даже того не хотелось, она, чтобы не обмануть ожиданий людей, знавших ее, делалась энтузиасткой. Сдержанная улыбка, игравшая постоянно на лице Анны Павловны, хотя и не шла к ее отжившим чертам, выражала, как у избалованных детей, постоянное сознание своего милого недостатка, от которого она не хочет, не может и не находит нужным исправляться.

В середине разговора про политические действия Анна Павловна разгорячилась.

— Ах, не говорите мне про Австрию! Я ничего не понимаю, может быть, но Австрия никогда не хотела и не хочет войны. Она предает нас. Россия одна должна быть спасительницей Европы. Наш благодетель знает свое высокое призвание и будет верен ему. Вот одно, во что́ я верю. Нашему доброму и чудному государю предстоит величайшая роль в мире, и он так добродетелен и хорош, что Бог не оставит его, и он исполнит свое призвание задавить гидру революции, которая теперь еще ужаснее в лице этого убийцы и злодея. Мы одни должны искупить кровь праведника. На кого нам надеяться, я вас спрашиваю?.. Англия с своим коммерческим духом не поймет и не может понять всю высоту души императора Александра. Она отказалась очистить Мальту. Она хочет видеть, ищет заднюю мысль наших действий. Что́ они сказали Новосильцову?.. Ничего. Они не поняли, они не могут понять самоотвержения нашего императора, который ничего не хочет для себя и всё хочет для блага мира. И что́ они обещали? Ничего. И что́ обещали, и того не будет! Пруссия уже объявила, что Бонапарте непобедим и что вся Европа ничего не может против него… И я не верю ни в одном слове ни Гарденбергу, ни Гаугвицу. :ltr[Cette fameuse neutralité prussienne, ce n’est qu’un piège]{lang=fr}[^9]. Я верю в одного Бога и в высокую судьбу нашего милого императора. Он спасет Европу!.. — Она вдруг остановилась с улыбкой насмешки над своею горячностью.

— Я думаю, — сказал князь улыбаясь, — что ежели бы вас послали вместо нашего милого Винценгероде, вы бы взяли приступом согласие прусского короля. Вы так красноречивы. Вы дадите мне чаю?

— Сейчас. :ltr[A propos]{lang=fr}, — прибавила она, опять успокоиваясь, — нынче у меня два очень интересные человека, :ltr[le vicomte de Mortemart, il est allié aux Montmorency par les Rohans]{lang=fr}, одна из лучших фамилий Франции. Это один из хороших эмигрантов, из настоящих. И потом :ltr[l’abbé Morio]{lang=fr}[^10]: вы знаете этот глубокий ум? Он был принят государем. Вы знаете?

— А! Я очень рад буду, — сказал князь. — Скажите, — прибавил он, как будто только что вспомнив что-то и особенно-небрежно, тогда как то, о чем он спрашивал, было главною целью его посещения, — правда, что :ltr[l’impératrice-mère]{lang=fr} желает назначения барона Функе первым секретарем в Вену? :ltr[C’est un pauvre sire, ce baron, à ce qu’il paraît]{lang=fr}[^11]. — Князь Василий желал определить сына на это место, которое через императрицу Марию Феодоровну старались доставить барону.

Анна Павловна почти закрыла глаза в знак того, что ни она, ни кто другой не могут судить про то, что́ угодно или нравится императрице.

— :ltr[Monsieur le baron de Funke a été recommandé à l’impératrice-mère par sa sœur]{lang=fr}[^12], — только сказала она грустным, сухим тоном. В то время, как Анна Павловна назвала императрицу, лицо ее вдруг представило глубокое и искреннее выражение преданности и уважения, соединенное с грустью, что́ с ней бывало каждый раз, когда она в разговоре упоминала о своей высокой покровительнице. Она сказала, что ее величество изволила оказать барону Функе :ltr[beaucoup d’estime]{lang=fr}[^13], и опять взгляд ее подернулся грустью.

Князь равнодушно замолк. Анна Павловна, с свойственною ей придворною и женскою ловкостью и быстротою такта, захотела и щелконуть князя за то, что он дерзнул так отозваться о лице, рекомендованном императрице, и в то же время утешить его.

— :ltr[Mais à propos de votre famille]{lang=fr}, — сказала она, — знаете ли, что ваша дочь с тех пор, как выезжает, :ltr[fait les délices de tout le monde. On la trouve belle, comme le jour]{lang=fr}[^14].

Князь наклонился в знак уважения и признательности.

— Я часто думаю, — продолжала Анна Павловна после минутного молчания, придвигаясь к князю и ласково улыбаясь ему, как будто выказывая этим, что политические и светские разговоры кончены и теперь начинается задушевный: — я часто думаю, как иногда несправедливо распределяется счастие жизни. За что́ вам судьба дала таких двух славных детей (исключая Анатоля, вашего меньшого, я его не люблю, — вставила она безапелляционно, приподняв брови) — таких прелестных детей? А вы, право, менее всех цените их и потому их не сто́ите.

И она улыбнулась своею восторженною улыбкой.

— :ltr[Que voulez-vous? Lafater aurait dit que je n’ai pas la bosse de la paternité]{lang=fr}[^15], — сказал князь.

— Перестаньте шутить. Я хотела серьезно поговорить с вами. Знаете, я недовольна вашим меньшим сыном. Между нами будь сказано (лицо ее приняло грустное выражение), о нем говорили у ее величества и жалеют вас…

Князь не отвечал, но она молча, значительно глядя на него, ждала ответа. Князь Василий поморщился.

— Что́ ж мне делать? — сказал он наконец. — Вы знаете, я сделал для их воспитания все, что́ может отец, и оба вышли :ltr[des imbéciles]{lang=fr}[^16]. Ипполит, по крайней мере, покойный дурак, а Анатоль — беспокойный. Вот одно различие, — сказал он, улыбаясь более неестественно и одушевленно, чем обыкновенно, и при этом особенно резко выказывая в сложившихся около его рта морщинах что-то неожиданно-грубое и неприятное.

— И зачем родятся дети у таких людей, как вы? Ежели бы вы не были отец, я бы ни в чем не могла упрекнуть вас, — сказала Анна Павловна, задумчиво поднимая глаза.

— :ltr[Je suis votre]{lang=fr} верный раб, :ltr[et à vous seule je puis l’avouer]{lang=fr}. Мои дети — :ltr[ce sont les entraves de mon existence]{lang=fr}. Это мой крест. Я так себе объясняю. :ltr[Que voulez-vous]{lang=fr}?..[^17] — Он помолчал, выражая жестом свою покорность жестокой судьбе.

Анна Павловна задумалась.

— Вы никогда не думали о том, чтобы женить вашего блудного сына Анатоля. Говорят, — сказала она, — что старые девицы :ltr[ont la manie des mariages]{lang=fr}. Я еще не чувствую за собою этой слабости, но у меня есть одна :ltr[petite personne]{lang=fr}, которая очень несчастлива с отцом, :ltr[une parente à nous, une princesse]{lang=fr}[^18] Болконская. — Князь Василий не отвечал, хотя с свойственною светским людям быстротой соображения и памяти показал движением головы, что он принял к соображению эти сведения.

— Нет, вы знаете ли, что этот Анатоль мне сто́ит 40 000 в год, — сказал он, видимо, не в силах удерживать печальный ход своих мыслей. Он помолчал.

— Что́ будет через пять лет, если это пойдет так? :ltr[Voilà l’avantage d’être père]{lang=fr}[^19]. Она богата, ваша княжна?

— Отец очень богат и скуп. Он живет в деревне. Знаете, этот известный князь Болконский, отставленный еще при покойном императоре и прозванный «прусским королем». Он очень умный человек, но со странностями и тяжелый. :ltr[La pauvre petite est malheureuse, comme les pierres]{lang=fr}[^20]. У нее брат, вот что́ недавно женился на Lise Мейнен, адъютант Кутузова. Он будет нынче у меня.

— :ltr[Ecoutez, chère Annette]{lang=fr}[^21], — сказал князь, взяв вдруг свою собеседницу за руку и пригибая ее почему-то книзу, — :ltr[Arrangez-moi cette affaire et je suis votre]{lang=fr} вернейший раб :ltr[à tout jamais]{lang=fr} (:span[рап]{style="razryadka"}, :ltr[comme mon]{lang=fr} староста :ltr[m’écrit des]{lang=fr}[^22] донесенья: покой-ер-п). Она хорошей фамилии и богата. Всё, что́ мне нужно.

И он с теми свободными и фамильярными, грациозными движениями, которые его отличали, взял за руку фрейлину, поцеловал ее и, поцеловав, помахал фрейлинскою рукой, развалившись на креслах и глядя в сторону.

— :ltr[Attendez]{lang=fr}, — сказала Анна Павловна, соображая. — Я нынче же поговорю Lise (:ltr[la femme du jeune]{lang=fr} Болконский)[^23]. И, может быть, это уладится. :ltr[Ce sera dans votre famille, que je ferai mon apprentissage de vieille fille]{lang=fr}[^24].

[^1]: Ну, князь, Генуя и Лукка поместья фамилии Бонапарте. Нет, я вам вперед говорю, если вы мне не скажете, что у нас война, если вы еще позволите себе защищать все гадости, все ужасы этого Антихриста (право, я верю, что он Антихрист), — я вас больше не знаю, вы уж не друг мой, вы уж не мой верный раб, как вы говорите.

[^2]: Я вижу, что я вас пугаю.

[^3]: Если у вас, граф (или князь), нет в виду ничего лучшего и если перспектива вечера у бедной больной не слишком вас пугает, то я буду очень рада видеть вас нынче у себя между семью и десятью часами. Анна Шерер.

[^4]: Господи, какое горячее нападение!

[^5]: Прежде всего скажите, как ваше здоровье, милый друг.

[^6]: Признаюсь, все эти праздники и фейерверки становятся несносны.

[^7]: Не мучьте меня. Ну, что́ же решили по случаю депеши Новосильцова? Вы всё знаете.

[^8]: Что́ решили? Решили, что Бонапарте сжег свои корабли, и мы тоже, кажется, готовы сжечь наши.

[^9]: Этот пресловутый нейтралитет Пруссии — только западня.

[^10]: Кстати, — виконт Мортемар, он в родстве с Монморанси чрез Роганов… аббат Морио.

[^11]: вдовствующая императрица… Барон этот ничтожное существо, как кажется.

[^12]: Барон Функе рекомендован императрице-матери ее сестрою.

[^13]: много уважения.

[^14]: Кстати о вашем семействе… составляет наслаждение всего общества. Ее находят прекрасною, как день.

[^15]: Что́ делать? Лафатер сказал бы, что у меня нет шишки родительской любви.

[^16]: дурни.

[^17]: Я ваш… и вам одним могу признаться. Мои дети — обуза моего существования… Что делать?..

[^18]: имеют манию женить… девушка… наша родственница, княжна.

[^19]: Вот выгода быть отцом.

[^20]: Бедняжка несчастлива, как камни.

[^21]: Послушайте, милая Анет.

[^22]: Устройте мне это дело, и я навсегда ваш… как мой староста мне пишет.

[^23]: Постойте… Лизе (жене Болконского).

[^24]: Я в вашем семействе начну обучаться ремеслу старой девицы.
`].join('\n\n');

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { // every face the pages use, loaded before the build
  'Old Standard TT': ['400', '400i'], // TEXT: the novel, the notes, the heads
  Oranienbaum: ['400'], // DISPLAY: the title page and the headings
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown }, config(), kitCyrillicFonts(FONTS));
showPages(doc, { title: 'Война и мир' });
offerPdf(() => renderToPdf(doc, { fontProvider: cyrillicPdfProvider }), `${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 · 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 ───────────────────────────────────────────────────────────────────────
```

## 常见问题

- 一页超过三四个星号，读起来就慢，第9页达到五个。可以像本配方这样把同一段话的译文合成一条注，也可以用`numberFormat: 'decimal'`改用数字。
- 输入在句号后面的注号就留在句号后面，先后由Markdown决定。

## 致谢

- 食谱: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- 文字: Война и мир, volume I, part I, chapter I, complete, after the Complete Works (PSS, vol. 9, 1937) in the transcription of ru.wikisource, with slips of the transcription corrected, Tolstoy’s translations placed as in current editions and the note mark set before the stop: Leo Tolstoy ([来源](https://ru.wikisource.org/wiki/Война_и_мир_(Толстой)/Том_1)), 公有领域
- 文字: The note on the text and the colophon: Postext Cookbook, 原创
- 字体: Old Standard TT (OFL-1.1), Oranienbaum (OFL-1.1)
- 代码: MIT · 示例内容: MIT

## 相关食谱

- [No. 201 · 按单调正字法断词的希腊语小说](https://postext.dev/zh/cookbook/monotonic-greek-novel.md): 把Theotokis《Η τιμή και το χρήμα》第一章排成13.5 × 20.5 cm的书：单调希腊语断词、«»引号、不带重音的大写书眉。 · 难度 2 (中级) · 小说、戏剧与文学散文
- [No. 071 · 脚注排在引用它的那一栏底部](https://postext.dev/zh/cookbook/novel-footnotes-column-foot.md): Markdown的[^id]标记变成编号注释，排在引用它的那一栏底部；另有开关可切换为单栏、章末注和连续编号。 · 难度 2 (中级) · 小说、戏剧与文学散文
- [No. 038 · 平装小说：下沉的章首页与右页起章](https://postext.dev/zh/cookbook/trade-paperback-novel.md): 把《The Awakening》排成140 × 216 mm的平装本：一幅绘画封面、一页不带书眉的版权页，然后每章都从右页开始，正文下沉，上面是一个斜体章序号。 · 难度 2 (中级) · 小说、戏剧与文学散文
