# Un roman russe aux notes comptées par page

> Le premier chapitre de Guerre et Paix en 130 × 200 mm : tirets de dialogue, traductions de Tolstoï en notes à astérisques et mots gardés ensemble.

- Version HTML: https://postext.dev/fr/cookbook/russian-novel-notes-by-page
- Recette Nº 205 · Caractères et texte · Niveau 2 (Intermédiaire) · Sorties: Canvas, PDF
- Genres: Fiction, théâtre et prose littéraire
- Nécessite postext ≥ 1.100.0, postext-pdf ≥ 1.100.0 · testée avec 1.100.0, postext-pdf 1.100.0 le 2026-12-02
- Pages: [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)
- Ouvrir dans le Sandbox: https://postext.dev/fr/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)
- Dernière mise à jour: 2026-12-02
- Autres langues: [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), [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)

## En bref

Le début de Guerre et Paix en russe, comme un livre relié d'autrefois. Les répliques en français sont traduites au pied de chaque page, avec des astérisques qui repartent d'un à la page suivante.

## Ce que vous allez composer

Le chapitre I de la première partie du tome I de *Война и мир* (*Guerre et Paix*), en entier, d'après les Œuvres complètes (tome 9, 1937), sur une page de 130 × 200 mm, celle que donne la feuille russe 84 × 108/32. Le texte est en Old Standard, corps 10,5 sur 13,2 pt, 34 lignes de 100 mm. Anna Pavlovna et le prince Vassili parlent à demi en français ; les traductions de Tolstoï lui-même sont au pied, avec des astérisques qui recommencent à chaque page. Les titres en Oranienbaum écrivent *Том первый* et *Часть первая* en toutes lettres. Une page de titre en noir et rouge brique précède, avec au verso une note dans la langue de l'édition.

**Cette recette répond à:**

- Comment composer un roman russe, astérisques comptés par page et mots gardés ensemble ?
- Comment faire des notes de bas de page ?
- Comment écrire des tirets de dialogue, des années en début de paragraphe, des prix et des symboles littéraux sans que le Markdown les interprète mal ?
- Comment régler les titres courants : titre du livre sur la page de gauche, titre du chapitre sur celle de droite, numéro de page à l’extérieur ?

## La réponse courte

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

## Ingrédients

**Enseigne**

