# Ein Kapitel aus einem griechischen Mathematikbuch

> Drei Seiten zum Satz des Pythagoras für griechische Schüler: Abschnitte 3.1 bis 3.3 in Versalien ohne Tonos, Εικόνα und Πίνακας, Formeln mit MathJax.

- HTML-Fassung: https://postext.dev/de/cookbook/greek-maths-textbook
- Rezept Nº 203 · Schulbücher · Stufe 3 (Fortgeschritten) · Ausgaben: Canvas, PDF
- Gattungen: Lehrbücher
- Benötigt postext ≥ 1.99.1, postext-pdf ≥ 1.99.1 · getestet mit 1.99.1, postext-pdf 1.99.1 am 2026-11-29
- Seiten: [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
- In der Sandbox öffnen: https://postext.dev/de/sandbox#recipe=greek-maths-textbook&lang=en (.postext: https://postext.dev/cookbook/greek-maths-textbook/en/greek-maths-textbook.postext)
- Zuletzt aktualisiert: 2026-11-29
- Andere Sprachen: [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), [el](https://postext.dev/el/cookbook/greek-maths-textbook.md), [fr](https://postext.dev/fr/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)

## Kurz gesagt

Drei Seiten aus einem griechischen Schulbuch für Mathematik über das rechtwinklige Dreieck. Die Abschnittstitel stehen in Großbuchstaben, Zeichnung und Tabelle tragen griechische Bezeichnungen und die Formeln griechische Buchstaben.

## Was Sie setzen

Den Anfang von Kapitel 3 eines erdachten Mathematikbuchs für die zweite Klasse des griechischen Gymnasiums, zum Satz des Pythagoras. Ein petrolfarbenes Band trägt ΚΕΦΑΛΑΙΟ 3 und den Titel; es folgen die Abschnitte 3.1 bis 3.3 in gesperrten Versalien. Der Lehrsatz steht auf einem petrolfarbenen Fond, zwei Rechenbeispiele hängen an einem ockerfarbenen Streifen, und ein gerahmter Kasten erzählt, woher der Satz kommt. Abbildung 3.1 zeichnet die Quadrate über den Seiten eines 3-4-5-Dreiecks; Tabelle 3.1 prüft fünf pythagoreische Tripel. Der Text ist Source Serif 4 in 10,5 auf 15 pt, Überschriften und Bezeichnungen Fira Sans, die Formeln MathJax. Die Seite ist in jeder Ausgabe griechisch und für dieses Rezept geschrieben; nur das Kolophon wechselt die Sprache.

**Dieses Rezept beantwortet:**

- Wie setze ich ein Mathematikbuch auf Griechisch, mit griechischen Bildbezeichnungen, Abschnitten und Formeln?
- Wie setze ich Formeln (im Text, abgesetzt, Gleichungen) und behalte sie im PDF als Vektoren?
- Wie füge ich eine Abbildung mit nummerierter Bildunterschrift ein und verweise im Text darauf („siehe Abb. 3.2“)?
- Wie erstelle ich eine Tabelle mit Kopfzeilen, verbundenen Zellen, Spaltenbreiten und Ausrichtung je Zelle?

## Die kurze Antwort

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

## Zutaten

**Zeigt**

- [Mathematik](https://postext.dev/de/docs/document-format-inline.md#mathematische-formeln): LaTeX im Text und abgesetzt, gesetzt mit MathJax, auf dem Raster und als Vektor in jeder Ausgabe, Chemie über mhchem.
- [Abbildung und Tabelle in Ihrer Sprache](https://postext.dev/de/docs/configuration-resources.md#ressourcentypen): defaultResourceTypes(locale) liefert die eingebauten Typen Abbildung und Tabelle, ihre Bezeichnungen und Verweise in der Sprache des Dokuments.
- [Nummerierte Überschriften](https://postext.dev/de/docs/configuration-headings.md#überschreibungen-pro-ebene): Nummerierungsvorlagen je Ebene (1, 1.1, IV, A, 01), die auch die Auftakte, Kolumnentitel und das Inhaltsverzeichnis drucken.

**Verwendet außerdem**

- [Silbentrennung und Dokumentsprache](https://postext.dev/de/docs/justification.md#unterstützte-sprachen)
- [Gestaltete Auftakte](https://postext.dev/de/docs/configuration-headings.md#seitenbreite-und-erweiterte-gestaltung)
- [Überschriftenattribute](https://postext.dev/de/docs/document-format.md#attribute-von-überschriften)
- [Kapitel ohne Nummer](https://postext.dev/de/docs/configuration-styles.md#überschriftenstile)
- [Gestaltungselemente verankern](https://postext.dev/de/docs/configuration-headers-footers.md#platzierung-von-elementen)
- [Verweise, die Abbildungen platzieren](https://postext.dev/de/docs/document-format-resources.md#verweis-im-text-die-hauptform)
- [Nummerierte Bildunterschriften](https://postext.dev/de/docs/document-format-resources.md#nummerierung-beim-ersten-verweis)
- [Format der Bildunterschrift](https://postext.dev/de/docs/configuration-resources.md#legendenstil)
- [Tabellen aus Daten](https://postext.dev/de/docs/document-format-resources.md#blockeinbettung-optional-ausdrückliche-platzierung-im-text)
- [Tabellenformat](https://postext.dev/de/docs/configuration-resources.md#tabellenstil)
- [Kästen](https://postext.dev/de/docs/configuration-callouts.md#kastenstile)
- [Text, Linien und Kästen in Seitengestaltungen](https://postext.dev/de/docs/configuration-headers-footers.md#kopf--und-fußzeilen)
- [Kolumnentitel und Seitenzahlen](https://postext.dev/de/docs/configuration-headers-footers.md#kopf--und-fußzeilen)
- [Gespiegelte Ränder](https://postext.dev/de/docs/configuration-page-layout.md#gespiegelte-ränder)
- [PDF-Export](https://postext.dev/de/docs/configuration-pdf-output.md#pdfs-erzeugen)
- [Überschriftenformate](https://postext.dev/de/docs/configuration-styles.md#überschriftenstile)
- [Abbildungen genau hier](https://postext.dev/de/docs/document-format-resources.md#blockeinbettung-optional-ausdrückliche-platzierung-im-text)
- [Kopfzeilen nach Seitenrolle](https://postext.dev/de/docs/configuration-headers-footers.md#textelemente)
- [Absatzformate](https://postext.dev/de/docs/configuration-styles.md#absatzformate)
- [Im PDF eingebettete Schriften](https://postext.dev/de/docs/configuration-pdf-output.md#warum-ein-font-provider)
- [Eigene Ressourcentypen](https://postext.dev/de/docs/configuration-resources.md#ressourcentypen)
- [Abbildungen und Tabellen als Ressourcen](https://postext.dev/de/docs/document-format-resources.md#ressourcen)
- [Hoch- und Tiefstellung](https://postext.dev/de/docs/document-format-inline.md#inline-formatierung)

**Die Konfiguration auf einen Blick**

- [`bodyText`](https://postext.dev/de/docs/configuration-text.md#fließtext), [`calloutStyles`](https://postext.dev/de/docs/configuration-callouts.md#kastenstile), [`captionStyle`](https://postext.dev/de/docs/configuration-resources.md#legendenstil), [`colorPalette`](https://postext.dev/de/docs/configuration-fonts-colors-viewers.md#farbpalette), [`footer`](https://postext.dev/de/docs/configuration-headers-footers.md#kopf--und-fußzeilen), [`header`](https://postext.dev/de/docs/configuration-headers-footers.md#kopf--und-fußzeilen), [`headingStyles`](https://postext.dev/de/docs/configuration-styles.md#überschriftenstile), [`headings`](https://postext.dev/de/docs/configuration-headings.md#überschriften), [`layout`](https://postext.dev/de/docs/configuration-page-layout.md#layout), [`locale`](https://postext.dev/de/docs/configuration-language.md#silbentrennung), [`math`](https://postext.dev/de/docs/configuration-lists-math.md#mathematik), [`orderedLists`](https://postext.dev/de/docs/configuration-lists-math.md#nummerierte-listen), [`page`](https://postext.dev/de/docs/configuration-page-layout.md#seite), [`paragraphStyles`](https://postext.dev/de/docs/configuration-styles.md#absatzformate), [`resourceTypes`](https://postext.dev/de/docs/configuration-resources.md#ressourcentypen), [`tableStyle`](https://postext.dev/de/docs/configuration-resources.md#tabellenstil)

**APIs**

- [`buildDocumentWithFonts`](https://postext.dev/de/docs/configuration-programmatic-usage.md#schriften-vor-dem-layout-laden), [`decompressWoff2`](https://postext.dev/de/docs/configuration-pdf-output.md#font-provider-im-browser-fontsource--woff2), [`defaultResourceTypes`](https://postext.dev/de/docs/configuration-resources.md#ressourcentypen), [`initMathEngine`](https://postext.dev/de/docs/document-format-inline.md#mathematische-formeln), [`registerResourceImage`](https://postext.dev/de/docs/architecture.md#api-oberfläche), `renderMath`, [`renderPageToCanvas`](https://postext.dev/de/docs/configuration-programmatic-usage.md#eine-seite-als-bitmap-rendern), [`renderToPdf`](https://postext.dev/de/docs/configuration-pdf-output.md#pdfs-erzeugen)

**Schriften**

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

## Zubereitung

### 1 · Ein locale für Text, Bezeichnungen und Versalien

Der Code steht in [der kurzen Antwort](https://postext.dev/de/cookbook/greek-maths-textbook.md#die-kurze-antwort) oben. `locale: 'el'` trennt den Text mit den monotonischen Mustern, nennt die Ressourcentypen Εικόνα und Πίνακας und lässt `textTransform: 'uppercase'` den Tonos entfernen ([Dokumentsprache](https://postext.dev/de/docs/configuration-language.md)). Die Mathematik ist TeX zwischen `$`, gesetzt von MathJax nach `await initMathEngine()` ([Mathematik](https://postext.dev/de/docs/configuration-lists-math.md)); `\alpha`, `\beta` und `\gamma` geben die griechischen Buchstaben der Formeln. `math.fontSizeScale` vergrößert sie, damit ihre x-Höhe die der Source Serif trifft.

### 2 · Kapitel 3, Abschnitte 3.1 in Versalien

```js
// script.js, Zeilen 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="Κεφάλαιο"}` gibt dem Kapitel die Nummer 3, also zählen seine Abschnitte 3.1, 3.2 und seine Abbildung und Tabelle 3.1. Die H2 werden klein geschrieben, «Τι λέει το θεώρημα», und gedruckt als ΤΙ ΛΕΕΙ ΤΟ ΘΕΩΡΗΜΑ. `## Ασκήσεις {style="exercises"}` nimmt einen Überschriftenstil mit `numbered: false`, und die Aufgaben tragen dieselbe Überschrift ohne Nummer.

### 3 · Εικόνα und Πίνακας aus dem locale

```js
// script.js, Zeilen 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')` übergibt die eingebauten griechischen Typen, nach Kapitel gezählt ([Ressourcen](https://postext.dev/de/docs/configuration-resources.md)). Nur die Legende der Tabelle wandert, über die Tabelle. Im Text druckt `Η :ref{id="tetragona" style="full"}` «Η Εικόνα 3.1» und `Ο :ref{id="triades" style="full"}` «Ο Πίνακας 3.1»: Schreiben Sie den Artikel ins Markdown, denn εικόνα ist weiblich und πίνακας männlich.

### 4 · Eine Abbildung mit MathJax-Beschriftung

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

Ein als Bild gezeichnetes SVG kann die Schriften der Seite nicht nutzen; seine Beschriftungen sind daher MathJax-Pfade aus `renderMath`: `\mathrm{A}`, `\mathrm{B}` und `\Gamma` sind die Großbuchstaben Α, Β, Γ, da Alpha und Beta die Form von A und B teilen. Die Abbildung bekommt `placement: { position: 'top' }` und die halbe Satzbreite, so steht sie oben auf Seite 2, und der Text von Seite 1 läuft unter dem Lehrsatz weiter.

## Das ganze Rezept

Eine Datei, aus dem Ordner des Rezepts zusammengesetzt, mit dem Beispieltext und dem gemeinsamen Baukasten der Rezepte bereits eingebettet; sie baut ihre eigene Seite auf. Zum Ausführen setzen Sie sie in ein `<script type="module">` auf einer leeren Seite oder fügen sie in das JS-Feld eines neuen CodePen-Pens ein (als Modul). Sie importiert postext von esm.sh, es gibt also nichts zu installieren oder zu bauen.

- Quellordner: 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 ───────────────────────────────────────────────────────────────────────
```

## Häufige Fehler

- **Mathematik braucht await initMathEngine() vor dem ersten Build.** Formeln, die gesetzt werden, bevor die Mathematik-Engine läuft, sind graue Platzhalterkästen. Importieren Sie initMathEngine mit den anderen Symbolen aus https://esm.sh/postext und warten Sie es vor dem ersten Build ab; ein Dokument mit Mathematik, das ohne es gebaut wird, gibt eine Konsolenwarnung aus. Seit postext 1.5 wird MathJax im Paket als ein Modul mitgeliefert, das initMathEngine nachlädt, sodass der einfache Import von einem CDN funktioniert und ?bundle nicht gebraucht wird (bis 1.4 musste jedes Symbol von https://esm.sh/postext?bundle kommen). Importieren Sie nur von einer URL: zwei URLs laden zwei Engines.

- Halten Sie die Einheit mit einem geschützten Leerzeichen (U+00A0) im Markdown auf der Zeile ihrer Zahl: Ein auf zwei Zeilen verteiltes «10 cm» liest sich in einem Schulbuch schlecht.
- Eine Formel ist ein unteilbares Wort. Ein Satz, der auf `$30^2 + 40^2 = 900 + 1600 = 2500 = 50^2$` endet, dehnt die Zeilen davor; hier steht die Summe abgesetzt zwischen `$$`.
- Schreiben Sie Dreiecksnamen wie ΑΒΓ als griechische Großbuchstaben im Text, nicht zwischen `$`: MathJax würde sie in seine eigene Kursive setzen.

## Nachweise

- Rezept: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Schrift: Source Serif 4 (OFL-1.1), Fira Sans (OFL-1.1)
- Code: MIT · Beispielinhalt: CC-BY-4.0

## Verwandte Rezepte

- [Nº 028 · Laborbericht: Formeln, Indizes und eine Titrationskurve](https://postext.dev/de/cookbook/lab-report-formulas.md): Ein vierseitiger Chemiebericht auf A4, der Formeln und Einheiten im Text mit ~ und ^ auszeichnet und TeX für die Reaktion und die Gleichungen behält. · Stufe 3 (Fortgeschritten) · Berichte
- [Nº 002 · Zweispaltiger Aufsatz mit nummerierten Gleichungen](https://postext.dev/de/cookbook/journal-article-with-maths.md): Ein zweispaltiger Physikaufsatz, dessen Formeln im Text und sieben nummerierte Gleichungen MathJax setzt und die im PDF als Vektoren bleiben. · Stufe 3 (Fortgeschritten) · Fachartikel und Wissenschaft
- [Nº 201 · Ein griechischer Roman mit monotonischer Silbentrennung](https://postext.dev/de/cookbook/monotonic-greek-novel.md): Das erste Kapitel von Theotokis’ «Η τιμή και το χρήμα» als Buch in 13,5 × 20,5 cm: monotonische Trennmuster, Guillemets «» und Versalien ohne Akzent. · Stufe 2 (Mittel) · Belletristik, Drama und Prosa
