# Novela rusa con notas numeradas por página

> El primer capítulo de Guerra y paz en página de 130 × 200 mm: rayas de diálogo, las traducciones de Tolstói con asteriscos al pie y palabras que van juntas.

- Versión HTML: https://postext.dev/es/cookbook/russian-novel-notes-by-page
- Receta N.º 205 · Texto y tipografía · Nivel 2 (Intermedio) · Salidas: Canvas, PDF
- Géneros: Narrativa, teatro y prosa literaria
- Requiere postext ≥ 1.100.0, postext-pdf ≥ 1.100.0 · probada con 1.100.0, postext-pdf 1.100.0 el 2026-12-02
- Páginas: [1](https://postext.dev/cookbook/russian-novel-notes-by-page/es/p01.webp?v=ccda17f6), [2](https://postext.dev/cookbook/russian-novel-notes-by-page/es/p02.webp?v=ccda17f6), [3](https://postext.dev/cookbook/russian-novel-notes-by-page/es/p03.webp?v=ccda17f6), [4](https://postext.dev/cookbook/russian-novel-notes-by-page/es/p04.webp?v=ccda17f6), [5](https://postext.dev/cookbook/russian-novel-notes-by-page/es/p05.webp?v=ccda17f6), [10](https://postext.dev/cookbook/russian-novel-notes-by-page/es/p10.webp?v=ccda17f6)
- Abrir en el Sandbox: https://postext.dev/es/sandbox#recipe=russian-novel-notes-by-page&lang=es (.postext: https://postext.dev/cookbook/russian-novel-notes-by-page/es/russian-novel-notes-by-page.postext)
- Última actualización: 2026-12-02
- Otros idiomas: [en](https://postext.dev/en/cookbook/russian-novel-notes-by-page.md), [ca](https://postext.dev/ca/cookbook/russian-novel-notes-by-page.md), [de](https://postext.dev/de/cookbook/russian-novel-notes-by-page.md), [el](https://postext.dev/el/cookbook/russian-novel-notes-by-page.md), [fr](https://postext.dev/fr/cookbook/russian-novel-notes-by-page.md), [it](https://postext.dev/it/cookbook/russian-novel-notes-by-page.md), [pt](https://postext.dev/pt/cookbook/russian-novel-notes-by-page.md), [ru](https://postext.dev/ru/cookbook/russian-novel-notes-by-page.md), [zh](https://postext.dev/zh/cookbook/russian-novel-notes-by-page.md), [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 pocas palabras

El comienzo de Guerra y paz en ruso, como un libro encuadernado a la antigua. Los parlamentos en francés se traducen al pie de cada página con asteriscos que vuelven a empezar en la siguiente.

## Lo que vas a componer

El capítulo I de la parte I del tomo I de *Война и мир* (*Guerra y paz*), completo, según las Obras completas (tomo 9, 1937), en una página de 130 × 200 mm, la que da el pliego ruso de 84 × 108/32. El texto va en Old Standard de 10,5 sobre 13,2 pt, 34 líneas de 100 mm. Anna Pávlovna y el príncipe Vasili hablan a medias en francés; las traducciones del propio Tolstói están al pie, con asteriscos que empiezan de nuevo en cada página. Los títulos, en Oranienbaum, escriben con letras *Том первый* y *Часть первая*. Antes va una portada en negro y rojo ladrillo, con una nota en la lengua de la edición en su vuelta.

**Esta receta responde a:**

- ¿Cómo compongo una novela rusa, con asteriscos contados por página y palabras que van juntas?
- ¿Cómo hago notas al pie?
- ¿Cómo escribo rayas de diálogo, años al principio de párrafo, precios y símbolos literales sin que el Markdown los malinterprete?
- ¿Cómo pongo cabeceras: el título del libro en la página izquierda, el del capítulo en la derecha y el folio por fuera?

## La respuesta corta

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

## Ingredientes

**Enseña**

- [Los idiomas de alfabeto cirílico como idioma del documento](https://postext.dev/es/docs/cyrillic-layout.md#empezar-un-libro-en-cirílico): locale 'ru', 'uk', 'be', 'bg', 'sr', 'mk', 'kk', 'ky', 'tt', 'ba', 'tg' o 'mn' da al libro la separación silábica, los pies, los títulos de tabla, las notas, los números en letra, los formatos de pliego y el sentido del lomo de su idioma.
- [Palabras que no se separan a final de línea](https://postext.dev/es/docs/cyrillic-layout.md#palabras-que-van-juntas): bodyText.wordTies mantiene la palabra corta con la siguiente, las iniciales con el apellido, el número con su unidad y la raya fuera del comienzo de línea, según las reglas del idioma del documento.
- [Notas al pie](https://postext.dev/es/docs/document-format-notes-references.md#notas-al-pie): Notas citadas con [^id] y compuestas al pie de la columna que las cita, o tras el capítulo, numeradas por capítulo o por todo el libro.

**También usa**

- [Separación silábica e idioma del documento](https://postext.dev/es/docs/justification.md#idiomas-admitidos)
- [Corte de líneas óptimo (Knuth–Plass)](https://postext.dev/es/docs/justification.md#knuth-plass-ver-el-párrafo-completo)
- [Estilos de carácter](https://postext.dev/es/docs/document-format-inline.md#estilos-de-carácter)
- [Fragmentos en la otra dirección](https://postext.dev/es/docs/arabic-layout.md#aislamientos)
- [Títulos numerados](https://postext.dev/es/docs/configuration-headings.md#configuración-por-nivel)
- [Aperturas diseñadas](https://postext.dev/es/docs/configuration-headings.md#apertura-a-toda-página-y-diseño-avanzado)
- [Estilos de título](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)
- [Atributos de título](https://postext.dev/es/docs/document-format.md#atributos-de-encabezado)
- [Formato de página](https://postext.dev/es/docs/configuration-page-layout.md#tamaños-de-página-predefinidos)
- [Cabeceras y folios](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies)
- [Márgenes simétricos](https://postext.dev/es/docs/configuration-page-layout.md#márgenes-simétricos-espejo)
- [Sangrías, alineación y separación de párrafos](https://postext.dev/es/docs/configuration-text.md#texto-base)
- [Estilos de párrafo](https://postext.dev/es/docs/configuration-styles.md#estilos-de-párrafo)
- [Metadatos del documento](https://postext.dev/es/docs/document-format.md#frontmatter)
- [Paleta de color semántica](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores)
- [Exportación a PDF](https://postext.dev/es/docs/configuration-pdf-output.md#generación-de-pdf)
- [Fuentes incrustadas en el PDF](https://postext.dev/es/docs/configuration-pdf-output.md#por-qué-un-proveedor-de-fuentes)
- [Color del papel](https://postext.dev/es/docs/configuration-page-layout.md#página)
- [Cabeceras según el tipo de página](https://postext.dev/es/docs/configuration-headers-footers.md#elementos-de-texto)
- [Cabeceras por sección](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)
- [Capítulos sin número](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)

**La configuración de un vistazo**

- [`bodyText`](https://postext.dev/es/docs/configuration-text.md#texto-base), [`characterStyles`](https://postext.dev/es/docs/configuration-styles.md#estilos-de-carácter), [`colorPalette`](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores), [`footer`](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies), [`footnotes`](https://postext.dev/es/docs/configuration-notes-references.md#notas-al-pie), [`header`](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies), [`headingStyles`](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado), [`headings`](https://postext.dev/es/docs/configuration-headings.md#encabezados), [`layout`](https://postext.dev/es/docs/configuration-page-layout.md#disposición), [`locale`](https://postext.dev/es/docs/configuration-language.md#separación-silábica), [`page`](https://postext.dev/es/docs/configuration-page-layout.md#página), [`paragraphStyles`](https://postext.dev/es/docs/configuration-styles.md#estilos-de-párrafo)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/es/docs/configuration-programmatic-usage.md#cargar-las-fuentes-antes-de-componer), [`decompressWoff2`](https://postext.dev/es/docs/configuration-pdf-output.md#proveedor-de-fuentes-en-el-navegador-fontsource--woff2), [`renderPageToCanvas`](https://postext.dev/es/docs/configuration-programmatic-usage.md#renderizar-una-página-como-mapa-de-bits), [`renderToPdf`](https://postext.dev/es/docs/configuration-pdf-output.md#generación-de-pdf)

**Tipografías**

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

## Elaboración

### 1 · Poner el idioma y los asteriscos

El código es [la respuesta corta](https://postext.dev/es/cookbook/russian-novel-notes-by-page.md#la-respuesta-corta) de arriba. `locale: 'ru'` separa las palabras con los patrones rusos, mantiene una preposición, un número o una raya [con su palabra](https://postext.dev/es/docs/cyrillic-layout.md#palabras-que-van-juntas) y [cuenta las notas por página](https://postext.dev/es/docs/cyrillic-layout.md#notas-numeradas-por-página). `numberFormat: 'symbols'` las marca con asteriscos. La llamada se escribe donde la pone el ruso, antes del punto o la coma y después de la interrogación, y el motor no deja que el punto caiga a la línea siguiente. Una medida de 100 mm es estrecha para tantas ataduras; de ahí un poco de tracking. Cada pasaje francés va en `:ltr[…]{lang=fr}`, para dividirse con los patrones del francés.

### 2 · Sacar la página del pliego

```js
// script.js, líneas 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'` da los 130 × 200 mm de la [GOST 5773](https://postext.dev/es/docs/cyrillic-layout.md#formatos-y-lomos). El margen inferior se calcula a partir de 34 líneas, y `mirror` invierte los lados en las pares.

### 3 · Espaciar una palabra, acentuar una vocal

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

Los libros rusos de la época espaciaban una palabra para destacarla. La [разрядка](https://postext.dev/es/docs/cyrillic-layout.md#énfasis-acentos-y-verso) es un estilo de carácter con `letterSpacing`, que aquí llevan las dos palabras que la edición pone en cursiva, *грипп* y *рап*. El acento es U+0301 detrás de la vocal, como en *что́* y *сто́ит*.

### 4 · Escribir con letras el tomo y la parte

```js
// script.js, líneas 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/es/docs/cyrillic-layout.md#numeración-con-letras-y-palabras) y `{2:ordinal}` escriben los contadores con palabras en la lengua del documento, y `numberPosition: 'replace'` los imprime en lugar del título. El Markdown dice `# Том` y `## Часть`, y nadie tiene que reescribir un número.

### 5 · Las cabeceras

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

El autor va sobre las pares y el título con su tomo sobre las impares, en cursiva y con un filete fino debajo. `pages: 'body'` deja limpio el arranque, que lleva el folio al pie.

### 6 · Una portada a dos tintas

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

El marco está en la cabecera de la sección, donde puede ocupar la página entera; los textos salen del título y de sus atributos.

## La receta completa

Un solo archivo, compuesto a partir de la carpeta de la receta con el texto de ejemplo y el kit común del Recetario ya incluidos; construye su propia página. Para ejecutarlo, ponlo en un `<script type="module">` de una página vacía o pégalo en el panel JS de un pen nuevo de CodePen (como módulo). Importa postext desde esm.sh, así que no hay nada que instalar ni compilar.

- Carpeta de la receta: 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 = 'es'; // @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"}

# Sobre el texto {style="note-page"}

:::paragraphs{style="note"}
El capítulo I de la primera parte del tomo I de *Guerra y paz* sigue las Obras completas de L. N. Tolstói (tomo 9, 1937) en la transcripción de la Wikisource rusa. Las traducciones del francés que van al pie son del propio Tolstói; cuando dos pertenecen a una misma réplica, van unidas por puntos suspensivos. Se corrigen erratas de la transcripción, entre ellas «pan» en letra latina por «рап». Las palabras que la edición pone en cursiva van aquí espaciadas; la letra ё figura solo donde la imprime la edición.
:::

:::paragraphs{style="colophon"}
Compuesto en Old Standard y Oranienbaum (SIL OFL)\
Texto: L. N. Tolstói, dominio público, de 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 ───────────────────────────────────────────────────────────────────────
```

## Errores frecuentes

- Más de tres o cuatro asteriscos por página frenan al lector, y la página 9 llega a cinco. Junta en una sola nota las traducciones de un mismo parlamento, como hace esta receta, o usa cifras con `numberFormat: 'decimal'`.
- Una llamada escrita después del punto se queda después del punto. El orden lo pone el Markdown.

## Créditos

- Receta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Texto: Война и мир, tomo I, parte I, capítulo I, completo, según las Obras completas (PSS, t. 9, 1937) en la transcripción de ru.wikisource, con las erratas de la transcripción corregidas, las traducciones de Tolstói colocadas como en las ediciones actuales y la llamada de nota antes del punto: Leo Tolstoy ([fuente](https://ru.wikisource.org/wiki/Война_и_мир_(Толстой)/Том_1)), dominio público
- Texto: La nota sobre el texto y el colofón: Postext Cookbook, original
- Tipografías: Old Standard TT (OFL-1.1), Oranienbaum (OFL-1.1)
- Código: MIT · Contenido de ejemplo: MIT

## Relacionadas

- [N.º 201 · Una novela griega con partición monotónica](https://postext.dev/es/cookbook/monotonic-greek-novel.md): El primer capítulo de «Η τιμή και το χρήμα» de Theotokis en un libro de 13,5 × 20,5 cm: patrones del griego monotónico, comillas «» y versales sin tilde. · Nivel 2 (Intermedio) · Narrativa, teatro y prosa literaria
- [N.º 071 · Notas al pie de la columna que las cita](https://postext.dev/es/cookbook/novel-footnotes-column-foot.md): Las llamadas [^id] pasan a notas numeradas al pie de la columna que las cita, con interruptores para una columna, notas finales y numeración continua. · Nivel 2 (Intermedio) · Narrativa, teatro y prosa literaria
- [N.º 038 · Novela en rústica: aperturas hundidas y capítulos en impar](https://postext.dev/es/cookbook/trade-paperback-novel.md): The Awakening en rústica de 140 × 216 mm: cubierta pintada, colofón sin cabeceras y cada capítulo hundido en página impar bajo un número romano en cursiva. · Nivel 2 (Intermedio) · Narrativa, teatro y prosa literaria
