# Ein russischer Roman mit Anmerkungen je Seite

> Das erste Kapitel von Krieg und Frieden auf 130 × 200 mm: Dialogstriche, Tolstois Übersetzungen als Sternchennoten und Wörter, die zusammenbleiben.

- HTML-Fassung: https://postext.dev/de/cookbook/russian-novel-notes-by-page
- Rezept Nº 205 · Schrift und Text · Stufe 2 (Mittel) · Ausgaben: Canvas, PDF
- Gattungen: Belletristik, Drama und Prosa
- Benötigt postext ≥ 1.100.0, postext-pdf ≥ 1.100.0 · getestet mit 1.100.0, postext-pdf 1.100.0 am 2026-12-02
- Seiten: [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)
- In der Sandbox öffnen: https://postext.dev/de/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)
- Zuletzt aktualisiert: 2026-12-02
- Andere Sprachen: [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), [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), [ja](https://postext.dev/ja/cookbook/russian-novel-notes-by-page.md), [ar](https://postext.dev/ar/cookbook/russian-novel-notes-by-page.md)

## Kurz gesagt

Der Anfang von Krieg und Frieden auf Russisch, als gebundenes Buch alter Schule. Die französischen Reden sind am Fuß jeder Seite übersetzt, mit Sternchen, die auf der nächsten Seite neu beginnen.

## Was Sie setzen

Band I, Teil I, Kapitel I von *Война и мир* (*Krieg und Frieden*), vollständig nach der Gesamtausgabe (Band 9, 1937), auf 130 × 200 mm, dem Format des russischen Bogens 84 × 108/32. Der Text steht in Old Standard, 10,5 auf 13,2 pt, 34 Zeilen zu 100 mm. Anna Pawlowna und Fürst Wassili sprechen halb französisch; Tolstois eigene Übersetzungen stehen am Fuß, mit Sternchen, die auf jeder Seite neu beginnen. Die Überschriften in Oranienbaum schreiben *Том первый* und *Часть первая* aus. Voran geht ein Titelblatt in Schwarz und Ziegelrot, auf dessen Rückseite eine Notiz in der Sprache der Ausgabe steht.

**Dieses Rezept beantwortet:**

- Wie setze ich einen russischen Roman, mit Sternchen je Seite und Wörtern, die zusammenbleiben?
- Wie mache ich Fußnoten?
- Wie schreibe ich Dialogstriche, Jahreszahlen am Absatzanfang, Preise und wörtliche Symbole, ohne dass Markdown sie falsch liest?
- Wie setze ich Kolumnentitel: Buchtitel auf der linken Seite, Kapiteltitel auf der rechten, Seitenzahl außen?

## Die kurze Antwort

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

## Zutaten

**Zeigt**

- [Kyrillisch geschriebene Sprachen als Dokumentsprache](https://postext.dev/de/docs/cyrillic-layout.md#ein-kyrillisches-buch-anlegen): locale 'ru', 'uk', 'be', 'bg', 'sr', 'mk', 'kk', 'ky', 'tt', 'ba', 'tg' oder 'mn' gibt dem Buch Silbentrennung, Bildunterschriften, Tabellentitel, Fußnoten, Zahlwörter, Bogenformate und Rückenrichtung seiner Sprache.
- [Wörter, die am Zeilenende beisammenbleiben](https://postext.dev/de/docs/cyrillic-layout.md#wörter-die-zusammenbleiben): bodyText.wordTies hält ein kurzes Wort beim nächsten, Initialen beim Nachnamen, eine Zahl bei ihrer Einheit und den Gedankenstrich vom Zeilenanfang fern, nach den Regeln der Dokumentsprache.
- [Fußnoten](https://postext.dev/de/docs/document-format-notes-references.md#fußnoten): Mit [^id] zitierte Anmerkungen, gesetzt am Fuß der Spalte, die sie zitiert, oder nach dem Kapitel, nummeriert je Kapitel oder durch das ganze Buch.

**Verwendet außerdem**

- [Silbentrennung und Dokumentsprache](https://postext.dev/de/docs/justification.md#unterstützte-sprachen)
- [Optimaler Zeilenumbruch (Knuth-Plass)](https://postext.dev/de/docs/justification.md#knuth-plass-der-blick-auf-den-ganzen-absatz)
- [Zeichenformate](https://postext.dev/de/docs/document-format-inline.md#zeichenformate)
- [Textstellen in der anderen Richtung](https://postext.dev/de/docs/arabic-layout.md#isolate)
- [Nummerierte Überschriften](https://postext.dev/de/docs/configuration-headings.md#überschreibungen-pro-ebene)
- [Gestaltete Auftakte](https://postext.dev/de/docs/configuration-headings.md#seitenbreite-und-erweiterte-gestaltung)
- [Überschriftenformate](https://postext.dev/de/docs/configuration-styles.md#überschriftenstile)
- [Überschriftenattribute](https://postext.dev/de/docs/document-format.md#attribute-von-überschriften)
- [Endformat](https://postext.dev/de/docs/configuration-page-layout.md#vorgegebene-seitenformate)
- [Kolumnentitel und Seitenzahlen](https://postext.dev/de/docs/configuration-headers-footers.md#kopf--und-fußzeilen)
- [Gespiegelte Ränder](https://postext.dev/de/docs/configuration-page-layout.md#gespiegelte-ränder)
- [Einzüge, Ausrichtung und Absatzabstände](https://postext.dev/de/docs/configuration-text.md#fließtext)
- [Absatzformate](https://postext.dev/de/docs/configuration-styles.md#absatzformate)
- [Dokument-Metadaten](https://postext.dev/de/docs/document-format.md#frontmatter)
- [Semantische Farbpalette](https://postext.dev/de/docs/configuration-fonts-colors-viewers.md#farbpalette)
- [PDF-Export](https://postext.dev/de/docs/configuration-pdf-output.md#pdfs-erzeugen)
- [Im PDF eingebettete Schriften](https://postext.dev/de/docs/configuration-pdf-output.md#warum-ein-font-provider)
- [Papierfarbe](https://postext.dev/de/docs/configuration-page-layout.md#seite)
- [Kopfzeilen nach Seitenrolle](https://postext.dev/de/docs/configuration-headers-footers.md#textelemente)
- [Kolumnentitel je Abschnitt](https://postext.dev/de/docs/configuration-styles.md#überschriftenstile)
- [Kapitel ohne Nummer](https://postext.dev/de/docs/configuration-styles.md#überschriftenstile)

**Die Konfiguration auf einen Blick**

- [`bodyText`](https://postext.dev/de/docs/configuration-text.md#fließtext), [`characterStyles`](https://postext.dev/de/docs/configuration-styles.md#zeichenformate), [`colorPalette`](https://postext.dev/de/docs/configuration-fonts-colors-viewers.md#farbpalette), [`footer`](https://postext.dev/de/docs/configuration-headers-footers.md#kopf--und-fußzeilen), [`footnotes`](https://postext.dev/de/docs/configuration-notes-references.md#fußnoten), [`header`](https://postext.dev/de/docs/configuration-headers-footers.md#kopf--und-fußzeilen), [`headingStyles`](https://postext.dev/de/docs/configuration-styles.md#überschriftenstile), [`headings`](https://postext.dev/de/docs/configuration-headings.md#überschriften), [`layout`](https://postext.dev/de/docs/configuration-page-layout.md#layout), [`locale`](https://postext.dev/de/docs/configuration-language.md#silbentrennung), [`page`](https://postext.dev/de/docs/configuration-page-layout.md#seite), [`paragraphStyles`](https://postext.dev/de/docs/configuration-styles.md#absatzformate)

**APIs**

- [`buildDocumentWithFonts`](https://postext.dev/de/docs/configuration-programmatic-usage.md#schriften-vor-dem-layout-laden), [`decompressWoff2`](https://postext.dev/de/docs/configuration-pdf-output.md#font-provider-im-browser-fontsource--woff2), [`renderPageToCanvas`](https://postext.dev/de/docs/configuration-programmatic-usage.md#eine-seite-als-bitmap-rendern), [`renderToPdf`](https://postext.dev/de/docs/configuration-pdf-output.md#pdfs-erzeugen)

**Schriften**

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

## Zubereitung

### 1 · Sprache und Sternchen einstellen

Der Code steht oben in [der kurzen Antwort](https://postext.dev/de/cookbook/russian-novel-notes-by-page.md#die-kurze-antwort). `locale: 'ru'` trennt nach den russischen Mustern, hält eine Präposition, eine Zahl oder einen Gedankenstrich [bei ihrem Wort](https://postext.dev/de/docs/cyrillic-layout.md#wörter-die-zusammenbleiben) und [zählt die Anmerkungen je Seite](https://postext.dev/de/docs/cyrillic-layout.md#seitenweise-gezählte-anmerkungen). `numberFormat: 'symbols'` setzt sie mit Sternchen. Das Zeichen wird getippt, wo das Russische es verlangt, vor Punkt oder Komma und nach dem Fragezeichen; der Punkt fällt nie auf die nächste Zeile. Ein Satzspiegel von 100 mm ist eng für so viele Bindungen, darum etwas Laufweite. Jede französische Stelle steht in `:ltr[…]{lang=fr}` und wird nach französischen Mustern getrennt.

### 2 · Die Seite aus dem Bogen gewinnen

```js
// script.js, Zeilen 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'` gibt die 130 × 200 mm der [GOST 5773](https://postext.dev/de/docs/cyrillic-layout.md#formate-und-buchrücken). Der Fußsteg ergibt sich aus 34 Zeilen, und `mirror` kehrt die Stege auf linken Seiten um.

### 3 · Ein Wort sperren, einen Vokal betonen

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

Russische Bücher jener Zeit sperrten ein Wort, um es hervorzuheben. Die [разрядка](https://postext.dev/de/docs/cyrillic-layout.md#hervorhebung-betonung-und-verse) ist ein Zeichenstil mit `letterSpacing`; hier tragen ihn die beiden Wörter, die die Ausgabe kursiv setzt, *грипп* und *рап*. Die Betonung ist U+0301 nach dem Vokal, wie in *что́* und *сто́ит*.

### 4 · Band und Teil ausschreiben

```js
// script.js, Zeilen 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/de/docs/cyrillic-layout.md#nummerierung-in-buchstaben-und-wörtern) und `{2:ordinal}` schreiben die Zähler in der Sprache des Dokuments aus, und `numberPosition: 'replace'` druckt sie anstelle der Überschrift. Im Markdown stehen `# Том` und `## Часть`; niemand muss eine Zahl neu tippen.

### 5 · Die Kolumnentitel

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

Der Autor steht über den linken Seiten, Titel und Band über den rechten, kursiv über einer feinen Linie. `pages: 'body'` hält den Anfang frei, der seine Seitenzahl unten trägt.

### 6 · Ein Titelblatt in zwei Farben

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

Der Rahmen liegt im Kopf des Abschnitts, wo er die ganze Seite fassen kann; die Texte kommen aus dem Titel und seinen Attributen.

## Das ganze Rezept

Eine Datei, aus dem Ordner des Rezepts zusammengesetzt, mit dem Beispieltext und dem gemeinsamen Baukasten der Rezepte bereits eingebettet; sie baut ihre eigene Seite auf. Zum Ausführen setzen Sie sie in ein `<script type="module">` auf einer leeren Seite oder fügen sie in das JS-Feld eines neuen CodePen-Pens ein (als Modul). Sie importiert postext von esm.sh, es gibt also nichts zu installieren oder zu bauen.

- Quellordner: 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 ───────────────────────────────────────────────────────────────────────
```

## Häufige Fehler

- Mehr als drei oder vier Sternchen auf einer Seite halten den Leser auf, und Seite 9 kommt auf fünf. Fassen Sie die Übersetzungen einer Rede in einer Anmerkung zusammen, wie dieses Rezept es tut, oder nehmen Sie Ziffern mit `numberFormat: 'decimal'`.
- Ein Notenzeichen, das nach dem Punkt getippt ist, bleibt dort. Die Reihenfolge bestimmt das Markdown.

## Nachweise

- Rezept: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Text: Война и мир, 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 ([Quelle](https://ru.wikisource.org/wiki/Война_и_мир_(Толстой)/Том_1)), gemeinfrei
- Text: The note on the text and the colophon: Postext Cookbook, Original
- Schrift: Old Standard TT (OFL-1.1), Oranienbaum (OFL-1.1)
- Code: MIT · Beispielinhalt: MIT

## Verwandte Rezepte

- [Nº 201 · Ein griechischer Roman mit monotonischer Silbentrennung](https://postext.dev/de/cookbook/monotonic-greek-novel.md): Das erste Kapitel von Theotokis’ «Η τιμή και το χρήμα» als Buch in 13,5 × 20,5 cm: monotonische Trennmuster, Guillemets «» und Versalien ohne Akzent. · Stufe 2 (Mittel) · Belletristik, Drama und Prosa
- [Nº 071 · Fußnoten am Fuß der Spalte, die sie zitiert](https://postext.dev/de/cookbook/novel-footnotes-column-foot.md): Fußnotenzeichen [^id] im Markdown werden zu nummerierten Fußnoten am Fuß ihrer Spalte, mit Schaltern für eine Spalte, Kapitelendnoten und durchgehende Nummern. · Stufe 2 (Mittel) · Belletristik, Drama und Prosa
- [Nº 038 · Taschenbuch: tiefe Auftakte und Kapitel rechts](https://postext.dev/de/cookbook/trade-paperback-novel.md): Beate und Mareile als Taschenbuch von 140 × 216 mm: gemalter Umschlag, Impressum ohne Kolumnentitel, dann tief gesetzte Kapitel rechts unter kursiver Ziffer. · Stufe 2 (Mittel) · Belletristik, Drama und Prosa
