# Un paragrafo di un libro di fisica russo

> Il § 14 di un libro di fisica russo: Рис. 1, titolo di tabella su due righe, tg e arctg nelle formule, note per pagina e liste 1) а).

- Versione HTML: https://postext.dev/it/cookbook/russian-physics-textbook
- Ricetta Nº 207 · Libri di testo · Livello 3 (Avanzato) · Output: Canvas, PDF
- Generi: Libri di testo
- Richiede postext ≥ 1.100.0, postext-pdf ≥ 1.100.0 · provata con 1.100.0, postext-pdf 1.100.0 il 2026-12-02
- Pagine: [71](https://postext.dev/cookbook/russian-physics-textbook/en/p01.webp?v=48200ba5), [72](https://postext.dev/cookbook/russian-physics-textbook/en/p02.webp?v=48200ba5), [73](https://postext.dev/cookbook/russian-physics-textbook/en/p03.webp?v=48200ba5), [74](https://postext.dev/cookbook/russian-physics-textbook/en/p04.webp?v=48200ba5)
- PDF: https://postext.dev/cookbook/russian-physics-textbook/en/russian-physics-textbook.pdf?v=48200ba5
- Apri nella Sandbox: https://postext.dev/it/sandbox#recipe=russian-physics-textbook&lang=en (.postext: https://postext.dev/cookbook/russian-physics-textbook/en/russian-physics-textbook.postext)
- Ultimo aggiornamento: 2026-12-02
- Altre lingue: [en](https://postext.dev/en/cookbook/russian-physics-textbook.md), [es](https://postext.dev/es/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), [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)

## In breve

Quattro pagine di un libro scolastico russo di fisica su un corpo in discesa. Il disegno, la tabella, il problema svolto e le domande hanno etichette e numeri dei libri scolastici russi.

## Che cosa comporrai

Un paragrafo di un libro immaginario di fisica della nona classe, su un corpo sul piano inclinato, a 145 × 215 mm, il formato che gli editori russi chiamano 60 × 90/16. Si apre con «§ 14» su una linguetta blu. La Рис. 1 disegna le forze; la Таблица 1 dà l’attrito di sei coppie di materiali, con l’angolo limite calcolato da tg α. Un riquadro dice che cosa ricordare e un problema svolto sta in due celle, «Дано» e «Решение». Le domande si numerano 1), 2) e, dentro, а), б). Il testo è PT Serif 10 su 13,6 pt, titoli e didascalie Golos Text, le formule MathJax. La pagina è russa in tutte le edizioni ed è scritta per questa ricetta; solo il colophon cambia lingua.

**Questa ricetta risponde a:**

- Come compongo un libro scolastico russo con Рис., titolo di tabella su due righe, liste 1) а) e tg?
- Come compongo formule matematiche (in linea, in display, equazioni) mantenendole vettoriali nel PDF?
- Come aggiungo una figura con didascalia numerata e la cito nel testo («vedi Fig. 3.2»)?
- Come personalizzo gli elenchi: punti elenco per livello, numerazione (a)/(i), caselle di controllo, spaziature che restano sulla griglia?

## La risposta breve

```js
// script.js, righe 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
```

## Ingredienti

**Insegna**