- [Les langues en cyrillique comme langue du document](https://postext.dev/fr/docs/cyrillic-layout.md#commencer-un-livre-en-cyrillique): locale 'ru', 'uk', 'be', 'bg', 'sr', 'mk', 'kk', 'ky', 'tt', 'ba', 'tg' ou 'mn' donne au livre la césure, les légendes, les titres de tableau, les notes, les nombres en lettres, les formats de feuille et le sens du dos de sa langue.
- [Mots maintenus ensemble en fin de ligne](https://postext.dev/fr/docs/cyrillic-layout.md#mots-gardés-ensemble): bodyText.wordTies garde le mot court avec le suivant, les initiales avec le nom, le nombre avec son unité et le tiret hors du début de ligne, selon les règles de la langue du document.
- [Notes de bas de page](https://postext.dev/fr/docs/document-format-notes-references.md#notes-de-bas-de-page): Des notes appelées avec [^id] et composées au pied de la colonne qui les cite, ou après le chapitre, numérotées par chapitre ou sur tout le livre.

**Utilise aussi**

- [Césure et langue du document](https://postext.dev/fr/docs/justification.md#langues-prises-en-charge)
- [Coupure optimale des lignes (Knuth–Plass)](https://postext.dev/fr/docs/justification.md#knuth-plass-voir-le-paragraphe-entier)
- [Styles de caractère](https://postext.dev/fr/docs/document-format-inline.md#styles-de-caractère)
- [Passages dans l’autre sens](https://postext.dev/fr/docs/arabic-layout.md#isolats)
- [Titres numérotés](https://postext.dev/fr/docs/configuration-headings.md#réglages-par-niveau)
- [Ouvertures composées](https://postext.dev/fr/docs/configuration-headings.md#étendue-et-maquette-avancée)
- [Styles de titre](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)
- [Attributs de titre](https://postext.dev/fr/docs/document-format.md#attributs-de-titre)
- [Format de la page](https://postext.dev/fr/docs/configuration-page-layout.md#formats-de-page-prédéfinis)
- [Titres courants et folios](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page)
- [Marges en miroir](https://postext.dev/fr/docs/configuration-page-layout.md#marges-en-miroir)
- [Retraits, alignement et espacement des paragraphes](https://postext.dev/fr/docs/configuration-text.md#texte-courant)
- [Styles de paragraphe](https://postext.dev/fr/docs/configuration-styles.md#styles-de-paragraphe)
- [Métadonnées du document](https://postext.dev/fr/docs/document-format.md#en-tête-yaml)
- [Palette de couleurs sémantique](https://postext.dev/fr/docs/configuration-fonts-colors-viewers.md#palette-de-couleurs)
- [Export PDF](https://postext.dev/fr/docs/configuration-pdf-output.md#générer-des-pdf)
- [Polices intégrées au PDF](https://postext.dev/fr/docs/configuration-pdf-output.md#pourquoi-un-fournisseur-de-polices)
- [Couleur du papier](https://postext.dev/fr/docs/configuration-page-layout.md#page)
- [Titres courants selon le rôle de la page](https://postext.dev/fr/docs/configuration-headers-footers.md#éléments-de-texte)
- [Titres courants par section](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)
- [Chapitres non numérotés](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)

**La configuration en un coup d’œil**

- [`bodyText`](https://postext.dev/fr/docs/configuration-text.md#texte-courant), [`characterStyles`](https://postext.dev/fr/docs/configuration-styles.md#styles-de-caractère), [`colorPalette`](https://postext.dev/fr/docs/configuration-fonts-colors-viewers.md#palette-de-couleurs), [`footer`](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page), [`footnotes`](https://postext.dev/fr/docs/configuration-notes-references.md#notes-de-bas-de-page), [`header`](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page), [`headingStyles`](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre), [`headings`](https://postext.dev/fr/docs/configuration-headings.md#titres), [`layout`](https://postext.dev/fr/docs/configuration-page-layout.md#mise-en-page), [`locale`](https://postext.dev/fr/docs/configuration-language.md#césure), [`page`](https://postext.dev/fr/docs/configuration-page-layout.md#page), [`paragraphStyles`](https://postext.dev/fr/docs/configuration-styles.md#styles-de-paragraphe)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/fr/docs/configuration-programmatic-usage.md#charger-les-polices-avant-la-mise-en-page), [`decompressWoff2`](https://postext.dev/fr/docs/configuration-pdf-output.md#fournisseur-de-polices-dans-le-navigateur-fontsource--woff2), [`renderPageToCanvas`](https://postext.dev/fr/docs/configuration-programmatic-usage.md#rendre-une-page-en-bitmap), [`renderToPdf`](https://postext.dev/fr/docs/configuration-pdf-output.md#générer-des-pdf)

**Caractères**

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

## Préparation

### 1 · Choisir la langue et les astérisques

Le code est [la réponse courte](https://postext.dev/fr/cookbook/russian-novel-notes-by-page.md#la-réponse-courte) ci-dessus. `locale: 'ru'` coupe selon les motifs russes, garde une préposition, un nombre ou un tiret [avec son mot](https://postext.dev/fr/docs/cyrillic-layout.md#mots-gardés-ensemble) et [compte les notes par page](https://postext.dev/fr/docs/cyrillic-layout.md#notes-comptées-par-page). `numberFormat: 'symbols'` les marque d'astérisques. L'appel se saisit où le veut l'usage russe, avant le point ou la virgule et après le point d'interrogation, et le moteur ne laisse jamais le point tomber à la ligne suivante. Une justification de 100 mm est étroite pour tant de liens ; d'où un peu d'approche. Chaque passage français est dans `:ltr[…]{lang=fr}` et se coupe selon les motifs français.

### 2 · Tirer la page de la feuille

```js
// script.js, lignes 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'` donne les 130 × 200 mm de [GOST 5773](https://postext.dev/fr/docs/cyrillic-layout.md#formats-et-dos). La marge de pied se calcule d'après 34 lignes, et `mirror` inverse les côtés sur les versos.

### 3 · Espacer un mot, accentuer une voyelle

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

Les livres russes de l'époque espaçaient un mot pour le faire ressortir. La [разрядка](https://postext.dev/fr/docs/cyrillic-layout.md#mise-en-valeur-accent-tonique-et-vers) est un style de caractère avec `letterSpacing`, réservé ici aux deux mots que l'édition met en italique, *грипп* et *рап*. L'accent tonique est U+0301 après la voyelle, comme dans *что́* et *сто́ит*.

### 4 · Écrire le tome et la partie en lettres

```js
// script.js, lignes 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/fr/docs/cyrillic-layout.md#numérotation-par-lettres-et-en-toutes-lettres) et `{2:ordinal}` écrivent les compteurs en toutes lettres dans la langue du document, et `numberPosition: 'replace'` les imprime à la place du titre. Le Markdown porte `# Том` et `## Часть`, et personne n'a de numéro à resaisir.

### 5 · Les titres courants

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

L'auteur est sur les versos, le titre et son tome sur les rectos, en italique au-dessus d'un filet maigre. `pages: 'body'` dégage l'ouverture, qui porte son folio en pied.

### 6 · Une page de titre en deux encres

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

Le cadre est dans l'en-tête de la section, où il peut couvrir la page ; les textes viennent du titre et de ses attributs.

## La recette complète

Un seul fichier, composé à partir du dossier de la recette avec le texte d’exemple et le kit commun des Recettes déjà inclus ; il construit sa propre page. Pour l’exécuter, placez-le dans un `<script type="module">` d’une page vide ou collez-le dans le panneau JS d’un nouveau pen CodePen (en tant que module). Il importe postext depuis esm.sh : il n’y a rien à installer ni à compiler.

- Dossier de la recette: 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 ───────────────────────────────────────────────────────────────────────
```

## Erreurs fréquentes

- Au-delà de trois ou quatre astérisques par page, le lecteur ralentit, et la page 9 en compte cinq. Réunissez en une note les traductions d'une même réplique, comme le fait cette recette, ou prenez des chiffres avec `numberFormat: 'decimal'`.
- Un appel saisi après le point reste après le point. L'ordre est celui du Markdown.

## Crédits

- Recette: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Texte: Война и мир, 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 ([source](https://ru.wikisource.org/wiki/Война_и_мир_(Толстой)/Том_1)), domaine public
- Texte: The note on the text and the colophon: Postext Cookbook, original
- Caractères: Old Standard TT (OFL-1.1), Oranienbaum (OFL-1.1)
- Code: MIT · Contenu d’exemple: MIT

## Recettes liées

- [Nº 201 · Un roman grec coupé selon le grec monotonique](https://postext.dev/fr/cookbook/monotonic-greek-novel.md): Le premier chapitre de « Η τιμή και το χρήμα » de Theotokis en livre de 13,5 × 20,5 cm : motifs du grec monotonique, guillemets «» et capitales sans accent. · Niveau 2 (Intermédiaire) · Fiction, théâtre et prose littéraire
- [Nº 071 · Des notes au pied de la colonne qui les appelle](https://postext.dev/fr/cookbook/novel-footnotes-column-foot.md): Les appels Markdown [^id] deviennent des notes numérotées au pied de la colonne qui les cite ; options : une colonne, fin de chapitre, numéros continus. · Niveau 2 (Intermédiaire) · Fiction, théâtre et prose littéraire
- [Nº 038 · Roman broché : ouvertures basses et chapitres au recto](https://postext.dev/fr/cookbook/trade-paperback-novel.md): Madame Gervaisais en broché de 140 × 216 mm : couverture peinte et colophon sans titres courants, puis chapitres ouverts bas au recto sous un chiffre italique. · Niveau 2 (Intermédiaire) · Fiction, théâtre et prose littéraire
