# Um capítulo de livro de matemática grego

> Três páginas sobre o teorema de Pitágoras para alunos gregos: seções 3.1 a 3.3 em versais sem tonos, legendas Εικόνα e Πίνακας e fórmulas do MathJax.

- Versão HTML: https://postext.dev/pt/cookbook/greek-maths-textbook
- Receita Nº 203 · Livros didáticos · Nível 3 (Avançado) · Saídas: Canvas, PDF
- Gêneros: Livros didáticos
- Requer postext ≥ 1.99.1, postext-pdf ≥ 1.99.1 · testada com 1.99.1, postext-pdf 1.99.1 em 2026-11-29
- Páginas: [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
- Abrir no Sandbox: https://postext.dev/pt/sandbox#recipe=greek-maths-textbook&lang=en (.postext: https://postext.dev/cookbook/greek-maths-textbook/en/greek-maths-textbook.postext)
- Última atualização: 2026-11-29
- Outros idiomas: [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), [fr](https://postext.dev/fr/cookbook/greek-maths-textbook.md), [it](https://postext.dev/it/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)

## Em poucas palavras

Três páginas de um livro escolar grego de matemática sobre o triângulo retângulo. Os títulos das seções vão em maiúsculas, o desenho e a tabela têm rótulos em grego e as fórmulas usam letras gregas.

## O que você vai compor

O início do capítulo 3 de um livro imaginário de matemática do segundo ano do ensino médio grego, sobre o teorema de Pitágoras. Uma faixa verde-azulada traz ΚΕΦΑΛΑΙΟ 3 e o título; seguem as seções 3.1 a 3.3 em versais espaçadas. O teorema fica sobre um fundo verde-azulado, dois exemplos resolvidos pendem de uma tarja ocre e um quadro com fio conta de onde vem o teorema. A Figura 3.1 desenha os quadrados sobre os lados de um triângulo 3-4-5; a Tabela 3.1 confere cinco ternos pitagóricos. O texto é Source Serif 4 10,5 sobre 15 pt, títulos e rótulos Fira Sans, as fórmulas MathJax. A página é grega em todas as edições e foi escrita para esta receita; só o colofão muda de língua.

**Esta receita responde a:**

- Como componho um livro de matemática em grego, com rótulos de figura em grego, seções numeradas e fórmulas?
- Como componho matemática (em linha, em destaque, equações) e a mantenho vetorial no PDF?
- Como acrescento uma figura com legenda numerada e a cito no texto (“ver fig. 3.2”)?
- Como faço uma tabela com linhas de cabeçalho, células mescladas, larguras de coluna e alinhamento por célula?

## A resposta curta

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

## Ingredientes

**Ensina**

- [Matemática](https://postext.dev/pt/docs/document-format-inline.md#fórmulas-matemáticas): LaTeX no texto e em destaque composto pelo MathJax, sobre a grade e vetorial em todas as saídas, com química pelo mhchem.
- [Figura e Tabela no seu idioma](https://postext.dev/pt/docs/configuration-resources.md#tipos-de-recurso): defaultResourceTypes(locale) fornece os tipos nativos Figura e Tabela, com rótulos e referências no idioma do documento.
- [Títulos numerados](https://postext.dev/pt/docs/configuration-headings.md#valores-por-nível): Modelos de numeração por nível (1, 1.1, IV, A, 01), que as aberturas, os cabeços e o sumário também imprimem.

**Também usa**

- [Hifenização e idioma do documento](https://postext.dev/pt/docs/justification.md#idiomas-compatíveis)
- [Aberturas desenhadas](https://postext.dev/pt/docs/configuration-headings.md#largura-e-design-avançado)
- [Atributos de título](https://postext.dev/pt/docs/document-format.md#atributos-de-título)
- [Capítulos sem número](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título)
- [Ancoragem de elementos de design](https://postext.dev/pt/docs/configuration-headers-footers.md#posicionamento-de-elementos)
- [Citações que posicionam as figuras](https://postext.dev/pt/docs/document-format-resources.md#referência-em-linha-a-forma-principal)
- [Legendas numeradas](https://postext.dev/pt/docs/document-format-resources.md#numeração-pela-primeira-referência)
- [Estilo de legenda](https://postext.dev/pt/docs/configuration-resources.md#estilo-de-legenda)
- [Tabelas a partir de dados](https://postext.dev/pt/docs/document-format-resources.md#inserção-em-bloco-opcional-posição-explícita-no-fluxo)
- [Estilo de tabela](https://postext.dev/pt/docs/configuration-resources.md#estilo-de-tabela)
- [Boxes](https://postext.dev/pt/docs/configuration-callouts.md#estilos-de-boxe)
- [Textos, fios e caixas nos designs de página](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés)
- [Cabeços e fólios](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés)
- [Margens espelhadas](https://postext.dev/pt/docs/configuration-page-layout.md#margens-espelhadas)
- [Exportação para PDF](https://postext.dev/pt/docs/configuration-pdf-output.md#geração-de-pdf)
- [Estilos de título](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título)
- [Figuras exatamente aqui](https://postext.dev/pt/docs/document-format-resources.md#inserção-em-bloco-opcional-posição-explícita-no-fluxo)
- [Cabeços por tipo de página](https://postext.dev/pt/docs/configuration-headers-footers.md#elementos-de-texto)
- [Estilos de parágrafo](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-parágrafo)
- [Fontes incorporadas ao PDF](https://postext.dev/pt/docs/configuration-pdf-output.md#por-que-um-provedor-de-fontes)
- [Tipos de recurso personalizados](https://postext.dev/pt/docs/configuration-resources.md#tipos-de-recurso)
- [Figuras e tabelas como recursos](https://postext.dev/pt/docs/document-format-resources.md#recursos)
- [Sobrescritos e subscritos](https://postext.dev/pt/docs/document-format-inline.md#formatação-em-linha)

**A configuração em resumo**

- [`bodyText`](https://postext.dev/pt/docs/configuration-text.md#texto-do-corpo), [`calloutStyles`](https://postext.dev/pt/docs/configuration-callouts.md#estilos-de-boxe), [`captionStyle`](https://postext.dev/pt/docs/configuration-resources.md#estilo-de-legenda), [`colorPalette`](https://postext.dev/pt/docs/configuration-fonts-colors-viewers.md#paleta-de-cores), [`footer`](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés), [`header`](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés), [`headingStyles`](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título), [`headings`](https://postext.dev/pt/docs/configuration-headings.md#títulos), [`layout`](https://postext.dev/pt/docs/configuration-page-layout.md#diagramação), [`locale`](https://postext.dev/pt/docs/configuration-language.md#hifenização), [`math`](https://postext.dev/pt/docs/configuration-lists-math.md#matemática), [`orderedLists`](https://postext.dev/pt/docs/configuration-lists-math.md#listas-numeradas), [`page`](https://postext.dev/pt/docs/configuration-page-layout.md#página), [`paragraphStyles`](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-parágrafo), [`resourceTypes`](https://postext.dev/pt/docs/configuration-resources.md#tipos-de-recurso), [`tableStyle`](https://postext.dev/pt/docs/configuration-resources.md#estilo-de-tabela)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/pt/docs/configuration-programmatic-usage.md#carregar-as-fontes-antes-da-diagramação), [`decompressWoff2`](https://postext.dev/pt/docs/configuration-pdf-output.md#provedor-de-fontes-no-navegador-fontsource--woff2), [`defaultResourceTypes`](https://postext.dev/pt/docs/configuration-resources.md#tipos-de-recurso), [`initMathEngine`](https://postext.dev/pt/docs/document-format-inline.md#fórmulas-matemáticas), [`registerResourceImage`](https://postext.dev/pt/docs/architecture.md#superfície-da-api), `renderMath`, [`renderPageToCanvas`](https://postext.dev/pt/docs/configuration-programmatic-usage.md#renderizar-uma-página-como-bitmap), [`renderToPdf`](https://postext.dev/pt/docs/configuration-pdf-output.md#geração-de-pdf)

**Tipos**

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

## Preparo

### 1 · Um locale para o texto, os rótulos e as versais

O código é [a resposta curta](https://postext.dev/pt/cookbook/greek-maths-textbook.md#a-resposta-curta) acima. `locale: 'el'` hifeniza o texto com os padrões monotônicos, chama os tipos de recurso Εικόνα e Πίνακας e faz `textTransform: 'uppercase'` tirar o tonos ([idioma do documento](https://postext.dev/pt/docs/configuration-language.md)). A matemática é TeX entre `$`, composto pelo MathJax depois de `await initMathEngine()` ([matemática](https://postext.dev/pt/docs/configuration-lists-math.md)); `\alpha`, `\beta` e `\gamma` dão as letras gregas das fórmulas. `math.fontSizeScale` as aumenta para que a altura de x encontre a da Source Serif.

### 2 · Capítulo 3, seções 3.1 em versais

```js
// script.js, linhas 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="Κεφάλαιο"}` dá ao capítulo o número 3, e as seções contam 3.1, 3.2 e a figura e a tabela 3.1. Os H2 são escritos em minúsculas, «Τι λέει το θεώρημα», e saem ΤΙ ΛΕΕΙ ΤΟ ΘΕΩΡΗΜΑ. `## Ασκήσεις {style="exercises"}` usa um estilo de título com `numbered: false`, e os exercícios têm o mesmo título sem número.

### 3 · Εικόνα e Πίνακας a partir do locale

```js
// script.js, linhas 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')` entrega os tipos gregos embutidos, numerados por capítulo ([recursos](https://postext.dev/pt/docs/configuration-resources.md)). Só a legenda da tabela muda de lugar, acima dela. No texto, `Η :ref{id="tetragona" style="full"}` imprime «Η Εικόνα 3.1» e `Ο :ref{id="triades" style="full"}` «Ο Πίνακας 3.1»: escreva o artigo no Markdown, porque εικόνα é feminino e πίνακας masculino.

### 4 · Uma figura rotulada pelo MathJax

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

Um SVG desenhado como imagem não pode usar as fontes da página, então os rótulos são traçados do MathJax obtidos com `renderMath`: `\mathrm{A}`, `\mathrm{B}` e `\Gamma` são as maiúsculas Α, Β, Γ, já que alfa e beta têm a forma de A e B. A figura leva `placement: { position: 'top' }` e meia mancha, então abre a página 2 e o texto da página 1 continua sob o teorema.

## A receita completa

Um único arquivo, composto a partir da pasta da receita com o texto de exemplo e o kit comum das Receitas já incluídos; ele monta a própria página. Para executá-lo, coloque-o em um `<script type="module">` de uma página vazia ou cole-o no painel JS de um pen novo do CodePen (como módulo). Ele importa o postext do esm.sh, então não há nada para instalar nem compilar.

- Pasta da receita: 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 ───────────────────────────────────────────────────────────────────────
```

## Erros comuns

- **Matemática precisa de await initMathEngine() antes da primeira composição.** Fórmulas diagramadas antes de o motor de matemática estar rodando saem como caixas cinza no lugar da fórmula. Importe initMathEngine de https://esm.sh/postext com os outros símbolos e aguarde-o com await antes da primeira composição; um documento com matemática composto sem ele imprime um aviso no console. Desde o postext 1.5, o MathJax vem dentro do pacote postext como um único módulo que initMathEngine baixa, então a importação simples funciona a partir de uma CDN e ?bundle não é necessário (até a 1.4, todos os símbolos tinham de vir de https://esm.sh/postext?bundle). Importe de uma única URL: duas URLs carregam dois motores.

- Mantenha a unidade na linha do número com um espaço inseparável (U+00A0) no Markdown: um «10 cm» partido em duas linhas lê-se mal num livro didático.
- Uma fórmula é uma palavra que não se divide. Uma frase que termina em `$30^2 + 40^2 = 900 + 1600 = 2500 = 50^2$` estica as linhas anteriores; aqui essa soma vai em destaque, entre `$$`.
- Escreva os nomes de triângulos, ΑΒΓ, com maiúsculas gregas no texto, não entre `$`: o MathJax os poria no seu próprio itálico.

## Créditos

- Receita: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Tipos: Source Serif 4 (OFL-1.1), Fira Sans (OFL-1.1)
- Código: MIT · Conteúdo de exemplo: CC-BY-4.0

## Relacionadas

- [Nº 028 · Relatório de laboratório: fórmulas, índices e curva de pH](https://postext.dev/pt/cookbook/lab-report-formulas.md): Um relatório de química de quatro páginas A4 que marca com ~ e ^ as fórmulas e unidades do texto e deixa o TeX para a reação e as equações. · Nível 3 (Avançado) · Relatórios
- [Nº 002 · Artigo em duas colunas com equações numeradas](https://postext.dev/pt/cookbook/journal-article-with-maths.md): Um artigo de física em duas colunas com fórmulas no texto e sete equações numeradas, compostas pelo MathJax e vetoriais no PDF. · Nível 3 (Avançado) · Artigos e trabalhos acadêmicos
- [Nº 201 · Um romance grego com hifenização monotônica](https://postext.dev/pt/cookbook/monotonic-greek-novel.md): O primeiro capítulo de «Η τιμή και το χρήμα», de Theotokis, num livro de 13,5 × 20,5 cm: padrões do grego monotônico, aspas «» e versais sem acento. · Nível 2 (Intermediário) · Ficção, teatro e prosa literária
