# Un chapitre de manuel de mathématiques grec

> Trois pages sur le théorème de Pythagore pour des élèves grecs : sections 3.1 à 3.3 en capitales sans tonos, étiquettes Εικόνα et Πίνακας, formules MathJax.

- Version HTML: https://postext.dev/fr/cookbook/greek-maths-textbook
- Recette Nº 203 · Manuels scolaires · Niveau 3 (Avancé) · Sorties: Canvas, PDF
- Genres: Manuels scolaires
- Nécessite postext ≥ 1.99.1, postext-pdf ≥ 1.99.1 · testée avec 1.99.1, postext-pdf 1.99.1 le 2026-11-29
- Pages: [1](https://postext.dev/cookbook/greek-maths-textbook/en/p01.webp?v=65b5073b), [2](https://postext.dev/cookbook/greek-maths-textbook/en/p02.webp?v=65b5073b), [3](https://postext.dev/cookbook/greek-maths-textbook/en/p03.webp?v=65b5073b)
- PDF: https://postext.dev/cookbook/greek-maths-textbook/en/greek-maths-textbook.pdf?v=65b5073b
- Ouvrir dans le Sandbox: https://postext.dev/fr/sandbox#recipe=greek-maths-textbook&lang=en (.postext: https://postext.dev/cookbook/greek-maths-textbook/en/greek-maths-textbook.postext)
- Dernière mise à jour: 2026-11-29
- Autres langues: [en](https://postext.dev/en/cookbook/greek-maths-textbook.md), [es](https://postext.dev/es/cookbook/greek-maths-textbook.md), [ca](https://postext.dev/ca/cookbook/greek-maths-textbook.md), [de](https://postext.dev/de/cookbook/greek-maths-textbook.md), [el](https://postext.dev/el/cookbook/greek-maths-textbook.md), [it](https://postext.dev/it/cookbook/greek-maths-textbook.md), [pt](https://postext.dev/pt/cookbook/greek-maths-textbook.md), [zh](https://postext.dev/zh/cookbook/greek-maths-textbook.md), [ja](https://postext.dev/ja/cookbook/greek-maths-textbook.md), [ar](https://postext.dev/ar/cookbook/greek-maths-textbook.md)

## En bref

Trois pages d’un manuel scolaire grec de mathématiques sur le triangle rectangle. Les titres de section sont en capitales, le dessin et le tableau portent des étiquettes en grec et les formules emploient des lettres grecques.

## Ce que vous allez composer

Le début du chapitre 3 d’un manuel imaginaire de mathématiques de deuxième année du collège grec, sur le théorème de Pythagore. Un bandeau bleu canard porte ΚΕΦΑΛΑΙΟ 3 et le titre ; suivent les sections 3.1 à 3.3 en capitales espacées. Le théorème repose sur une teinte bleu canard, deux exemples résolus pendent à un liseré ocre et un encadré raconte d’où vient le théorème. La Figure 3.1 dessine les carrés sur les côtés d’un triangle 3-4-5 ; le Tableau 3.1 vérifie cinq triplets pythagoriciens. Le texte est en Source Serif 4 10,5 sur 15 pt, titres et étiquettes en Fira Sans, formules en MathJax. La page est grecque dans toutes les éditions et a été écrite pour cette recette ; seul le colophon change de langue.

**Cette recette répond à:**

- Comment composer un manuel de maths en grec, avec étiquettes grecques, sections numérotées et formules ?
- Comment composer des mathématiques (en ligne, hors texte, équations) et les garder vectorielles dans le PDF ?
- Comment ajouter une figure avec une légende numérotée et la citer dans le texte (« voir fig. 3.2 ») ?
- Comment faire un tableau avec rangées d’en-tête, cellules fusionnées, largeurs de colonne et alignement par cellule ?

## La réponse courte

```js
// script.js, lignes 36–45
// locale 'el' hyphenates the text with the monotonic patterns, names the figures and tables
// Εικόνα and Πίνακας (numbered {h1}.{n}: Εικόνα 3.1), writes «βλ. σ.» style references in
// Greek, and makes every textTransform 'uppercase' drop the tonos: the section titles
// below are written «Τι λέει το θεώρημα» and print ΤΙ ΛΕΕΙ ΤΟ ΘΕΩΡΗΜΑ.
const LOCALE = 'el';
// Between $ and $ is TeX, set by MathJax as vector paths, Greek letters included (\alpha,
// \beta, \gamma). initMathEngine() loads it before the first build.
await initMathEngine();
// Source Serif 4's x-height is 0.475 em, TeX's 0.442 em: the formulas are lifted to match.
const math = { fontSizeScale: 0.475 / 0.442, marginBottom: em(0.3), keepWithLeadIn: true };
```

## Ingrédients

**Enseigne**

- [Mathématiques](https://postext.dev/fr/docs/document-format-inline.md#formules-mathématiques): LaTeX en ligne et en display composé par MathJax, sur la grille et en vectoriel dans toutes les sorties, avec la chimie grâce à mhchem.
- [Figure et Tableau dans votre langue](https://postext.dev/fr/docs/configuration-resources.md#types-de-ressources): defaultResourceTypes(locale) fournit les types intégrés Figure et Tableau, leurs libellés et leurs renvois dans la langue du document.
- [Titres numérotés](https://postext.dev/fr/docs/configuration-headings.md#réglages-par-niveau): Des modèles de numérotation par niveau (1, 1.1, IV, A, 01), que les ouvertures, les titres courants et la table des matières impriment aussi.

**Utilise aussi**

- [Césure et langue du document](https://postext.dev/fr/docs/justification.md#langues-prises-en-charge)
- [Ouvertures composées](https://postext.dev/fr/docs/configuration-headings.md#étendue-et-maquette-avancée)
- [Attributs de titre](https://postext.dev/fr/docs/document-format.md#attributs-de-titre)
- [Chapitres non numérotés](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)
- [Ancrer les éléments de maquette](https://postext.dev/fr/docs/configuration-headers-footers.md#placement-des-éléments)
- [Des citations qui placent les figures](https://postext.dev/fr/docs/document-format-resources.md#renvoi-dans-le-texte-la-forme-principale)
- [Légendes numérotées](https://postext.dev/fr/docs/document-format-resources.md#numérotation-au-premier-renvoi)
- [Style des légendes](https://postext.dev/fr/docs/configuration-resources.md#style-de-légende)
- [Tableaux à partir de données](https://postext.dev/fr/docs/document-format-resources.md#insertion-en-bloc-facultative-placement-explicite-dans-le-texte)
- [Style de tableau](https://postext.dev/fr/docs/configuration-resources.md#style-de-tableau)
- [Encadrés](https://postext.dev/fr/docs/configuration-callouts.md#styles-dencadré)
- [Texte, filets et boîtes dans les maquettes de page](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page)
- [Titres courants et folios](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page)
- [Marges en miroir](https://postext.dev/fr/docs/configuration-page-layout.md#marges-en-miroir)
- [Export PDF](https://postext.dev/fr/docs/configuration-pdf-output.md#générer-des-pdf)
- [Styles de titre](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)
- [Des figures exactement ici](https://postext.dev/fr/docs/document-format-resources.md#insertion-en-bloc-facultative-placement-explicite-dans-le-texte)
- [Titres courants selon le rôle de la page](https://postext.dev/fr/docs/configuration-headers-footers.md#éléments-de-texte)
- [Styles de paragraphe](https://postext.dev/fr/docs/configuration-styles.md#styles-de-paragraphe)
- [Polices intégrées au PDF](https://postext.dev/fr/docs/configuration-pdf-output.md#pourquoi-un-fournisseur-de-polices)
- [Types de ressource personnalisés](https://postext.dev/fr/docs/configuration-resources.md#types-de-ressources)
- [Figures et tableaux comme ressources](https://postext.dev/fr/docs/document-format-resources.md#ressources)
- [Exposants et indices](https://postext.dev/fr/docs/document-format-inline.md#mise-en-forme-en-ligne)

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

- [`bodyText`](https://postext.dev/fr/docs/configuration-text.md#texte-courant), [`calloutStyles`](https://postext.dev/fr/docs/configuration-callouts.md#styles-dencadré), [`captionStyle`](https://postext.dev/fr/docs/configuration-resources.md#style-de-légende), [`colorPalette`](https://postext.dev/fr/docs/configuration-fonts-colors-viewers.md#palette-de-couleurs), [`footer`](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page), [`header`](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page), [`headingStyles`](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre), [`headings`](https://postext.dev/fr/docs/configuration-headings.md#titres), [`layout`](https://postext.dev/fr/docs/configuration-page-layout.md#mise-en-page), [`locale`](https://postext.dev/fr/docs/configuration-language.md#césure), [`math`](https://postext.dev/fr/docs/configuration-lists-math.md#mathématiques), [`orderedLists`](https://postext.dev/fr/docs/configuration-lists-math.md#listes-numérotées), [`page`](https://postext.dev/fr/docs/configuration-page-layout.md#page), [`paragraphStyles`](https://postext.dev/fr/docs/configuration-styles.md#styles-de-paragraphe), [`resourceTypes`](https://postext.dev/fr/docs/configuration-resources.md#types-de-ressources), [`tableStyle`](https://postext.dev/fr/docs/configuration-resources.md#style-de-tableau)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/fr/docs/configuration-programmatic-usage.md#charger-les-polices-avant-la-mise-en-page), [`decompressWoff2`](https://postext.dev/fr/docs/configuration-pdf-output.md#fournisseur-de-polices-dans-le-navigateur-fontsource--woff2), [`defaultResourceTypes`](https://postext.dev/fr/docs/configuration-resources.md#types-de-ressources), [`initMathEngine`](https://postext.dev/fr/docs/document-format-inline.md#formules-mathématiques), [`registerResourceImage`](https://postext.dev/fr/docs/architecture.md#surface-de-lapi), `renderMath`, [`renderPageToCanvas`](https://postext.dev/fr/docs/configuration-programmatic-usage.md#rendre-une-page-en-bitmap), [`renderToPdf`](https://postext.dev/fr/docs/configuration-pdf-output.md#générer-des-pdf)

**Caractères**

- Source Serif 4 (OFL-1.1), Fira Sans (OFL-1.1)

## Préparation

### 1 · Un seul locale pour le texte, les étiquettes et les capitales

Le code est [la réponse courte](https://postext.dev/fr/cookbook/greek-maths-textbook.md#la-réponse-courte) ci-dessus. `locale: 'el'` coupe le texte selon les motifs monotoniques, nomme les types de ressource Εικόνα et Πίνακας et fait ôter le tonos à `textTransform: 'uppercase'` ([langue du document](https://postext.dev/fr/docs/configuration-language.md)). Les mathématiques sont du TeX entre `$`, composé par MathJax après `await initMathEngine()` ([mathématiques](https://postext.dev/fr/docs/configuration-lists-math.md)) ; `\alpha`, `\beta` et `\gamma` donnent les lettres grecques des formules. `math.fontSizeScale` les agrandit pour que leur hauteur d’x rejoigne celle de Source Serif.

### 2 · Chapitre 3, sections 3.1 en capitales

```js
// script.js, lignes 49–69
// # Το Πυθαγόρειο θεώρημα {startAt=3 kicker="Κεφάλαιο"}: startAt makes it chapter 3, so
// its sections, figures and tables count 3.1, 3.2.
const sans = (size, weight, color, extra = {}) => ({ fontFamily: SANS, fontSize: pt(size),
  fontWeight: weight, color: col(color), ...extra });
const chapter = { level: 1, numberingTemplate: '{1}', marginBottom: pt(LEAD),
  advancedDesign: { enabled: true, minHeight: mm(38), slot: { elements: [
    { kind: 'box', id: 'band', style: { backgroundColor: col('teal') },
      placement: { ...at('page', 'top-left'), size: { width: 'fill', height: mm(52) } } },
    { kind: 'text', id: 'kicker', content: '{attr.kicker} {number}', align: 'left',
      ...sans(10, 600, 'paper', { letterSpacing: pt(2.4), textTransform: 'uppercase' }),
      placement: at('container', 'top-left', 0, 4) },
    { kind: 'text', id: 'title', content: '{titleText}', align: 'left', overflow: 'wrap',
      ...sans(28, 700, 'paper', { lineHeight: 1.1 }),
      placement: { ...at('#kicker', 'below', 0, 3), size: { width: mm(MEASURE) } } },
  ] } } };
const section = { level: 2, numberingTemplate: '{1}.{2}', numberSeparator: '  ',
  fontFamily: SANS, fontWeight: 700, fontSize: pt(11.5), lineHeight: pt(LEAD),
  letterSpacing: em(0.06), textTransform: 'uppercase', color: col('teal'),
  marginTop: pt(LEAD), marginBottom: pt(LEAD / 2) };
// ## Ασκήσεις {style="exercises"}: the same section head without a number.
const headingStyles = [{ id: 'exercises', numbered: false }];
```

`# Το Πυθαγόρειο θεώρημα {startAt=3 kicker="Κεφάλαιο"}` donne au chapitre le numéro 3 ; ses sections comptent 3.1, 3.2 et sa figure et son tableau 3.1. Les H2 sont écrits en minuscules, « Τι λέει το θεώρημα », et s’impriment ΤΙ ΛΕΕΙ ΤΟ ΘΕΩΡΗΜΑ. `## Ασκήσεις {style="exercises"}` prend un style de titre avec `numbered: false`, et les exercices ont le même titre sans numéro.

### 3 · Εικόνα et Πίνακας depuis le locale

```js
// script.js, lignes 92–102
// defaultResourceTypes('el') hands over the built-in Greek types, Εικόνα and Πίνακας, numbered
// 3.1 after the chapter; :ref{id="…"} writes «Εικόνα 3.1» in the text. Only the table's
// caption moves, over its table, as school books set them.
const resourceTypes = defaultResourceTypes(LOCALE).map((type) => (type.id === 'table'
  ? { ...type, captionStyle: { position: 'above' } } : type));
const captionStyle = { ...sans(9, 400, 'ink'), gap: mm(2.5), labelColor: col('teal'),
  note: { fontFamily: SANS, fontSize: pt(7.8), color: col('muted') } };
const tableStyle = { rules: 'horizontal', borderColor: col('rule'), borderWidth: pt(0.5),
  headerBackground: col('mist'), headerColor: col('teal'), headerFontFamily: SANS,
  headerFontSize: pt(9), bodyFontFamily: SANS, bodyFontSize: pt(9.5), bodyColor: col('ink'),
  cellPadding: mm(1.6) };
```

`defaultResourceTypes('el')` livre les types grecs intégrés, numérotés par chapitre ([ressources](https://postext.dev/fr/docs/configuration-resources.md)). Seule la légende du tableau change de place, au-dessus de lui. Dans le texte, `Η :ref{id="tetragona" style="full"}` imprime « Η Εικόνα 3.1 » et `Ο :ref{id="triades" style="full"}` « Ο Πίνακας 3.1 » : écrivez l’article dans le Markdown, car εικόνα est féminin et πίνακας masculin.

### 4 · Une figure étiquetée par MathJax

```js
// script.js, lignes 204–250
// An SVG drawn as an image cannot use the page's fonts, so its labels are MathJax paths:
// \mathrm{A}, \mathrm{B} and \Gamma are the Greek capitals Α, Β, Γ (Alpha and Beta share
// their shapes with A and B).
const U = 7; // mm to a unit of the grid
const [FIG_W, FIG_H] = [12 * U, 13 * U]; // mm
const R = (x) => Math.round(x * 100) / 100;
function tex(markup, x, y, size, color = 'ink') { // centred on (x, y)
  const r = renderMath(markup, false, 100);
  const k = size / 1000;
  return `<g transform="translate(${R(x - (r.viewBox.width * k) / 2)} ${R(y + size * 0.35)}) `
    + `scale(${k})" fill="${palette[color]}">`
    + `${r.paths.map((p) => `<path d="${p.d}"/>`).join('')}</g>`;
}
function squares() {
  // Right angle at A; AB = 3 up, AΓ = 4 across; the square on ΒΓ tilted outwards.
  const [ax, ay] = [5 * U, 8 * U];
  const A = [ax, ay]; const B = [ax, ay - 3 * U]; const G = [ax + 4 * U, ay];
  const poly = (pts, fill, stroke = palette.teal) => `<polygon points="${pts.map((p) => p.map(R)
    .join(',')).join(' ')}" fill="${fill}" stroke="${stroke}" stroke-width="0.35"/>`;
  const grid = (o, u, v, n) => { // n × n cells on the square with corner o and sides u, v
    let d = '';
    for (let i = 1; i < n; i++) {
      d += `M${R(o[0] + u[0] * i)} ${R(o[1] + u[1] * i)}l${R(v[0] * n)} ${R(v[1] * n)}`
        + `M${R(o[0] + v[0] * i)} ${R(o[1] + v[1] * i)}l${R(u[0] * n)} ${R(u[1] * n)}`;
    }
    return `<path d="${d}" stroke="${palette.paper}" stroke-width="0.35"/>`;
  };
  const sq = (o, u, v, n, fill) => poly([o, [o[0] + u[0] * n, o[1] + u[1] * n],
    [o[0] + (u[0] + v[0]) * n, o[1] + (u[1] + v[1]) * n], [o[0] + v[0] * n, o[1] + v[1] * n]],
  fill) + grid(o, u, v, n);
  // The squares on β = AΓ (4, below), on γ = AB (3, left) and on α = BΓ (5, up and right).
  const unitBG = [(G[0] - B[0]) / 5, (G[1] - B[1]) / 5]; // along BΓ, one unit
  const out = [-unitBG[1], unitBG[0]].map((x) => -x); // perpendicular, away from A
  let s = sq(A, [U, 0], [0, U], 4, '#9cc9cf') + sq(B, [0, U], [-U, 0], 3, '#cfe3e5')
    + sq(B, unitBG, out, 5, '#7fb3ba') + poly([A, B, G], palette.paper, palette.ink);
  s += `<path d="M${A[0] + 2} ${A[1]}v-2h-2" fill="none" stroke="${palette.ink}" `
    + 'stroke-width="0.3"/>'; // the right angle
  s += tex('\\mathrm{A}', A[0] - 2.2, A[1] + 2.4, 4) + tex('\\mathrm{B}', B[0] - 2.2, B[1] - 2.2, 4)
    + tex('\\Gamma', G[0] + 2.4, G[1] + 2.2, 4)
    + tex('\\gamma = 3', A[0] - 1.5 * U, A[1] - 1.5 * U, 4)
    + tex('\\beta = 4', A[0] + 2 * U, A[1] + 2 * U, 4)
    + tex('\\alpha = 5', (B[0] + G[0]) / 2 + 2.5 * out[0], (B[1] + G[1]) / 2 + 2.5 * out[1], 4);
  // The three squares reach from 2 to 12 units across and from 1 to 12 down: a unit of
  // paper round them.
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${FIG_W * 10}" height="${FIG_H * 10}" `
    + `viewBox="0 0 ${FIG_W} ${FIG_H}"><g transform="translate(${-U} 0)">${s}</g></svg>`;
}
```

Un SVG dessiné comme image ne peut pas employer les fontes de la page ; ses étiquettes sont donc des tracés MathJax obtenus par `renderMath` : `\mathrm{A}`, `\mathrm{B}` et `\Gamma` sont les capitales Α, Β, Γ, puisque alpha et bêta ont la forme de A et B. La figure prend `placement: { position: 'top' }` et la moitié de la justification ; elle ouvre la page 2 et le texte de la page 1 continue sous le théorème.

## La recette complète

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

- Dossier de la recette: https://github.com/drnachio/postext/tree/main/cookbook/greek-maths-textbook

### script.js

```js
// ═══ Postext Cookbook · Nº 203 · A Greek maths textbook page with formulas ═══════════════
// https://postext.dev/en/cookbook/greek-maths-textbook
// Code: MIT · Text: original (CC BY 4.0) · Figure: drawn in code (CC BY 4.0)
// Fonts: Source Serif 4, Fira Sans (SIL OFL 1.1) · Needs postext ≥ 1.99.1
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' | 'el'); the page is Greek
const RECIPE = 'greek-maths-textbook';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// A school book's palette: a deep teal for the chapter, its tint behind the theorem, and an
// ochre for the worked examples.
const palette = {
  ink: '#1b2227', // text
  teal: '#0f6170', // the accent: chapter band, section numbers, figure labels
  mist: '#e3f0f1', // the theorem's ground, the table's head
  ochre: '#b4691b', // examples: stripe and title
  rule: '#c9d3d6', // hairlines
  muted: '#5c676d', // running heads, captions' notes, the colophon
  paper: '#ffffff',
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = Object.entries({ ...palette, 'main-color': palette.teal })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const [SERIF, SANS] = ['Source Serif 4', 'Fira Sans']; // both with Greek
const [BODY, LEAD] = [10.5, 15]; // pt
const [TRIM_W, TRIM_H, TOP, BOTTOM, INNER, OUTER] = [205, 275, 24, 24, 26, 30]; // mm
const MEASURE = TRIM_W - INNER - OUTER; // mm: 149
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });

// #region answer: one Greek locale for the text, the labels and the capitals
// locale 'el' hyphenates the text with the monotonic patterns, names the figures and tables
// Εικόνα and Πίνακας (numbered {h1}.{n}: Εικόνα 3.1), writes «βλ. σ.» style references in
// Greek, and makes every textTransform 'uppercase' drop the tonos: the section titles
// below are written «Τι λέει το θεώρημα» and print ΤΙ ΛΕΕΙ ΤΟ ΘΕΩΡΗΜΑ.
const LOCALE = 'el';
// Between $ and $ is TeX, set by MathJax as vector paths, Greek letters included (\alpha,
// \beta, \gamma). initMathEngine() loads it before the first build.
await initMathEngine();
// Source Serif 4's x-height is 0.475 em, TeX's 0.442 em: the formulas are lifted to match.
const math = { fontSizeScale: 0.475 / 0.442, marginBottom: em(0.3), keepWithLeadIn: true };
// #endregion

// #region headings: a chapter band, then sections numbered 3.1, 3.2 in capitals
// # Το Πυθαγόρειο θεώρημα {startAt=3 kicker="Κεφάλαιο"}: startAt makes it chapter 3, so
// its sections, figures and tables count 3.1, 3.2.
const sans = (size, weight, color, extra = {}) => ({ fontFamily: SANS, fontSize: pt(size),
  fontWeight: weight, color: col(color), ...extra });
const chapter = { level: 1, numberingTemplate: '{1}', marginBottom: pt(LEAD),
  advancedDesign: { enabled: true, minHeight: mm(38), slot: { elements: [
    { kind: 'box', id: 'band', style: { backgroundColor: col('teal') },
      placement: { ...at('page', 'top-left'), size: { width: 'fill', height: mm(52) } } },
    { kind: 'text', id: 'kicker', content: '{attr.kicker} {number}', align: 'left',
      ...sans(10, 600, 'paper', { letterSpacing: pt(2.4), textTransform: 'uppercase' }),
      placement: at('container', 'top-left', 0, 4) },
    { kind: 'text', id: 'title', content: '{titleText}', align: 'left', overflow: 'wrap',
      ...sans(28, 700, 'paper', { lineHeight: 1.1 }),
      placement: { ...at('#kicker', 'below', 0, 3), size: { width: mm(MEASURE) } } },
  ] } } };
const section = { level: 2, numberingTemplate: '{1}.{2}', numberSeparator: '  ',
  fontFamily: SANS, fontWeight: 700, fontSize: pt(11.5), lineHeight: pt(LEAD),
  letterSpacing: em(0.06), textTransform: 'uppercase', color: col('teal'),
  marginTop: pt(LEAD), marginBottom: pt(LEAD / 2) };
// ## Ασκήσεις {style="exercises"}: the same section head without a number.
const headingStyles = [{ id: 'exercises', numbered: false }];
// #endregion

// #region boxes: the theorem on a tint, examples with an ochre stripe, a history note
const title = (color) => sans(8.5, 700, color, { letterSpacing: pt(1.4),
  textTransform: 'uppercase', gap: mm(1.5) });
const calloutStyles = [
  { id: 'theorem', background: col('mist'), backgroundEnabled: true, titleStyle: title('teal'),
    borderRadius: mm(1.5), padding: { top: mm(3.5), right: mm(5), bottom: mm(3), left: mm(5) },
    body: { firstLineIndent: pt(0) }, marginTop: pt(LEAD / 2), marginBottom: pt(LEAD / 2) },
  { id: 'example', backgroundEnabled: false, titleStyle: title('ochre'),
    stripe: { enabled: true, width: pt(2.5), color: col('ochre') },
    padding: { top: mm(0.5), right: mm(0), bottom: mm(0.5), left: mm(5) },
    body: { firstLineIndent: pt(0) }, marginTop: pt(LEAD / 2), marginBottom: pt(LEAD / 2) },
  { id: 'history', backgroundEnabled: false, titleStyle: title('muted'),
    border: { enabled: true, color: col('rule'), width: pt(0.75) },
    padding: { top: mm(3), right: mm(4), bottom: mm(3), left: mm(4) },
    body: { fontSize: pt(9.5), lineHeight: pt(13.5), firstLineIndent: pt(0) },
    marginTop: pt(LEAD / 2), marginBottom: pt(LEAD / 2) },
];
// #endregion

// #region labels: Εικόνα and Πίνακας from the locale, captions in the sans
// defaultResourceTypes('el') hands over the built-in Greek types, Εικόνα and Πίνακας, numbered
// 3.1 after the chapter; :ref{id="…"} writes «Εικόνα 3.1» in the text. Only the table's
// caption moves, over its table, as school books set them.
const resourceTypes = defaultResourceTypes(LOCALE).map((type) => (type.id === 'table'
  ? { ...type, captionStyle: { position: 'above' } } : type));
const captionStyle = { ...sans(9, 400, 'ink'), gap: mm(2.5), labelColor: col('teal'),
  note: { fontFamily: SANS, fontSize: pt(7.8), color: col('muted') } };
const tableStyle = { rules: 'horizontal', borderColor: col('rule'), borderWidth: pt(0.5),
  headerBackground: col('mist'), headerColor: col('teal'), headerFontFamily: SANS,
  headerFontSize: pt(9), bodyFontFamily: SANS, bodyFontSize: pt(9.5), bodyColor: col('ink'),
  cellPadding: mm(1.6) };
// #endregion

// Running heads: the book on the verso, the chapter on the recto, both in capitals.
const small = { fontFamily: SANS, fontWeight: 500, fontSize: pt(7.5), letterSpacing: pt(1.2),
  textTransform: 'uppercase', color: col('muted'), pages: 'body' };
const header = { elements: [
  { kind: 'text', id: 'verso', parity: 'even', content: '{title}', ...small,
    placement: at('page', 'top-left', OUTER, 13) },
  { kind: 'text', id: 'recto', parity: 'odd', content: '{chapterTitle}', ...small, align: 'right',
    placement: at('page', 'top-right', -OUTER, 13) },
] };
const folio = (parity, edge, x) => ({ kind: 'text', id: `folio-${parity}`, parity,
  content: '{pageNumber}', ...sans(9, 700, 'teal'), placement: at('page', edge, x, -12) });
const footer = { elements: [folio('even', 'bottom-left', OUTER),
  folio('odd', 'bottom-right', -OUTER)] };

const config = () => ({
  locale: LOCALE, // written out, never LANG: the page is Greek in every edition
  resourceTypes, colorPalette, math, headingStyles, calloutStyles, captionStyle, tableStyle,
  header, footer,
  page: { width: mm(TRIM_W), height: mm(TRIM_H), dpi: 150,
    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('teal'),
    referenceBold: false, firstLineIndent: mm(5), indentAfterHeading: false,
    minWordSpacing: 0.8, maxWordSpacing: 1.5, maxJustifyTracking: 10 }, // Greek words run long
  headings: { fontFamily: SANS, color: col('ink'), levels: [chapter, section] },
  orderedLists: { fontFamily: SANS, fontWeight: 700, color: col('teal'), marginTop: pt(0) },
  paragraphStyles: [{ id: 'colophon', ...sans(7.5, 400, 'muted'), lineHeight: pt(10),
    textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD),
    hyphenation: { enabled: false } }],
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The chapter (content.text.<lang>.md), then the colophon in the edition's language.
const markdown = [String.raw`---
title: "Μαθηματικά Βʹ Γυμνασίου"
---

# Το Πυθαγόρειο θεώρημα {startAt=3 kicker="Κεφάλαιο"}

Ένας μαραγκός θέλει να ελέγξει αν η γωνία ενός πάγκου είναι πραγματικά ορθή. Μετράει 30 εκατοστά πάνω στη μία πλευρά, 40 πάνω στην άλλη και ενώνει τα δύο σημάδια με το μέτρο: αν η απόσταση βγει ακριβώς 50 εκατοστά, η γωνία είναι ορθή. Το κόλπο αυτό το ήξεραν οι κτίστες εδώ και χιλιάδες χρόνια. Σε αυτό το κεφάλαιο θα δούμε γιατί δουλεύει.

## Τι λέει το θεώρημα

Σε ένα ορθογώνιο τρίγωνο η πλευρά απέναντι από την ορθή γωνία λέγεται υποτείνουσα και είναι η μεγαλύτερη πλευρά του. Οι άλλες δύο λέγονται κάθετες πλευρές. Στο τρίγωνο ΑΒΓ με την ορθή γωνία στο Α ονομάζουμε $\alpha$ την υποτείνουσα ΒΓ, $\beta$ την ΑΓ και $\gamma$ την ΑΒ.

:::callout{type="theorem" title="Πυθαγόρειο θεώρημα"}
Σε κάθε ορθογώνιο τρίγωνο το τετράγωνο της υποτείνουσας είναι ίσο με το άθροισμα των τετραγώνων των δύο κάθετων πλευρών:

$$\alpha^2 = \beta^2 + \gamma^2$$
:::

Η :ref{id="tetragona" style="full"} δείχνει το θεώρημα με εμβαδά. Πάνω σε κάθε πλευρά ενός τριγώνου με κάθετες πλευρές 3 και 4 έχουμε σχεδιάσει ένα τετράγωνο. Τα τετραγωνάκια στις δύο μικρές πλευρές είναι $9 + 16 = 25$, όσα ακριβώς έχει και το τετράγωνο της υποτείνουσας.

::resource{id="tetragona"}

Ισχύει και το αντίστροφο: αν σε ένα τρίγωνο το τετράγωνο της μεγαλύτερης πλευράς ισούται με το άθροισμα των τετραγώνων των δύο άλλων, τότε το τρίγωνο είναι ορθογώνιο. Αυτό ακριβώς χρησιμοποιεί ο μαραγκός της αρχής:

$$30^2 + 40^2 = 900 + 1600 = 2500 = 50^2$$

## Πώς χρησιμοποιούμε το θεώρημα

Όταν ξέρουμε δύο πλευρές ενός ορθογώνιου τριγώνου, το θεώρημα μάς δίνει την τρίτη. Αν λείπει η υποτείνουσα, προσθέτουμε τα τετράγωνα των κάθετων πλευρών και παίρνουμε την τετραγωνική ρίζα. Αν λείπει μια κάθετη πλευρά, αφαιρούμε.

:::callout{type="example" title="Παράδειγμα 1"}
Οι κάθετες πλευρές ενός ορθογώνιου τριγώνου είναι 6 cm και 8 cm. Πόση είναι η υποτείνουσα;

$$\alpha^2 = 6^2 + 8^2 = 36 + 64 = 100, \qquad \alpha = \sqrt{100} = 10 \text{ cm}$$
:::

:::callout{type="example" title="Παράδειγμα 2"}
Μια σκάλα μήκους 5 m ακουμπά σε έναν τοίχο. Η βάση της απέχει 1,4 m από τον τοίχο. Σε πόσο ύψος φτάνει η κορυφή της; Η σκάλα είναι η υποτείνουσα, άρα

$$\beta^2 = 5^2 - 1{,}4^2 = 25 - 1{,}96 = 23{,}04, \qquad \beta = \sqrt{23{,}04} = 4{,}8 \text{ m}$$
:::

## Πυθαγόρειες τριάδες

Όταν τρεις φυσικοί αριθμοί ικανοποιούν τη σχέση $\alpha^2 = \beta^2 + \gamma^2$, λέμε ότι σχηματίζουν μια πυθαγόρεια τριάδα. Η πιο γνωστή είναι η 3, 4, 5. Ο :ref{id="triades" style="full"} δίνει μερικές ακόμη και επαληθεύει την καθεμία.

::resource{id="triades"}

:::callout{type="history" title="Λίγη ιστορία"}
Το θεώρημα πήρε το όνομά του από τον Πυθαγόρα τον Σάμιο, που έζησε τον 6ο αιώνα π.Χ. Η σχέση όμως ήταν γνωστή πολύ νωρίτερα: μια πήλινη πινακίδα από τη Βαβυλώνα, η Plimpton 322, γραμμένη γύρω στο 1800 π.Χ., απαριθμεί πυθαγόρειες τριάδες. Η πρώτη απόδειξη που σώζεται βρίσκεται στα Στοιχεία του Ευκλείδη, στην πρόταση 47 του πρώτου βιβλίου.
:::

## Ασκήσεις {style="exercises"}

1. Οι κάθετες πλευρές ενός ορθογώνιου τριγώνου είναι 9 cm και 12 cm. Να βρείτε την υποτείνουσα.
2. Η υποτείνουσα ενός ορθογώνιου τριγώνου είναι 26 cm και μία κάθετη πλευρά του 10 cm. Να βρείτε την άλλη.
3. Είναι ορθογώνιο ένα τρίγωνο με πλευρές 6 cm, 7 cm και 9 cm; Να δικαιολογήσετε την απάντησή σας.
4. Ένα οικόπεδο σχήματος ορθογωνίου έχει διαστάσεις 30 m και 40 m. Πόσο μήκος έχει η διαγώνιός του;
`, String.raw`:::paragraphs{style="colophon"}
A page from an imaginary second-year secondary school textbook, written in Greek for this recipe. Set with Postext in Source Serif 4 and Fira Sans (SIL OFL); formulas by MathJax. Text and figure are original and licensed CC BY 4.0.
:::
`].join('\n\n');

// #region figure: the squares on the sides of a 3-4-5 triangle, labelled by MathJax
// An SVG drawn as an image cannot use the page's fonts, so its labels are MathJax paths:
// \mathrm{A}, \mathrm{B} and \Gamma are the Greek capitals Α, Β, Γ (Alpha and Beta share
// their shapes with A and B).
const U = 7; // mm to a unit of the grid
const [FIG_W, FIG_H] = [12 * U, 13 * U]; // mm
const R = (x) => Math.round(x * 100) / 100;
function tex(markup, x, y, size, color = 'ink') { // centred on (x, y)
  const r = renderMath(markup, false, 100);
  const k = size / 1000;
  return `<g transform="translate(${R(x - (r.viewBox.width * k) / 2)} ${R(y + size * 0.35)}) `
    + `scale(${k})" fill="${palette[color]}">`
    + `${r.paths.map((p) => `<path d="${p.d}"/>`).join('')}</g>`;
}
function squares() {
  // Right angle at A; AB = 3 up, AΓ = 4 across; the square on ΒΓ tilted outwards.
  const [ax, ay] = [5 * U, 8 * U];
  const A = [ax, ay]; const B = [ax, ay - 3 * U]; const G = [ax + 4 * U, ay];
  const poly = (pts, fill, stroke = palette.teal) => `<polygon points="${pts.map((p) => p.map(R)
    .join(',')).join(' ')}" fill="${fill}" stroke="${stroke}" stroke-width="0.35"/>`;
  const grid = (o, u, v, n) => { // n × n cells on the square with corner o and sides u, v
    let d = '';
    for (let i = 1; i < n; i++) {
      d += `M${R(o[0] + u[0] * i)} ${R(o[1] + u[1] * i)}l${R(v[0] * n)} ${R(v[1] * n)}`
        + `M${R(o[0] + v[0] * i)} ${R(o[1] + v[1] * i)}l${R(u[0] * n)} ${R(u[1] * n)}`;
    }
    return `<path d="${d}" stroke="${palette.paper}" stroke-width="0.35"/>`;
  };
  const sq = (o, u, v, n, fill) => poly([o, [o[0] + u[0] * n, o[1] + u[1] * n],
    [o[0] + (u[0] + v[0]) * n, o[1] + (u[1] + v[1]) * n], [o[0] + v[0] * n, o[1] + v[1] * n]],
  fill) + grid(o, u, v, n);
  // The squares on β = AΓ (4, below), on γ = AB (3, left) and on α = BΓ (5, up and right).
  const unitBG = [(G[0] - B[0]) / 5, (G[1] - B[1]) / 5]; // along BΓ, one unit
  const out = [-unitBG[1], unitBG[0]].map((x) => -x); // perpendicular, away from A
  let s = sq(A, [U, 0], [0, U], 4, '#9cc9cf') + sq(B, [0, U], [-U, 0], 3, '#cfe3e5')
    + sq(B, unitBG, out, 5, '#7fb3ba') + poly([A, B, G], palette.paper, palette.ink);
  s += `<path d="M${A[0] + 2} ${A[1]}v-2h-2" fill="none" stroke="${palette.ink}" `
    + 'stroke-width="0.3"/>'; // the right angle
  s += tex('\\mathrm{A}', A[0] - 2.2, A[1] + 2.4, 4) + tex('\\mathrm{B}', B[0] - 2.2, B[1] - 2.2, 4)
    + tex('\\Gamma', G[0] + 2.4, G[1] + 2.2, 4)
    + tex('\\gamma = 3', A[0] - 1.5 * U, A[1] - 1.5 * U, 4)
    + tex('\\beta = 4', A[0] + 2 * U, A[1] + 2 * U, 4)
    + tex('\\alpha = 5', (B[0] + G[0]) / 2 + 2.5 * out[0], (B[1] + G[1]) / 2 + 2.5 * out[1], 4);
  // The three squares reach from 2 to 12 units across and from 1 to 12 down: a unit of
  // paper round them.
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${FIG_W * 10}" height="${FIG_H * 10}" `
    + `viewBox="0 0 ${FIG_W} ${FIG_H}"><g transform="translate(${-U} 0)">${s}</g></svg>`;
}
// #endregion

// #region table: Pythagorean triples, computed, so every row checks
const TRIPLES = [[3, 4, 5], [5, 12, 13], [8, 15, 17], [7, 24, 25], [20, 21, 29]];
const cell = (content, extra = {}) => ({ content, align: 'center', ...extra });
const triples = { headerRowCount: 1, rows: [
  ['$\\beta$', '$\\gamma$', '$\\alpha$', '$\\beta^2 + \\gamma^2$', '$\\alpha^2$']
    .map((head) => cell(head, { isHeader: true })),
  ...TRIPLES.map(([b, g, a]) => [b, g, a, `${b * b} + ${g * g} = ${b * b + g * g}`, a * a]
    .map((value) => cell(String(value)))),
] };
// #endregion

const resources = [
  { id: 'tetragona', typeId: 'figure', kind: 'svg', createdAt: 0, updatedAt: 0,
    svg: { fileId: 'squares.svg', width: FIG_W * 10, height: FIG_H * 10 },
    // At the head of a page, half the measure wide.
    placement: { position: 'top', width: 0.5, align: 'center' },
    caption: 'Τα τετράγωνα στις πλευρές του ορθογώνιου τριγώνου ΑΒΓ με $\\beta = 4$ και '
      + '$\\gamma = 3$: τα 16 και τα 9 τετραγωνάκια μαζί είναι όσα τα 25 του τετραγώνου της '
      + 'υποτείνουσας.',
    altText: 'Ορθογώνιο τρίγωνο ΑΒΓ με την ορθή γωνία στο Α και ένα τετράγωνο χωρισμένο σε '
      + 'τετραγωνάκια πάνω σε κάθε πλευρά: 9 στην ΑΒ, 16 στην ΑΓ και 25 στην ΒΓ.' },
  { id: 'triades', typeId: 'table', kind: 'table', createdAt: 0, updatedAt: 0,
    table: { model: triples }, placement: { position: 'here' },
    caption: 'Πέντε πυθαγόρειες τριάδες.',
    note: 'Πολλαπλασιάζοντας μια τριάδα με τον ίδιο αριθμό παίρνουμε νέα: 6, 8, 10 ή 9, 12, 15.' },
];

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { // every face the pages paint, loaded before the first build
  'Source Serif 4': ['400', '400i', '700'], // SERIF: the text and the boxes
  'Fira Sans': ['400', '500', '600', '700'], // SANS: headings, box titles, captions, table, heads
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
await loadSvg('squares.svg', squares());
const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
showPages(doc, { title: 'Το Πυθαγόρειο θεώρημα' });
offerPdf(() => renderToPdf(doc, { fontProvider: fontsourceProvider, 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 ───────────────────────────────────────────────────────────────────────
```

## Erreurs fréquentes

- **Les maths demandent await initMathEngine() avant la première construction.** Les formules mises en page avant que le moteur de maths ne tourne sont des boîtes grises de remplacement. Importez initMathEngine depuis https://esm.sh/postext avec les autres symboles et attendez-le (await) avant la première construction ; un document avec des maths construit sans lui affiche un avertissement dans la console. Depuis postext 1.5, MathJax est livré dans le paquet sous forme d’un module que initMathEngine récupère : l’import simple fonctionne donc depuis un CDN et ?bundle n’est pas nécessaire (jusqu’à la 1.4, chaque symbole devait venir de https://esm.sh/postext?bundle). N’importez que depuis une seule URL : deux URL chargent deux moteurs.

- Gardez l’unité sur la ligne de son nombre avec une espace insécable (U+00A0) dans le Markdown : un « 10 cm » coupé sur deux lignes se lit mal dans un manuel.
- Une formule est un mot insécable. Une phrase qui finit par `$30^2 + 40^2 = 900 + 1600 = 2500 = 50^2$` étire les lignes qui la précèdent ; ici la somme est en formule centrée, entre `$$`.
- Écrivez les noms de triangles, ΑΒΓ, en capitales grecques dans le texte, pas entre `$` : MathJax les mettrait dans son propre italique.

## Crédits

- Recette: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Caractères: Source Serif 4 (OFL-1.1), Fira Sans (OFL-1.1)
- Code: MIT · Contenu d’exemple: CC-BY-4.0

## Recettes liées

- [Nº 028 · Compte rendu de TP : formules, indices et courbe de titrage](https://postext.dev/fr/cookbook/lab-report-formulas.md): Un compte rendu de chimie de quatre pages A4 qui note formules et unités du texte avec ~ et ^ et garde TeX pour la réaction et les équations. · Niveau 3 (Avancé) · Rapports
- [Nº 002 · Un article sur deux colonnes à équations numérotées](https://postext.dev/fr/cookbook/journal-article-with-maths.md): Un article de physique sur deux colonnes dont les formules en ligne et les sept équations numérotées, composées par MathJax, restent vectorielles dans le PDF. · Niveau 3 (Avancé) · Articles et publications universitaires
- [Nº 201 · Un roman grec coupé selon le grec monotonique](https://postext.dev/fr/cookbook/monotonic-greek-novel.md): Le premier chapitre de « Η τιμή και το χρήμα » de Theotokis en livre de 13,5 × 20,5 cm : motifs du grec monotonique, guillemets «» et capitales sans accent. · Niveau 2 (Intermédiaire) · Fiction, théâtre et prose littéraire