- [Le lingue in cirillico come lingua del documento](https://postext.dev/it/docs/cyrillic-layout.md#iniziare-un-libro-in-cirillico): locale 'ru', 'uk', 'be', 'bg', 'sr', 'mk', 'kk', 'ky', 'tt', 'ba', 'tg' o 'mn' dà al libro la sillabazione, le didascalie, i titoli delle tabelle, le note, i numeri in lettere, i formati di foglio e il verso del dorso della sua lingua.
- [Matematica](https://postext.dev/it/docs/document-format-inline.md#formule-matematiche): LaTeX in linea e in display composto da MathJax, sulla griglia e vettoriale in ogni output, con la chimica tramite mhchem.
- [Figura e Tabella nella tua lingua](https://postext.dev/it/docs/configuration-resources.md#tipi-di-risorsa): defaultResourceTypes(locale) fornisce i tipi integrati Figura e Tabella, con etichette e rimandi nella lingua del documento.

**Usa anche**

- [Parole tenute insieme a fine riga](https://postext.dev/it/docs/cyrillic-layout.md#parole-tenute-insieme)
- [Sillabazione e lingua del documento](https://postext.dev/it/docs/justification.md#lingue-supportate)
- [Note a piè di pagina](https://postext.dev/it/docs/document-format-notes-references.md#note-a-piè-di-pagina)
- [Elenchi numerati](https://postext.dev/it/docs/configuration-lists-math.md#elenchi-numerati)
- [Aperture progettate](https://postext.dev/it/docs/configuration-headings.md#estensione-e-grafica-avanzata)
- [Attributi dei titoli](https://postext.dev/it/docs/document-format.md#attributi-dei-titoli)
- [Citazioni che collocano le figure](https://postext.dev/it/docs/document-format-resources.md#rimando-in-linea-la-forma-principale)
- [Didascalie numerate](https://postext.dev/it/docs/document-format-resources.md#numerazione-al-primo-rimando)
- [Stile delle didascalie](https://postext.dev/it/docs/configuration-resources.md#stile-delle-didascalie)
- [Tabelle dai dati](https://postext.dev/it/docs/document-format-resources.md#inserimento-di-blocco-facoltativo-collocazione-in-linea-esplicita)
- [Stile delle tabelle](https://postext.dev/it/docs/configuration-resources.md#stile-delle-tabelle)
- [Riquadri](https://postext.dev/it/docs/configuration-callouts.md#stili-dei-riquadri)
- [Testo, filetti e riquadri nei progetti di pagina](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina)
- [Testatine e folio](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina)
- [Margini speculari](https://postext.dev/it/docs/configuration-page-layout.md#margini-speculari)
- [Esportazione in PDF](https://postext.dev/it/docs/configuration-pdf-output.md#generare-pdf)
- [Titoli numerati](https://postext.dev/it/docs/configuration-headings.md#personalizzazioni-per-livello)
- [Stili di titolo](https://postext.dev/it/docs/configuration-styles.md#stili-dei-titoli)
- [Figure proprio qui](https://postext.dev/it/docs/document-format-resources.md#inserimento-di-blocco-facoltativo-collocazione-in-linea-esplicita)
- [Interruzioni di pagina e di colonna](https://postext.dev/it/docs/document-format-directives.md#pagebreak)
- [Testatine secondo il ruolo della pagina](https://postext.dev/it/docs/configuration-headers-footers.md#elementi-di-testo)
- [Stili di paragrafo](https://postext.dev/it/docs/configuration-styles.md#stili-di-paragrafo)
- [Font incorporati nel PDF](https://postext.dev/it/docs/configuration-pdf-output.md#perché-un-provider-di-font)
- [Tipi di risorsa personalizzati](https://postext.dev/it/docs/configuration-resources.md#tipi-di-risorsa)
- [Figure e tabelle come risorse](https://postext.dev/it/docs/document-format-resources.md#risorse)
- [Pagine preliminari in numeri romani](https://postext.dev/it/docs/document-format-directives.md#numbering)
- [Apici e pedici](https://postext.dev/it/docs/document-format-inline.md#formattazione-in-linea)
- [Stili di tabella con nome](https://postext.dev/it/docs/configuration-resources.md#stili-di-tabella-con-nome)

**La configurazione in breve**

- [`bodyText`](https://postext.dev/it/docs/configuration-text.md#testo-corrente), [`calloutStyles`](https://postext.dev/it/docs/configuration-callouts.md#stili-dei-riquadri), [`captionStyle`](https://postext.dev/it/docs/configuration-resources.md#stile-delle-didascalie), [`colorPalette`](https://postext.dev/it/docs/configuration-fonts-colors-viewers.md#tavolozza-dei-colori), [`footer`](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina), [`footnotes`](https://postext.dev/it/docs/configuration-notes-references.md#note-a-piè-di-pagina), [`header`](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina), [`headingStyles`](https://postext.dev/it/docs/configuration-styles.md#stili-dei-titoli), [`headings`](https://postext.dev/it/docs/configuration-headings.md#titoli), [`layout`](https://postext.dev/it/docs/configuration-page-layout.md#impaginazione), [`locale`](https://postext.dev/it/docs/configuration-language.md#sillabazione), [`math`](https://postext.dev/it/docs/configuration-lists-math.md#matematica), [`orderedLists`](https://postext.dev/it/docs/configuration-lists-math.md#elenchi-numerati), [`page`](https://postext.dev/it/docs/configuration-page-layout.md#pagina), [`paragraphStyles`](https://postext.dev/it/docs/configuration-styles.md#stili-di-paragrafo), [`resourceTypes`](https://postext.dev/it/docs/configuration-resources.md#tipi-di-risorsa), [`tableStyle`](https://postext.dev/it/docs/configuration-resources.md#stile-delle-tabelle), [`tableStyles`](https://postext.dev/it/docs/configuration-resources.md#stili-di-tabella-con-nome)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/it/docs/configuration-programmatic-usage.md#caricare-i-font-prima-dellimpaginazione), [`decompressWoff2`](https://postext.dev/it/docs/configuration-pdf-output.md#provider-di-font-per-il-browser-fontsource--woff2), [`defaultResourceTypes`](https://postext.dev/it/docs/configuration-resources.md#tipi-di-risorsa), [`initMathEngine`](https://postext.dev/it/docs/document-format-inline.md#formule-matematiche), [`registerResourceImage`](https://postext.dev/it/docs/architecture.md#superficie-dellapi), `renderMath`, [`renderPageToCanvas`](https://postext.dev/it/docs/configuration-programmatic-usage.md#rasterizzare-una-pagina), [`renderToPdf`](https://postext.dev/it/docs/configuration-pdf-output.md#generare-pdf)

**Caratteri**

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

## Preparazione

### 1 · Un solo locale per testo, note ed etichette

Il codice è [la risposta breve](https://postext.dev/it/cookbook/russian-physics-textbook.md#la-risposta-breve) qui sopra. `locale: 'ru'` sillaba con gli schemi russi, tiene в, на o с sulla riga della parola che segue e 0,4 con кг, e riconta le note in ogni pagina ([composizione in cirillico](https://postext.dev/it/docs/cyrillic-layout.md)). `defaultResourceTypes('ru')` consegna Рис. con la didascalia sotto e Таблица con il numero a destra e il titolo centrato sotto ([risorse](https://postext.dev/it/docs/configuration-resources.md)). `numberFormat: 'lower-russian'` ordina una lista con а), б), в) e salta ё, й, ъ, ы e ь ([liste e matematica](https://postext.dev/it/docs/configuration-lists-math.md)). MathJax conosce `\tg`, `\ctg` e `\arctg`, i nomi della scuola russa.

### 2 · Il § 14 su una linguetta

```js
// script.js, righe 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="…"}` dà al paragrafo il numero 14, e `numberingTemplate: '§ {1}'` lo stampa come § 14. Il disegno posa un riquadro blu al vivo dall’angolo della pagina fino al numero; `minHeight` dà cinque righe all’apertura. La testatina della pagina dispari prende lo stesso numero con `{chapterNumber}`. `## Вопросы {style="plain"}` usa lo stile di titolo che mette in rosso ciò che fa lo studente.

### 3 · Un riquadro per la regola, una banda per il problema

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

Due stili di riquadro condividono il corpo e si distinguono per il fondo: `rule` mette «Запомните» su azzurro dietro una banda di 3 pt, `problem` ha una banda rossa e nessun fondo. `firstLineIndent: 0` toglie il rientro alla prima riga del riquadro, mentre i capoversi della pagina hanno tutti 1,5 em.

### 4 · Una figura con le lettere di MathJax

```js
// script.js, righe 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 disegnato come immagine non può usare i caratteri della pagina, quindi le sue lettere sono tracciati di MathJax dati da `renderMath`, con `\vec{N}` e `m\vec{g}` come nel testo. La pendenza è di 25°, e la freccia N è lunga quanto la componente di mg perpendicolare al piano, come nella fisica. `:ref{id="sily"}` stampa «рис. 1» nella frase.

### 5 · Una tabella calcolata e «Дано | Решение»

```js
// script.js, righe 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)` riempie la colonna degli angoli e `replace('.', ',')` scrive la virgola decimale. La soluzione è una seconda tabella di una riga: manca `headerRowCount` e il tipo di risorsa `given` non ha etichetta, così il riquadro mostra due celle senza titolo. `:ref{id="ugly" text="таблице 1"}` porta la parola nel caso che la frase chiede.

## La ricetta completa

Un unico file, composto a partire dalla cartella della ricetta con il testo di esempio e il kit comune del Ricettario già inclusi; costruisce la propria pagina. Per eseguirlo, mettilo in uno `<script type="module">` di una pagina vuota, oppure incollalo nel pannello JS di un nuovo pen di CodePen (come modulo). Importa postext da esm.sh: non c’è niente da installare né da compilare.

- Cartella della ricetta: 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 = 'en'; // @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"}
A section of an imaginary Russian physics textbook, written for this recipe. Set with Postext in PT Serif and Golos Text (SIL OFL); formulas by MathJax. Text and diagram are original, 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 ───────────────────────────────────────────────────────────────────────
```

## Errori frequenti

- **La matematica richiede await initMathEngine() prima della prima costruzione.** Le formule impaginate prima che il motore matematico sia in funzione sono riquadri segnaposto grigi. Importa initMathEngine da https://esm.sh/postext insieme agli altri simboli e attendilo con await prima della prima costruzione; un documento con matematica costruito senza di esso stampa un avviso nella console. Da postext 1.5 MathJax è incluso nel pacchetto come un modulo che initMathEngine scarica, quindi l’import semplice funziona da una CDN e ?bundle non serve (fino alla 1.4 ogni simbolo doveva venire da https://esm.sh/postext?bundle). Importa da un solo URL: due URL caricano due motori.

- Scrivi la virgola decimale come `9{,}8`. Una virgola sola è punteggiatura per TeX e compone 9, 8 con uno spazio.
- Componi il quadrato di `м/с^2^` nel testo con `^2^`. Il carattere ² esce dal font in un’altra misura e un altro peso.

## Crediti

- Ricetta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Caratteri: PT Serif (OFL-1.1), Golos Text (OFL-1.1)
- Codice: MIT · Contenuto di esempio: CC-BY-4.0

## Ricette correlate

- [Nº 028 · Relazione di laboratorio: formule, pedici e una curva](https://postext.dev/it/cookbook/lab-report-formulas.md): Una relazione di chimica di quattro pagine A4 che segna formule e unità nel testo con ~ e ^ e riserva il TeX alla reazione e alle equazioni. · Livello 3 (Avanzato) · Rapporti
- [Nº 008 · Una famiglia di riquadri da manuale, distinti per colore](https://postext.dev/it/cookbook/textbook-box-family.md): Sei tipi di riquadro da manuale in tre colori, distinti da una banda con icona, un bollino, una linguetta numerata, dei pittogrammi o un segno fuori dal bordo. · Livello 2 (Intermedio) · Libri di testo
- [Nº 049 · Un compito d’esame con il foglio delle risposte](https://postext.dev/it/cookbook/exam-paper.md): Un esame di storia di quattro pagine su US Letter: bolle e punteggi come chip, punteggi su un tabulatore, domande numerate 1, a), i) e righe da una tabella. · Livello 2 (Intermedio) · Quaderni ed eserciziari
