# Un apartado de un libro de física ruso

> El § 14 de un libro de física ruso: Рис. 1, título de tabla en dos líneas, tg y arctg en las fórmulas, notas por página y listas 1) а).

- Versión HTML: https://postext.dev/es/cookbook/russian-physics-textbook
- Receta N.º 207 · Libros de texto · Nivel 3 (Avanzado) · Salidas: Canvas, PDF
- Géneros: Libros de texto
- 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: [71](https://postext.dev/cookbook/russian-physics-textbook/es/p01.webp?v=8ff5022c), [72](https://postext.dev/cookbook/russian-physics-textbook/es/p02.webp?v=8ff5022c), [73](https://postext.dev/cookbook/russian-physics-textbook/es/p03.webp?v=8ff5022c), [74](https://postext.dev/cookbook/russian-physics-textbook/es/p04.webp?v=8ff5022c)
- PDF: https://postext.dev/cookbook/russian-physics-textbook/es/russian-physics-textbook.pdf?v=8ff5022c
- Abrir en el Sandbox: https://postext.dev/es/sandbox#recipe=russian-physics-textbook&lang=es (.postext: https://postext.dev/cookbook/russian-physics-textbook/es/russian-physics-textbook.postext)
- Última actualización: 2026-12-02
- Otros idiomas: [en](https://postext.dev/en/cookbook/russian-physics-textbook.md), [ca](https://postext.dev/ca/cookbook/russian-physics-textbook.md), [de](https://postext.dev/de/cookbook/russian-physics-textbook.md), [el](https://postext.dev/el/cookbook/russian-physics-textbook.md), [fr](https://postext.dev/fr/cookbook/russian-physics-textbook.md), [it](https://postext.dev/it/cookbook/russian-physics-textbook.md), [pt](https://postext.dev/pt/cookbook/russian-physics-textbook.md), [ru](https://postext.dev/ru/cookbook/russian-physics-textbook.md), [zh](https://postext.dev/zh/cookbook/russian-physics-textbook.md), [ja](https://postext.dev/ja/cookbook/russian-physics-textbook.md), [ar](https://postext.dev/ar/cookbook/russian-physics-textbook.md)

## En pocas palabras

Cuatro páginas de un libro escolar ruso de física sobre un cuerpo en una pendiente. El dibujo, la tabla, el problema resuelto y las preguntas llevan los rótulos y números de los libros escolares rusos.

## Lo que vas a componer

Un apartado de un libro imaginario de física de noveno curso, sobre un cuerpo en un plano inclinado, a 145 × 215 mm, el formato que los editores rusos llaman 60 × 90/16. Se abre con «§ 14» en una pestaña azul. La Рис. 1 dibuja las fuerzas; la Таблица 1 da el rozamiento de seis pares de materiales, con el ángulo límite calculado a partir de tg α. Un recuadro dice lo que hay que recordar y un problema resuelto va en dos celdas, «Дано» y «Решение». Las preguntas se numeran 1), 2) y, dentro, а), б). El texto es PT Serif de 10 sobre 13,6 pt, títulos y pies Golos Text, las fórmulas MathJax. La página está en ruso en todas las ediciones y se escribió para esta receta; solo el colofón cambia de lengua.

**Esta receta responde a:**

- ¿Cómo compongo un libro escolar ruso con Рис., título de tabla en dos líneas, listas 1) а) y tg?
- ¿Cómo compongo matemáticas (en línea, destacadas, ecuaciones) y las mantengo vectoriales en el PDF?
- ¿Cómo añado una figura con pie numerado y la cito en el texto («véase la fig. 3.2»)?
- ¿Cómo personalizo las listas: viñetas por nivel, numeración (a)/(i), casillas de tareas y un espaciado que respete la rejilla?

## La respuesta corta

```js
// script.js, líneas 39–63
// locale 'ru' hyphenates by the Russian patterns, keeps a short preposition with its word and a
// number with its unit (9,8 м/с², 0,4 кг), counts the notes again on every page and indents
// them, and gives the resource types Рис. and Таблица.
const LOCALE = 'ru';
// A figure is «Рис. 1. …» under the drawing. A table has «Таблица 1» at the right on a line of
// its own and its title centred under it, which is how defaultResourceTypes('ru') comes. Both
// count through the book here ({n}, no chapter), and a reference in a sentence is «рис. 1».
const resourceTypes = [
  ...defaultResourceTypes(LOCALE).map((type) => ({ ...type, numberingTemplate: '{n}',
    resetOn: 'never' })),
  // «Дано | Решение» is a table without label or title.
  { id: 'given', name: 'Решение', shortLabel: '', captionPrefix: '', numberingTemplate: '{n}',
    resetOn: 'never', counterFormat: 'decimal', defaultPlacement: { position: 'here' } },
];
// Lists count 1) 2) and, inside, а) б) в): the Cyrillic series leaves out ё й ъ ы ь.
const orderedLists = { color: col('ink'), fontWeight: 400, separator: ')', marginTop: pt(0),
  marginBottom: pt(0), indent: em(1.5), separatorColor: col('brick'), levels: [
    { level: 1, numberFormat: 'decimal', separator: ')', color: col('brick'), fontWeight: 700 },
    { level: 2, numberFormat: 'lower-russian', separator: ')', color: col('brick') },
  ] };
// MathJax knows the operators of the Russian school: \tg, \ctg, \arctg. The decimal comma is
// written {,}: 9{,}8 sets without the space a comma takes in a list.
await initMathEngine();
const math = { fontSizeScale: 1.1, marginTop: em(0.7), marginBottom: em(0.7),
  keepWithLeadIn: true, indentAfterDisplay: true }; // PT Serif's x-height is 0.5 em, TeX's 0.44
```

