# ページごとに注を数えるロシア語の小説

> 『戦争と平和』第1章を130 × 200 mmに。会話のダッシュ、アステリスクで示すトルストイ自身の仏語訳、行末で分けない語、語で書く巻と編の番号まで組みます。

- HTML版: https://postext.dev/ja/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)
- Sandboxで開く: https://postext.dev/ja/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), [zh](https://postext.dev/zh/cookbook/russian-novel-notes-by-page.md), [ar](https://postext.dev/ar/cookbook/russian-novel-notes-by-page.md)

## かんたんな説明

『戦争と平和』の冒頭をロシア語で、昔ながらの上製本のように組みます。フランス語のせりふは各ページの下に訳され、アステリスクは次のページでまた一つから始まります。

## できあがり

『戦争と平和』（*Война и мир*）第1巻第1編第1章の全文を、全集第9巻（1937年）に拠って、130 × 200 mmのページに組みます。ロシアの84 × 108/32判の仕上がり寸法です。本文はOld Standard 10.5 pt、行送り13.2 pt、行長100 mmの34行。アンナ・パーヴロヴナとワシーリイ公爵は半ばフランス語で話し、トルストイ自身の訳がページの下に入り、アステリスクはページごとに始めから数えます。見出しは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/ja/docs/cyrillic-layout.md#キリル文字の本の始め方): localeを'ru'、'uk'、'be'、'bg'、'sr'、'mk'、'kk'、'ky'、'tt'、'ba'、'tg'、'mn'のいずれかにすると、その言語のハイフネーション、キャプション、表題、注、数詞、全紙判型、背文字の向きになります。
- [行末で分けない語](https://postext.dev/ja/docs/cyrillic-layout.md#分けない語): bodyText.wordTiesは、文書の言語の規則に従って、短い語を次の語と、頭文字を姓と、数を単位と同じ行に保ち、ダッシュを行頭に置きません。
- [脚注](https://postext.dev/ja/docs/document-format-notes-references.md#脚注): [^id]で参照する注です。参照した段の下端か章の後に置き、章ごと、または本全体の通し番号を振ります。

**ほかに使うもの**

- [ハイフネーションと文書の言語](https://postext.dev/ja/docs/justification.md#対応するロケール)
- [最適な改行（Knuth–Plass）](https://postext.dev/ja/docs/justification.md#knuth-plass段落全体を見渡す)
- [文字スタイル](https://postext.dev/ja/docs/document-format-inline.md#文字スタイル)
- [逆方向の文字列](https://postext.dev/ja/docs/arabic-layout.md#アイソレート)
- [番号付き見出し](https://postext.dev/ja/docs/configuration-headings.md#レベルごとの上書き)
- [デザインした章扉](https://postext.dev/ja/docs/configuration-headings.md#幅と詳細デザイン)
- [見出しスタイル](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [見出しの属性](https://postext.dev/ja/docs/document-format.md#見出しの属性)
- [仕上がりサイズ](https://postext.dev/ja/docs/configuration-page-layout.md#ページサイズのプリセット)
- [柱とノンブル](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル)
- [見開きの余白](https://postext.dev/ja/docs/configuration-page-layout.md#見開きの余白)
- [字下げ、行そろえ、段落間隔](https://postext.dev/ja/docs/configuration-text.md#本文)
- [段落スタイル](https://postext.dev/ja/docs/configuration-styles.md#段落スタイル)
- [文書のメタデータ](https://postext.dev/ja/docs/document-format.md#フロントマター)
- [セマンティックカラーパレット](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット)
- [PDFの書き出し](https://postext.dev/ja/docs/configuration-pdf-output.md#pdfの生成)
- [PDFに埋め込むフォント](https://postext.dev/ja/docs/configuration-pdf-output.md#なぜフォントプロバイダーが必要か)
- [用紙の色](https://postext.dev/ja/docs/configuration-page-layout.md#ページ)
- [ページの役割ごとの柱](https://postext.dev/ja/docs/configuration-headers-footers.md#テキスト要素)
- [節ごとの柱](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [番号のない章](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)

**設定の一覧**

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

**API**

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

**書体**

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

## 作り方

### 1 · 言語とアステリスクを決める

コードは上の[手短な答え](https://postext.dev/ja/cookbook/russian-novel-notes-by-page.md#手短な答え)です。`locale: 'ru'`はロシア語の規則で語を分け、前置詞や数やダッシュを[その語から離さず](https://postext.dev/ja/docs/cyrillic-layout.md#分けない語)、[注をページごとに数えます](https://postext.dev/ja/docs/cyrillic-layout.md#ページごとに番号を振る注)。`numberFormat: 'symbols'`で番号がアステリスクになります。合印はロシア語の習慣どおり、句点や読点の前、疑問符の後に打ちます。句点だけが次の行に落ちることはありません。行長100 mmはこれだけの規則には狭いので、字間に少し余裕を与えています。フランス語の箇所は`: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/ja/docs/cyrillic-layout.md#判型と背)の130 × 200 mmです。地の余白は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/ja/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/ja/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 · 2色の扉

```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) }),
];
```

枠は節のヘッダーに置きます。そこならページ全体を囲めます。文字は見出しとその属性から取ります。

## レシピの全体

レシピのフォルダーから合成した1つのファイルで、サンプルのテキストとレシピ集の共通キットを埋め込んであり、自分でページを組み立てます。動かすには、空のページの`<script type="module">`に入れるか、新しいCodePenのpenの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 ───────────────────────────────────────────────────────────────────────
```

## よくあるつまずき

- 1ページに三つか四つを超えるアステリスクは読みにくく、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/ja/cookbook/monotonic-greek-novel.md): テオトキス『Η τιμή και το χρήμα』の第1章を13.5 × 20.5 cmの本に。単調ギリシャ語の分綴、«»の引用符、アクセントを落とした大文字の柱。 · 難易度 2 (中級) · 小説・戯曲・文芸
- [No. 071 · 引用した段の地に置く脚注](https://postext.dev/ja/cookbook/novel-footnotes-column-foot.md): Markdownの[^id]の合印が、引用した段の地に置く番号付きの脚注になります。1段組み、章末注、通し番号への切り替えも付けています。 · 難易度 2 (中級) · 小説・戯曲・文芸
- [No. 038 · 並製本の小説：下げた章頭と改丁](https://postext.dev/ja/cookbook/trade-paperback-novel.md): 『The Awakening』を140 × 216 mmの並製本に組みます。柱のない彩色の表紙と奥付に続き、各章は奇数ページから、イタリックの章番号の下へ下げて始まります。 · 難易度 2 (中級) · 小説・戯曲・文芸