## 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.
- [Matemáticas](https://postext.dev/es/docs/document-format-inline.md#fórmulas-matemáticas): LaTeX en línea y destacado compuesto por MathJax, sobre la rejilla y vectorial en todas las salidas, con química mediante mhchem.
- [Figura y Tabla en tu idioma](https://postext.dev/es/docs/configuration-resources.md#tipos-de-recurso): defaultResourceTypes(locale) devuelve los tipos Figura y Tabla de serie, con etiquetas y referencias en el idioma del documento.

**También usa**

- [Palabras que no se separan a final de línea](https://postext.dev/es/docs/cyrillic-layout.md#palabras-que-van-juntas)
- [Separación silábica e idioma del documento](https://postext.dev/es/docs/justification.md#idiomas-admitidos)
- [Notas al pie](https://postext.dev/es/docs/document-format-notes-references.md#notas-al-pie)
- [Listas numeradas](https://postext.dev/es/docs/configuration-lists-math.md#listas-ordenadas)
- [Aperturas diseñadas](https://postext.dev/es/docs/configuration-headings.md#apertura-a-toda-página-y-diseño-avanzado)
- [Atributos de título](https://postext.dev/es/docs/document-format.md#atributos-de-encabezado)
- [Citas que colocan las figuras](https://postext.dev/es/docs/document-format-resources.md#referencia-en-línea-la-forma-principal)
- [Pies numerados](https://postext.dev/es/docs/document-format-resources.md#numeración-por-primera-referencia)
- [Estilo de los pies](https://postext.dev/es/docs/configuration-resources.md#estilo-de-pies-de-recurso)
- [Tablas a partir de datos](https://postext.dev/es/docs/document-format-resources.md#inserción-en-bloque-opcional-colocación-en-línea-explícita)
- [Estilo de tablas](https://postext.dev/es/docs/configuration-resources.md#estilo-de-tablas)
- [Recuadros](https://postext.dev/es/docs/configuration-callouts.md#estilos-de-recuadro)
- [Textos, filetes y cajas en los diseños de página](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies)
- [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)
- [Exportación a PDF](https://postext.dev/es/docs/configuration-pdf-output.md#generación-de-pdf)
- [Títulos numerados](https://postext.dev/es/docs/configuration-headings.md#configuración-por-nivel)
- [Estilos de título](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)
- [Figuras justo aquí](https://postext.dev/es/docs/document-format-resources.md#inserción-en-bloque-opcional-colocación-en-línea-explícita)
- [Saltos de página y de columna](https://postext.dev/es/docs/document-format-directives.md#pagebreak)
- [Cabeceras según el tipo de página](https://postext.dev/es/docs/configuration-headers-footers.md#elementos-de-texto)
- [Estilos de párrafo](https://postext.dev/es/docs/configuration-styles.md#estilos-de-párrafo)
- [Fuentes incrustadas en el PDF](https://postext.dev/es/docs/configuration-pdf-output.md#por-qué-un-proveedor-de-fuentes)
- [Tipos de recurso propios](https://postext.dev/es/docs/configuration-resources.md#tipos-de-recurso)
- [Figuras y tablas como recursos](https://postext.dev/es/docs/document-format-resources.md#recursos)
- [Preliminares en romanos](https://postext.dev/es/docs/document-format-directives.md#numbering)
- [Superíndices y subíndices](https://postext.dev/es/docs/document-format-inline.md#formato-en-línea)
- [Estilos de tabla con nombre](https://postext.dev/es/docs/configuration-resources.md#estilos-de-tabla-con-nombre)

**La configuración de un vistazo**

- [`bodyText`](https://postext.dev/es/docs/configuration-text.md#texto-base), [`calloutStyles`](https://postext.dev/es/docs/configuration-callouts.md#estilos-de-recuadro), [`captionStyle`](https://postext.dev/es/docs/configuration-resources.md#estilo-de-pies-de-recurso), [`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), [`math`](https://postext.dev/es/docs/configuration-lists-math.md#matemáticas), [`orderedLists`](https://postext.dev/es/docs/configuration-lists-math.md#listas-ordenadas), [`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), [`resourceTypes`](https://postext.dev/es/docs/configuration-resources.md#tipos-de-recurso), [`tableStyle`](https://postext.dev/es/docs/configuration-resources.md#estilo-de-tablas), [`tableStyles`](https://postext.dev/es/docs/configuration-resources.md#estilos-de-tabla-con-nombre)

**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), [`defaultResourceTypes`](https://postext.dev/es/docs/configuration-resources.md#tipos-de-recurso), [`initMathEngine`](https://postext.dev/es/docs/document-format-inline.md#fórmulas-matemáticas), [`registerResourceImage`](https://postext.dev/es/docs/architecture.md#api-pública), `renderMath`, [`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**

- PT Serif (OFL-1.1), Golos Text (OFL-1.1)

## Elaboración

### 1 · Un locale para el texto, las notas y los rótulos

El código es [la respuesta corta](https://postext.dev/es/cookbook/russian-physics-textbook.md#la-respuesta-corta) de arriba. `locale: 'ru'` parte las palabras con los patrones rusos, deja в, на o с en la línea de la palabra que sigue y 0,4 con кг, y cuenta las notas de nuevo en cada página ([composición en cirílico](https://postext.dev/es/docs/cyrillic-layout.md)). `defaultResourceTypes('ru')` entrega Рис. con su pie debajo y Таблица con el número a la derecha y el título centrado debajo ([recursos](https://postext.dev/es/docs/configuration-resources.md)). `numberFormat: 'lower-russian'` ordena una lista con а), б), в) y se salta ё, й, ъ, ы y ь ([listas y matemáticas](https://postext.dev/es/docs/configuration-lists-math.md)). MathJax conoce `\tg`, `\ctg` y `\arctg`, los nombres de la escuela rusa.

### 2 · § 14 en una pestaña

```js
// script.js, líneas 67–85
// # Тело на наклонной плоскости {startAt=14 kicker="…"}: a section (параграф) is the H1.
const paragraph = { level: 1, numberingTemplate: '§ {1}', marginBottom: pt(0),
  advancedDesign: { enabled: true, minHeight: pt(5 * LEAD), slot: { elements: [
    { kind: 'box', id: 'tab', style: { backgroundColor: col('blue') },
      placement: { ...at('page', 'top-left', 0, 0), size: { width: mm(INNER + 25),
        height: mm(TOP + 17) } } },
    { kind: 'text', id: 'number', content: '{number}', align: 'left', ...sans(27, 700, 'paper'),
      placement: at('container', 'top-left', 0, 3.5) },
    { kind: 'text', id: 'kicker', content: '{attr.kicker}', align: 'left',
      ...sans(7.8, 500, 'muted'), placement: at('container', 'top-left', 31, -7) },
    { kind: 'text', id: 'title', content: '{titleText}', align: 'left', overflow: 'wrap',
      ...sans(21, 700, 'ink', { lineHeight: 1.12 }),
      placement: { ...at('container', 'top-left', 31, 0), size: { width: mm(MEASURE - 31) } } },
  ] } } };
const subhead = { level: 2, numberingTemplate: '', fontFamily: SANS, fontWeight: 600,
  fontSize: pt(11.5), lineHeight: pt(LEAD), color: col('blue'), marginTop: pt(LEAD * 1.3),
  marginBottom: pt(LEAD * 0.5) };
// ## Вопросы {style="plain"}: what the pupil does, in red.
const headingStyles = [{ id: 'plain', color: col('brick') }];
```

`# Тело на наклонной плоскости {startAt=14 kicker="…"}` da al apartado el número 14, y `numberingTemplate: '§ {1}'` lo imprime como § 14. El diseño lleva un cuadro azul a sangre desde la esquina de la página hasta la base del número; `minHeight` da cinco líneas a la apertura. El folio explicativo de la página impar toma el mismo número con `{chapterNumber}`. `## Вопросы {style="plain"}` usa el estilo de título que pone en rojo lo que hace el alumno.

### 3 · Un recuadro para la regla, una franja para el problema

```js
// script.js, líneas 89–99
const title = (color) => sans(8.2, 700, color, { gap: mm(1) });
const box = { body: { firstLineIndent: pt(0) }, marginTop: pt(LEAD / 2),
  marginBottom: pt(LEAD / 2) };
const calloutStyles = [
  { id: 'rule', ...box, background: col('mist'), backgroundEnabled: true, titleStyle: title('blue'),
    stripe: { enabled: true, width: pt(3), color: col('blue') },
    padding: { top: mm(3), right: mm(4), bottom: mm(2), left: mm(5) } },
  { id: 'problem', ...box, backgroundEnabled: false, titleStyle: title('brick'),
    stripe: { enabled: true, width: pt(2), color: col('brick') },
    padding: { top: mm(0.5), right: mm(0), bottom: mm(0.5), left: mm(4) } },
];
```

Dos estilos de recuadro comparten el cuerpo y se distinguen por el fondo: `rule` pone «Запомните» sobre azul pálido tras una franja de 3 pt, `problem` lleva una franja roja y ningún fondo. `firstLineIndent: 0` deja sin sangría la primera línea de un recuadro, mientras que los párrafos de la página llevan todos 1,5 em.

### 4 · Una figura rotulada con MathJax

```js
// script.js, líneas 235–293
// An SVG drawn as an image cannot use the page's fonts, so its letters are MathJax paths.
// Millimetres; the slope falls to the right, along x.
const [FIG_W, FIG_H] = [104, 58];
const A = (25 * Math.PI) / 180, R = (x) => Math.round(x * 100) / 100;
function tex(markup, x, y, size = 4.6, color = 'ink') { // centred on (x, y)
  const [r, k] = [renderMath(markup, false, 100), size / 1000];
  return `<g transform="translate(${R(x - (r.viewBox.width * k) / 2)} ${R(y + size * 0.33)}) `
    + `scale(${k})" fill="${palette[color]}">`
    + `${r.paths.map((p) => `<path d="${p.d}"/>`).join('')}</g>`;
}
function arrow([x, y], angle, length, color, width = 0.7) { // angle in radians, y down
  const [c, s, head, half] = [Math.cos(angle), Math.sin(angle), 2.6, 0.95];
  const p = (u, v) => `${R(x + u * c - v * s)} ${R(y + u * s + v * c)}`;
  return `<path d="M${p(0, 0)}L${p(length - head + 0.2, 0)}" stroke="${palette[color]}" `
    + `stroke-width="${width}"/><path d="M${p(length, 0)}L${p(length - head, half)}`
    + `L${p(length - head, -half)}Z" fill="${palette[color]}"/>`;
}
function slope() {
  const foot = [96, 55], run = 88, base = [foot[0] - run, foot[1]];
  const top = [base[0], base[1] - run * Math.tan(A)];
  const along = (d, out = 0) => [foot[0] - d * Math.cos(A) + out * Math.sin(A),
    foot[1] - d * Math.sin(A) - out * Math.cos(A)]; // d up the slope from its foot
  const poly = (pts, fill, stroke, w) => `<polygon points="${pts.map((p) => p.map(R).join(','))
    .join(' ')}" fill="${fill}" stroke="${stroke}" stroke-width="${w}" stroke-linejoin="round"/>`;
  const [bw, bh, d] = [17, 11, 55]; // the body, and how far up the slope it stands
  const [C, mid] = [along(d, bh / 2), bh / 2];
  const ray = (d1, o1, d2, o2, dash = '') => { const [p, q] = [along(d1, o1), along(d2, o2)];
    return `<path d="M${p.map(R).join(' ')}L${q.map(R).join(' ')}" stroke="${palette.muted}" `
      + `stroke-width="0.3"${dash}/>`; };
  let s = poly([base, foot, top], palette.mist, palette.ink, 0.45)
    + poly([along(d - bw / 2), along(d + bw / 2), along(d + bw / 2, bh), along(d - bw / 2, bh)],
      '#cdd9e8', palette.blue, 0.45);
  // The axes through the centre of the body: x down the slope, y away from it.
  s += ray(d + 22, mid, d - 34, mid) + ray(d, mid - 23, d, mid + 24);
  s += arrow(along(d - 31, mid), A, 4.5, 'muted', 0.3)
    + arrow(along(d, mid + 22), A - Math.PI / 2, 4.5, 'muted', 0.3);
  // mg and its components, dashed to the axes.
  const [G, dash] = [23, ' stroke-dasharray="1.2 0.9"']; // mm of arrow for mg; N follows
  const tip = [C[0], C[1] + G];
  s += [along(d - G * Math.sin(A), mid), along(d, mid - G * Math.cos(A))].map((p) =>
    `<path d="M${tip.map(R).join(' ')}L${p.map(R).join(' ')}" `
    + `stroke="${palette.muted}" stroke-width="0.3"${dash}/>`).join('');
  s += arrow(C, Math.PI / 2, G, 'brick') + arrow(C, A - Math.PI / 2, G * Math.cos(A), 'brick')
    + arrow(C, A + Math.PI, 15, 'brick')
    + `<circle cx="${R(C[0])}" cy="${R(C[1])}" r="0.8" fill="${palette.ink}"/>`;
  // The angle at the foot, and the equal one between mg and the normal.
  const arc = (o, r, from, to) => `<path d="M${R(o[0] + r * Math.cos(from))} `
    + `${R(o[1] + r * Math.sin(from))}A${r} ${r} 0 0 1 ${R(o[0] + r * Math.cos(to))} `
    + `${R(o[1] + r * Math.sin(to))}" stroke="${palette.ink}" stroke-width="0.3"/>`;
  s += arc(foot, 14, Math.PI, Math.PI + A) + arc(C, 11, Math.PI / 2, Math.PI / 2 + A);
  s += tex('\\alpha', foot[0] - 17.5, foot[1] - 3.8)
    + tex('\\alpha', C[0] - 2.9, C[1] + 13.6, 4)
    + tex('m\\vec{g}', C[0] + 5.6, C[1] + G - 3.6, 4.6, 'brick')
    + tex('\\vec{N}', ...along(d - 4.6, mid + 18), 4.6, 'brick')
    + tex('\\vec{F}_{\\text{тр}}', ...along(d + 14, mid + 5), 4.6, 'brick')
    + tex('x', ...along(d - 33.5, mid + 3.6), 4.2) + tex('y', ...along(d + 3.4, mid + 25), 4.2);
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${FIG_W * 10}" height="${FIG_H * 10}" `
    + `viewBox="0 0 ${FIG_W} ${FIG_H}" fill="none">${s}</svg>`;
}
```

Un SVG dibujado como imagen no puede usar los tipos de la página, así que sus letras son trazados de MathJax que da `renderMath`, con `\vec{N}` y `m\vec{g}` como en el texto. La pendiente es de 25°, y la flecha N mide lo mismo que la componente de mg perpendicular al plano, como en la física. `:ref{id="sily"}` imprime «рис. 1» en la frase.

### 5 · Una tabla calculada y «Дано | Решение»

```js
// script.js, líneas 297–317
const cell = (content, extra = {}) => ({ content, align: 'center', ...extra });
const PAIRS = [['Сталь по льду', 0.02], ['Лыжи по снегу', 0.05], ['Сталь по стали', 0.15],
  ['Дерево по дереву', 0.25], ['Резина по мокрому асфальту', 0.4],
  ['Резина по сухому асфальту', 0.7]];
const angles = { headerRowCount: 1, columnWidths: [2.2, 1, 1.2], rows: [
  [cell('Материалы', { align: 'left', isHeader: true }), cell('$\\mu$', { isHeader: true }),
    cell('$\\alpha_0$', { isHeader: true })],
  ...PAIRS.map(([name, mu]) => [cell(name, { align: 'left' }), cell(String(mu).replace('.', ',')),
    cell(`${Math.round((Math.atan(mu) * 180) / Math.PI)}°`)]),
] };
const given = { columnWidths: [1, 2.9], rows: [[
  { content: ['**Дано:**', '$\\alpha = 30^\\circ$', '$\\mu = 0{,}25$', '$l = 2$ м',
    '$v_0 = 0$', '**Найти:** $a$, $v$'].join('\n'), background: col('sand'), verticalAlign: 'top' },
  { content: ['**Решение**',
    'Так как $\\tg\\alpha \\approx 0{,}58 > \\mu$, ящик скользит:',
    '$a = g\\,(\\sin\\alpha - \\mu\\cos\\alpha)$,',
    '$a = 9{,}8 \\cdot (0{,}5 - 0{,}25 \\cdot 0{,}87) \\approx 2{,}8$ м/с^2^.',
    'Начальная скорость равна нулю, $v^2 = 2al$:',
    '$v = \\sqrt{2al} = \\sqrt{2 \\cdot 2{,}8 \\cdot 2} \\approx 3{,}3$ м/с.'].join('\n'),
  verticalAlign: 'top' },
]] };
```

`Math.atan(mu)` llena la columna de ángulos y `replace('.', ',')` escribe la coma decimal. La solución es una segunda tabla de una fila: no hay `headerRowCount` y el tipo de recurso `given` no tiene rótulo, así que el recuadro muestra dos celdas sin título. `:ref{id="ugly" text="таблице 1"}` lleva la palabra en el caso que pide la frase.

## 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-physics-textbook

### script.js

```js
// ═══ Postext Cookbook · Nº 207 · A section of a Russian physics textbook ═════════════════
// https://postext.dev/en/cookbook/russian-physics-textbook
// Code: MIT · Text: original (CC BY 4.0) · Diagram: drawn in code (CC BY 4.0)
// Fonts: PT Serif, Golos Text (SIL OFL 1.1) · Needs postext ≥ 1.100.0
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, initMathEngine, renderMath,
  defaultResourceTypes,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'es'; // @lang: the language of the colophon ('en' | 'es' | 'ru'); the page is Russian
const RECIPE = 'russian-physics-textbook';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// Two inks on white, as a school press prints them: a blue for what is learnt, a brick red for
// what is asked.
const palette = {
  ink: '#1d2126', // text
  blue: '#1c4c86', // the accent: section number, headings, rule box, the body in the diagram
  mist: '#e8eef6', // the rule box's ground, the table's head, the slope in the diagram
  brick: '#b03a2a', // problems, questions and the forces in the diagram
  sand: '#f6efe6', // the «Дано» column
  rule: '#bcc8d6', // hairlines
  muted: '#586370', // running heads, the colophon
  paper: '#ffffff',
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = Object.entries({ ...palette, 'main-color': palette.blue })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const [SERIF, SANS] = ['PT Serif', 'Golos Text']; // both with Cyrillic
const [BODY, LEAD] = [10, 13.6]; // pt
const [TOP, BOTTOM, INNER, OUTER] = [20, 19, 16, 18]; // mm, on a 145 × 215 page
const MEASURE = 145 - INNER - OUTER; // mm: 111, about 64 characters
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const sans = (size, weight, color, extra = {}) => ({ fontFamily: SANS, fontSize: pt(size),
  fontWeight: weight, color: col(color), ...extra });

// #region answer: one Russian locale: patterns, ties, notes by page, Рис. and Таблица
// locale 'ru' hyphenates by the Russian patterns, keeps a short preposition with its word and a
// number with its unit (9,8 м/с², 0,4 кг), counts the notes again on every page and indents
// them, and gives the resource types Рис. and Таблица.
const LOCALE = 'ru';
// A figure is «Рис. 1. …» under the drawing. A table has «Таблица 1» at the right on a line of
// its own and its title centred under it, which is how defaultResourceTypes('ru') comes. Both
// count through the book here ({n}, no chapter), and a reference in a sentence is «рис. 1».
const resourceTypes = [
  ...defaultResourceTypes(LOCALE).map((type) => ({ ...type, numberingTemplate: '{n}',
    resetOn: 'never' })),
  // «Дано | Решение» is a table without label or title.
  { id: 'given', name: 'Решение', shortLabel: '', captionPrefix: '', numberingTemplate: '{n}',
    resetOn: 'never', counterFormat: 'decimal', defaultPlacement: { position: 'here' } },
];
// Lists count 1) 2) and, inside, а) б) в): the Cyrillic series leaves out ё й ъ ы ь.
const orderedLists = { color: col('ink'), fontWeight: 400, separator: ')', marginTop: pt(0),
  marginBottom: pt(0), indent: em(1.5), separatorColor: col('brick'), levels: [
    { level: 1, numberFormat: 'decimal', separator: ')', color: col('brick'), fontWeight: 700 },
    { level: 2, numberFormat: 'lower-russian', separator: ')', color: col('brick') },
  ] };
// MathJax knows the operators of the Russian school: \tg, \ctg, \arctg. The decimal comma is
// written {,}: 9{,}8 sets without the space a comma takes in a list.
await initMathEngine();
const math = { fontSizeScale: 1.1, marginTop: em(0.7), marginBottom: em(0.7),
  keepWithLeadIn: true, indentAfterDisplay: true }; // PT Serif's x-height is 0.5 em, TeX's 0.44
// #endregion

// #region headings: «§ 14» in a blue tab, then subheads without numbers
// # Тело на наклонной плоскости {startAt=14 kicker="…"}: a section (параграф) is the H1.
const paragraph = { level: 1, numberingTemplate: '§ {1}', marginBottom: pt(0),
  advancedDesign: { enabled: true, minHeight: pt(5 * LEAD), slot: { elements: [
    { kind: 'box', id: 'tab', style: { backgroundColor: col('blue') },
      placement: { ...at('page', 'top-left', 0, 0), size: { width: mm(INNER + 25),
        height: mm(TOP + 17) } } },
    { kind: 'text', id: 'number', content: '{number}', align: 'left', ...sans(27, 700, 'paper'),
      placement: at('container', 'top-left', 0, 3.5) },
    { kind: 'text', id: 'kicker', content: '{attr.kicker}', align: 'left',
      ...sans(7.8, 500, 'muted'), placement: at('container', 'top-left', 31, -7) },
    { kind: 'text', id: 'title', content: '{titleText}', align: 'left', overflow: 'wrap',
      ...sans(21, 700, 'ink', { lineHeight: 1.12 }),
      placement: { ...at('container', 'top-left', 31, 0), size: { width: mm(MEASURE - 31) } } },
  ] } } };
const subhead = { level: 2, numberingTemplate: '', fontFamily: SANS, fontWeight: 600,
  fontSize: pt(11.5), lineHeight: pt(LEAD), color: col('blue'), marginTop: pt(LEAD * 1.3),
  marginBottom: pt(LEAD * 0.5) };
// ## Вопросы {style="plain"}: what the pupil does, in red.
const headingStyles = [{ id: 'plain', color: col('brick') }];
// #endregion

// #region boxes: the rule on a tint behind a blue stripe, the problem behind a red one
const title = (color) => sans(8.2, 700, color, { gap: mm(1) });
const box = { body: { firstLineIndent: pt(0) }, marginTop: pt(LEAD / 2),
  marginBottom: pt(LEAD / 2) };
const calloutStyles = [
  { id: 'rule', ...box, background: col('mist'), backgroundEnabled: true, titleStyle: title('blue'),
    stripe: { enabled: true, width: pt(3), color: col('blue') },
    padding: { top: mm(3), right: mm(4), bottom: mm(2), left: mm(5) } },
  { id: 'problem', ...box, backgroundEnabled: false, titleStyle: title('brick'),
    stripe: { enabled: true, width: pt(2), color: col('brick') },
    padding: { top: mm(0.5), right: mm(0), bottom: mm(0.5), left: mm(4) } },
];
// #endregion

const captionStyle = { ...sans(8.6, 400, 'ink'), gap: mm(2), align: 'center', labelBold: true,
  labelColor: col('blue'), note: { fontFamily: SANS, fontSize: pt(7.6), color: col('muted') } };
const tableStyle = { rules: 'horizontal', borderColor: col('rule'), borderWidth: pt(0.5),
  headerBackground: col('mist'), headerColor: col('blue'), headerFontFamily: SANS,
  headerFontSize: pt(8.4), bodyFontFamily: SANS, bodyFontSize: pt(8.8), bodyColor: col('ink'),
  cellPadding: mm(1.3) };
const tableStyles = [{ id: 'given', rules: 'none', borders: false, bodyFontFamily: SERIF,
  bodyFontSize: pt(BODY), cellPadding: mm(2.6) }];

// Running heads: the book on the verso, the section on the recto; folios at the foot.
const small = (id, parity, content, edge, x) => ({ kind: 'text', id, parity, content, pages: 'body',
  align: parity === 'odd' ? 'right' : 'left', ...sans(7.6, 500, 'muted'),
  placement: at('page', edge, x, 11) });
const header = { elements: [
  small('verso', 'even', '{title}', 'top-left', OUTER),
  small('recto', 'odd', '{chapterNumber}. {chapterTitle}', 'top-right', -OUTER),
  { kind: 'rule', id: 'line', direction: 'horizontal', thickness: pt(0.5), color: col('rule'),
    pages: 'body', placement: { ...at('container', 'top', 0, 15.5), size: { width: 'fill' } } },
] };
const folio = (parity, edge, x) => ({ kind: 'text', id: `folio-${parity}`, parity,
  content: '{pageNumber}', ...sans(8.8, 700, 'blue'), placement: at('page', edge, x, -10) });
const footer = { elements: [folio('even', 'bottom-left', OUTER),
  folio('odd', 'bottom-right', -OUTER)] };

const config = () => ({
  locale: LOCALE, // written out, never LANG: the page is Russian in every edition
  resourceTypes, colorPalette, math, headingStyles, calloutStyles, captionStyle, tableStyle,
  tableStyles, orderedLists, header, footer,
  // 60 × 90/16 is a sheet format of GOST 5773, trimmed to 145 × 215 mm.
  page: { sizePreset: '60x90/16', dpi: 150, pageNumbering: { startAt: 71 },
    margins: { top: mm(TOP), bottom: mm(BOTTOM), left: mm(INNER), right: mm(OUTER),
      mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: SERIF, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    referenceBold: false, firstLineIndent: em(1.5), indentAfterHeading: true, // all indented
    minWordSpacing: 0.8, maxWordSpacing: 1.5, maxJustifyTracking: 10 },
  headings: { fontFamily: SANS, color: col('ink'), levels: [paragraph, subhead] },
  footnotes: { fontFamily: SERIF, fontSize: pt(8.2), lineHeight: pt(10.8),
    separator: { enabled: true, width: 0.25, lineWidth: pt(0.5), color: col('muted') } },
  paragraphStyles: [{ id: 'colophon', ...sans(7, 400, 'muted'), lineHeight: pt(9.4),
    textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD),
    hyphenation: false }],
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The section (content.text.<lang>.md), then the colophon in the edition's language.
const markdown = [String.raw`---
title: "Физика. 9 класс"
---

# Тело на наклонной плоскости {startAt=14 kicker="Глава 2 · Законы движения"}

Санки сами съезжают с ледяной горки, а ящик на пологом пандусе стоит неподвижно. Оба тела лежат на наклонной поверхности, и силы на них действуют одни и те же. От чего же зависит, останется тело на месте или начнёт скользить?

## Какие силы действуют на тело

Плоскость, которая составляет с горизонтом острый угол, называют **наклонной плоскостью**. Угол этот обозначим $\alpha$. На тело массой $m$, которое соскальзывает по ней, действуют три силы (:ref{id="sily"}): сила тяжести $m\vec{g}$, направленная отвесно вниз[^g]; сила реакции опоры $\vec{N}$, перпендикулярная плоскости; сила трения $\vec{F}_{\text{тр}}$, направленная вдоль плоскости, против движения. Скорость тела направлена вдоль плоскости вниз.

[^g]: Ускорение свободного падения у поверхности Земли $g \approx 9{,}8$ м/с^2^. Если в задаче не нужна большая точность, берут $g = 10$ м/с^2^.

::resource{id="sily"}

Направим ось $x$ вдоль плоскости вниз, а ось $y$ — перпендикулярно ей. Тогда раскладывать на проекции придётся только силу тяжести: угол между нею и перпендикуляром к плоскости тоже равен $\alpha$. Вдоль оси $y$ тело не движется, поэтому сумма проекций сил на эту ось равна нулю:

$$N - mg\cos\alpha = 0, \qquad N = mg\cos\alpha.$$

## Когда тело начинает скользить

Сила трения скольжения пропорциональна силе реакции опоры: $F_{\text{тр}} = \mu N$, где $\mu$ — коэффициент трения, который зависит от материалов и обработки поверхностей. Запишем второй закон Ньютона в проекциях на ось $x$:

$$ma = mg\sin\alpha - \mu mg\cos\alpha.$$

Разделим обе части уравнения на $m$.

:::callout{type="rule" title="Запомните"}
Ускорение тела, которое скользит по наклонной плоскости вниз, не зависит от его массы:

$$a = g\,(\sin\alpha - \mu\cos\alpha).$$
:::

Будем увеличивать угол наклона. При некотором угле $\alpha_0$ тело заскользит равномерно: $a = 0$, и тогда $\sin\alpha_0 = \mu\cos\alpha_0$. Этот угол называют **предельным**; его тангенс[^tg] равен коэффициенту трения:

$$\tg\alpha_0 = \mu, \qquad \alpha_0 = \arctg\mu.$$

[^tg]: От латинского *tangens* — «касающийся». В русских учебниках тангенс обозначают $\tg$, котангенс — $\ctg$.

Если $\tg\alpha \leqslant \mu$, тело, поставленное на плоскость, остаётся на месте; если $\tg\alpha > \mu$, оно скользит с ускорением. Предельные углы для нескольких пар материалов приведены в :ref{id="ugly" text="таблице 1"}. Тангенс угла наклона указывают и на дорожных знаках: надпись «12 %» перед крутым спуском означает, что $\tg\alpha = 0{,}12$, то есть $\alpha \approx 7^\circ$.

::resource{id="ugly"}

## Пример решения задачи {style="plain"}

:::callout{type="problem" title="Задача"}
Ящик соскальзывает по доске, наклонённой под углом 30° к горизонту. Коэффициент трения ящика о доску равен 0,25. С каким ускорением движется ящик и какую скорость он приобретёт, пройдя из состояния покоя 2 м?

::resource{id="reshenie"}

**Ответ:** $a \approx 2{,}8$ м/с^2^, $v \approx 3{,}3$ м/с.
:::

:::pagebreak

## Вопросы {style="plain"}

1. Назовите силы, которые действуют на тело, лежащее на наклонной плоскости, и укажите направление каждой из них.
2. Угол наклона плоскости увеличивают. Как при этом меняется:
   1. проекция силы тяжести на ось $x$;
   2. сила реакции опоры;
   3. сила трения, пока тело покоится;
   4. сила трения, когда тело скользит?
3. Зависит ли предельный угол наклона от массы тела? Почему?

## Упражнение 14 {style="plain"}

1. Брусок массой 0,4 кг равномерно скользит по доске, наклонённой под углом 22° к горизонту. Найдите:
   1. коэффициент трения бруска о доску;
   2. силу реакции опоры;
   3. силу трения.
2. Удержится ли на спуске, где $\tg\alpha = 0{,}45$, автомобиль с заторможенными колёсами, если асфальт:
   1. сухой;
   2. мокрый?
3. Лыжник съезжает с горы длиной 80 м, наклонённой под углом 10° к горизонту. Пользуясь таблицей 1, найдите ускорение лыжника, скорость в конце спуска и время спуска.

## Сделайте дома {style="plain"}

Положите на доску книгу и медленно поднимайте край доски, пока книга не сдвинется с места. Измерьте высоту $h$ поднятого края и расстояние $b$ по столу от него до другого края. Вычислите коэффициент трения: $\mu = h/b$. Повторите опыт с двумя книгами.
`, String.raw`:::paragraphs{style="colophon"}
Un apartado de un libro de física ruso imaginario, escrito para esta receta. Compuesto con Postext en PT Serif y Golos Text (SIL OFL); fórmulas de MathJax. Texto y esquema originales, CC BY 4.0.
:::
`].join('\n\n');

// #region figure: the three forces on a slope of 25°, lettered by MathJax
// An SVG drawn as an image cannot use the page's fonts, so its letters are MathJax paths.
// Millimetres; the slope falls to the right, along x.
const [FIG_W, FIG_H] = [104, 58];
const A = (25 * Math.PI) / 180, R = (x) => Math.round(x * 100) / 100;
function tex(markup, x, y, size = 4.6, color = 'ink') { // centred on (x, y)
  const [r, k] = [renderMath(markup, false, 100), size / 1000];
  return `<g transform="translate(${R(x - (r.viewBox.width * k) / 2)} ${R(y + size * 0.33)}) `
    + `scale(${k})" fill="${palette[color]}">`
    + `${r.paths.map((p) => `<path d="${p.d}"/>`).join('')}</g>`;
}
function arrow([x, y], angle, length, color, width = 0.7) { // angle in radians, y down
  const [c, s, head, half] = [Math.cos(angle), Math.sin(angle), 2.6, 0.95];
  const p = (u, v) => `${R(x + u * c - v * s)} ${R(y + u * s + v * c)}`;
  return `<path d="M${p(0, 0)}L${p(length - head + 0.2, 0)}" stroke="${palette[color]}" `
    + `stroke-width="${width}"/><path d="M${p(length, 0)}L${p(length - head, half)}`
    + `L${p(length - head, -half)}Z" fill="${palette[color]}"/>`;
}
function slope() {
  const foot = [96, 55], run = 88, base = [foot[0] - run, foot[1]];
  const top = [base[0], base[1] - run * Math.tan(A)];
  const along = (d, out = 0) => [foot[0] - d * Math.cos(A) + out * Math.sin(A),
    foot[1] - d * Math.sin(A) - out * Math.cos(A)]; // d up the slope from its foot
  const poly = (pts, fill, stroke, w) => `<polygon points="${pts.map((p) => p.map(R).join(','))
    .join(' ')}" fill="${fill}" stroke="${stroke}" stroke-width="${w}" stroke-linejoin="round"/>`;
  const [bw, bh, d] = [17, 11, 55]; // the body, and how far up the slope it stands
  const [C, mid] = [along(d, bh / 2), bh / 2];
  const ray = (d1, o1, d2, o2, dash = '') => { const [p, q] = [along(d1, o1), along(d2, o2)];
    return `<path d="M${p.map(R).join(' ')}L${q.map(R).join(' ')}" stroke="${palette.muted}" `
      + `stroke-width="0.3"${dash}/>`; };
  let s = poly([base, foot, top], palette.mist, palette.ink, 0.45)
    + poly([along(d - bw / 2), along(d + bw / 2), along(d + bw / 2, bh), along(d - bw / 2, bh)],
      '#cdd9e8', palette.blue, 0.45);
  // The axes through the centre of the body: x down the slope, y away from it.
  s += ray(d + 22, mid, d - 34, mid) + ray(d, mid - 23, d, mid + 24);
  s += arrow(along(d - 31, mid), A, 4.5, 'muted', 0.3)
    + arrow(along(d, mid + 22), A - Math.PI / 2, 4.5, 'muted', 0.3);
  // mg and its components, dashed to the axes.
  const [G, dash] = [23, ' stroke-dasharray="1.2 0.9"']; // mm of arrow for mg; N follows
  const tip = [C[0], C[1] + G];
  s += [along(d - G * Math.sin(A), mid), along(d, mid - G * Math.cos(A))].map((p) =>
    `<path d="M${tip.map(R).join(' ')}L${p.map(R).join(' ')}" `
    + `stroke="${palette.muted}" stroke-width="0.3"${dash}/>`).join('');
  s += arrow(C, Math.PI / 2, G, 'brick') + arrow(C, A - Math.PI / 2, G * Math.cos(A), 'brick')
    + arrow(C, A + Math.PI, 15, 'brick')
    + `<circle cx="${R(C[0])}" cy="${R(C[1])}" r="0.8" fill="${palette.ink}"/>`;
  // The angle at the foot, and the equal one between mg and the normal.
  const arc = (o, r, from, to) => `<path d="M${R(o[0] + r * Math.cos(from))} `
    + `${R(o[1] + r * Math.sin(from))}A${r} ${r} 0 0 1 ${R(o[0] + r * Math.cos(to))} `
    + `${R(o[1] + r * Math.sin(to))}" stroke="${palette.ink}" stroke-width="0.3"/>`;
  s += arc(foot, 14, Math.PI, Math.PI + A) + arc(C, 11, Math.PI / 2, Math.PI / 2 + A);
  s += tex('\\alpha', foot[0] - 17.5, foot[1] - 3.8)
    + tex('\\alpha', C[0] - 2.9, C[1] + 13.6, 4)
    + tex('m\\vec{g}', C[0] + 5.6, C[1] + G - 3.6, 4.6, 'brick')
    + tex('\\vec{N}', ...along(d - 4.6, mid + 18), 4.6, 'brick')
    + tex('\\vec{F}_{\\text{тр}}', ...along(d + 14, mid + 5), 4.6, 'brick')
    + tex('x', ...along(d - 33.5, mid + 3.6), 4.2) + tex('y', ...along(d + 3.4, mid + 25), 4.2);
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${FIG_W * 10}" height="${FIG_H * 10}" `
    + `viewBox="0 0 ${FIG_W} ${FIG_H}" fill="none">${s}</svg>`;
}
// #endregion

// #region tables: the limiting angles, computed, and «Дано | Решение» as two cells
const cell = (content, extra = {}) => ({ content, align: 'center', ...extra });
const PAIRS = [['Сталь по льду', 0.02], ['Лыжи по снегу', 0.05], ['Сталь по стали', 0.15],
  ['Дерево по дереву', 0.25], ['Резина по мокрому асфальту', 0.4],
  ['Резина по сухому асфальту', 0.7]];
const angles = { headerRowCount: 1, columnWidths: [2.2, 1, 1.2], rows: [
  [cell('Материалы', { align: 'left', isHeader: true }), cell('$\\mu$', { isHeader: true }),
    cell('$\\alpha_0$', { isHeader: true })],
  ...PAIRS.map(([name, mu]) => [cell(name, { align: 'left' }), cell(String(mu).replace('.', ',')),
    cell(`${Math.round((Math.atan(mu) * 180) / Math.PI)}°`)]),
] };
const given = { columnWidths: [1, 2.9], rows: [[
  { content: ['**Дано:**', '$\\alpha = 30^\\circ$', '$\\mu = 0{,}25$', '$l = 2$ м',
    '$v_0 = 0$', '**Найти:** $a$, $v$'].join('\n'), background: col('sand'), verticalAlign: 'top' },
  { content: ['**Решение**',
    'Так как $\\tg\\alpha \\approx 0{,}58 > \\mu$, ящик скользит:',
    '$a = g\\,(\\sin\\alpha - \\mu\\cos\\alpha)$,',
    '$a = 9{,}8 \\cdot (0{,}5 - 0{,}25 \\cdot 0{,}87) \\approx 2{,}8$ м/с^2^.',
    'Начальная скорость равна нулю, $v^2 = 2al$:',
    '$v = \\sqrt{2al} = \\sqrt{2 \\cdot 2{,}8 \\cdot 2} \\approx 3{,}3$ м/с.'].join('\n'),
  verticalAlign: 'top' },
]] };
// #endregion

const resources = [
  { id: 'sily', typeId: 'figure', kind: 'svg', createdAt: 0, updatedAt: 0,
    svg: { fileId: 'slope.svg', width: FIG_W * 10, height: FIG_H * 10 },
    placement: { position: 'here', width: 0.86, align: 'center' },
    caption: 'Силы, действующие на тело на наклонной плоскости',
    altText: 'Брусок на наклонной плоскости с углом альфа. Из центра бруска: mg отвесно вниз, '
      + 'N по нормали к плоскости, Fтр вверх вдоль неё; оси x (вниз вдоль плоскости) и y.' },
  { id: 'ugly', typeId: 'table', kind: 'table', createdAt: 0, updatedAt: 0,
    table: { model: angles }, placement: { position: 'here' },
    caption: 'Коэффициенты трения и предельные углы',
    note: 'Углы вычислены по формуле $\\alpha_0 = \\arctg\\mu$ и округлены до градуса.' },
  { id: 'reshenie', typeId: 'given', kind: 'table', createdAt: 0, updatedAt: 0,
    table: { model: given, styleId: 'given' }, placement: { position: 'here' },
    altText: 'Краткая запись условия и решение задачи' },
];

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { // every face the pages paint, loaded before the first build
  'PT Serif': ['400', '400i', '700'], // SERIF: the text, the notes, the solution
  'Golos Text': ['400', '500', '600', '700'], // SANS: headings, captions, table, heads
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
await loadSvg('slope.svg', slope());
const doc = await buildDocumentWithFonts({ markdown, resources }, config(),
  kitCyrillicFonts(FONTS));
showPages(doc, { title: 'Физика. 9 класс · § 14' });
offerPdf(() => renderToPdf(doc, { fontProvider: cyrillicPdfProvider, resourceBytes: imageBytes }),
  `${RECIPE}.pdf`); // text in the Fontsource faces; formulas and the figure as vector paths

// ─── 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 · images v3 ── recipes with pictures · postext.dev/cookbook
/** Registers a photo or PNG for the canvas and keeps its bytes for the PDF.
 *  fetch → ImageBitmap never taints the canvas (a plain cross-origin <img> would). */
async function loadImage(fileId, url) {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`Image not found (${res.status}): ${url}`);
  const bytes = new Uint8Array(await res.arrayBuffer());
  registerResourceImage(fileId, await createImageBitmap(new Blob([bytes])));
  (loadImage.bytes ??= new Map()).set(fileId, bytes);
}

/** Registers SVG markup as a vector image, its fonts inside (inlineSvgFonts, ≥ 1.25).
 *  `options` go to registerResourceImage: { singleInk: true } tints it on the canvas. */
async function loadSvg(fileId, svg, options) {
  if (typeof inlineSvgFonts === 'function') svg = await inlineSvgFonts(svg, svgFaces);
  const img = new Image();
  img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
  await img.decode();
  registerResourceImage(fileId, img, options);
  (loadImage.bytes ??= new Map()).set(fileId, new TextEncoder().encode(svg));
}

/** A face's Fontsource files: nearest weight; latin + what the SVG sets. */
async function svgFaces(family, weight, style, { codePoints = [] } = {}) {
  const [id, m] = [fontsourceId(family), await fontsourceMeta(family)];
  const w = m?.weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a)) ?? weight;
  const s = m?.styles.includes(style) === false ? 'normal' : style;
  return Promise.all(['latin', ...kitSubsetsFor(String.fromCodePoint(...codePoints), m)].map(async (x) => new Uint8Array(
    await (await fetch(`${await fontsourceAt(id)}files/${id}-${x}-${w}-${s}.woff2`)).arrayBuffer())));
}

/** renderToPdf({ resourceBytes: imageBytes }) */
function imageBytes(fileId) { return loadImage.bytes?.get(fileId); }

/** renderToHtml({ resourceImageUrl: imageUrl }) */
function imageUrl(fileId) {
  const bytes = imageBytes(fileId);
  if (!bytes) return undefined;
  imageUrl.urls ??= new Map();
  if (!imageUrl.urls.has(fileId)) {
    const type = /\.svg$/i.test(fileId) ? 'image/svg+xml' : /\.png$/i.test(fileId) ? 'image/png' : 'image/jpeg';
    imageUrl.urls.set(fileId, URL.createObjectURL(new Blob([bytes], { type })));
  }
  return imageUrl.urls.get(fileId);
}

// ─── 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

- **Las matemáticas necesitan await initMathEngine() antes de componer.** Las fórmulas compuestas antes de que arranque el motor de matemáticas son cajas grises de sustitución. Importa initMathEngine desde https://esm.sh/postext con los demás símbolos y espéralo con await antes de la primera composición; un documento con matemáticas compuesto sin él deja un aviso en la consola. Desde postext 1.5 MathJax viene dentro del paquete como un módulo que initMathEngine descarga, así que la importación normal funciona desde una CDN y ?bundle no hace falta (hasta la 1.4 todos los símbolos tenían que venir de https://esm.sh/postext?bundle). Importa desde una sola URL: dos URL cargan dos motores.

- Escribe la coma decimal como `9{,}8`. Una coma suelta es puntuación para TeX y compone 9, 8 con un espacio.
- Compón el cuadrado de `м/с^2^` en el texto con `^2^`. El carácter ² sale del tipo a otro tamaño y otro peso.

## Créditos

- Receta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Tipografías: PT Serif (OFL-1.1), Golos Text (OFL-1.1)
- Código: MIT · Contenido de ejemplo: CC-BY-4.0

## Relacionadas

- [N.º 028 · Informe de laboratorio: fórmulas, subíndices y curva de pH](https://postext.dev/es/cookbook/lab-report-formulas.md): Un informe de química de cuatro páginas A4 que marca con ~ y ^ las fórmulas y unidades del texto y deja TeX para la reacción y las ecuaciones. · Nivel 3 (Avanzado) · Informes y memorias
- [N.º 008 · Recuadros de libro de texto con código de colores](https://postext.dev/es/cookbook/textbook-box-family.md): Seis tipos de recuadro en tres colores, que se distinguen por una franja con icono, un distintivo, una pestaña numerada, pictogramas o una marca lateral. · Nivel 2 (Intermedio) · Libros de texto
- [N.º 049 · Examen con hoja de respuestas](https://postext.dev/es/cookbook/exam-paper.md): Un examen de historia de cuatro páginas: burbujas y puntos en chips, la puntuación en una tabulación, preguntas numeradas 1, a), i) y renglones de una tabla. · Nivel 2 (Intermedio) · Cuadernos y ejercicios
