# ギリシャ語の数学教科書の1章

> ギリシャの生徒向けに三平方の定理を扱う3ページ。3.1〜3.3節はtonosのない大文字、図表はΕικόναとΠίνακας、数式はMathJax。

- HTML版: https://postext.dev/ja/cookbook/greek-maths-textbook
- レシピ No. 203 · 教科書 · 難易度 3 (上級) · 出力: Canvas, PDF
- ジャンル: 教科書
- 必要なもの postext ≥ 1.99.1, postext-pdf ≥ 1.99.1 · テスト環境 1.99.1, postext-pdf 1.99.1 ／テスト日 2026-11-29
- ページ: [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
- Sandboxで開く: https://postext.dev/ja/sandbox#recipe=greek-maths-textbook&lang=en (.postext: https://postext.dev/cookbook/greek-maths-textbook/en/greek-maths-textbook.postext)
- 最終更新: 2026-11-29
- 他の言語: [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), [pt](https://postext.dev/pt/cookbook/greek-maths-textbook.md), [zh](https://postext.dev/zh/cookbook/greek-maths-textbook.md), [ar](https://postext.dev/ar/cookbook/greek-maths-textbook.md)

## かんたんな説明

直角三角形を扱うギリシャの中学校数学教科書の3ページ。節見出しは大文字、図と表にはギリシャ語のラベル、数式にはギリシャ文字を使います。

## できあがり

架空のギリシャの中学2年数学教科書から、三平方の定理を扱う第3章の冒頭です。濃い青緑の帯にΚΕΦΑΛΑΙΟ 3と章題が入り、3.1〜3.3節の見出しが字間を空けた大文字で続きます。定理は青緑の地に置き、2つの例題は黄土色の縦帯から下げ、罫で囲んだ枠が定理の由来を語ります。図3.1は3-4-5の三角形の各辺に立つ正方形を描き、表3.1はピタゴラス数5組を確かめます。本文はSource Serif 4 10.5/15 pt、見出しとラベルはFira Sans、数式はMathJaxです。ページはどの版でもギリシャ語で、このレシピのために書きました。言語が変わるのは奥付だけです。

**このレシピが答える問い:**

- ギリシャ語の数学教科書を、ギリシャ語の図ラベル・番号付きの節・数式付きで組むには？
- 数式（インライン、ディスプレイ、方程式）を組み、PDFでもベクターのまま保つには？
- 番号付きキャプションのある図を加え、本文で参照するには（「図3.2を参照」）？
- 見出し行、結合セル、列幅、セルごとのそろえを備えた表を作るには？

## 手短な答え

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

## 材料

**学べること**

- [数式](https://postext.dev/ja/docs/document-format-inline.md#数式): MathJaxで組むインライン数式とディスプレイ数式のLaTeXです。グリッドに乗り、すべての出力でベクターになります。化学式はmhchemで組めます。
- [「図」と「表」を文書の言語で](https://postext.dev/ja/docs/configuration-resources.md#リソースの種類): defaultResourceTypes(locale)は、組み込みの図と表の種類を、そのラベルと参照も含めて文書の言語で返します。
- [番号付き見出し](https://postext.dev/ja/docs/configuration-headings.md#レベルごとの上書き): 階層ごとの番号のテンプレート（1、1.1、IV、A、01）です。章扉、柱、目次にも同じ番号が印刷されます。

**ほかに使うもの**

- [ハイフネーションと文書の言語](https://postext.dev/ja/docs/justification.md#対応するロケール)
- [デザインした章扉](https://postext.dev/ja/docs/configuration-headings.md#幅と詳細デザイン)
- [見出しの属性](https://postext.dev/ja/docs/document-format.md#見出しの属性)
- [番号のない章](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [デザイン要素の基準位置](https://postext.dev/ja/docs/configuration-headers-footers.md#要素の配置)
- [図を配置する参照](https://postext.dev/ja/docs/document-format-resources.md#インライン参照基本の形)
- [番号付きキャプション](https://postext.dev/ja/docs/document-format-resources.md#初出順の番号付け)
- [キャプションのスタイル](https://postext.dev/ja/docs/configuration-resources.md#キャプションスタイル)
- [データから作る表](https://postext.dev/ja/docs/document-format-resources.md#ブロック埋め込み任意本文中への明示的な配置)
- [表スタイル](https://postext.dev/ja/docs/configuration-resources.md#表スタイル)
- [囲み](https://postext.dev/ja/docs/configuration-callouts.md#囲みスタイル)
- [ページデザインのテキスト・罫・ボックス](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル)
- [柱とノンブル](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル)
- [見開きの余白](https://postext.dev/ja/docs/configuration-page-layout.md#見開きの余白)
- [PDFの書き出し](https://postext.dev/ja/docs/configuration-pdf-output.md#pdfの生成)
- [見出しスタイル](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [その場に置く図](https://postext.dev/ja/docs/document-format-resources.md#ブロック埋め込み任意本文中への明示的な配置)
- [ページの役割ごとの柱](https://postext.dev/ja/docs/configuration-headers-footers.md#テキスト要素)
- [段落スタイル](https://postext.dev/ja/docs/configuration-styles.md#段落スタイル)
- [PDFに埋め込むフォント](https://postext.dev/ja/docs/configuration-pdf-output.md#なぜフォントプロバイダーが必要か)
- [独自のリソースの種類](https://postext.dev/ja/docs/configuration-resources.md#リソースの種類)
- [リソースとしての図と表](https://postext.dev/ja/docs/document-format-resources.md#リソース)
- [上付きと下付き](https://postext.dev/ja/docs/document-format-inline.md#インライン書式)

**設定の一覧**

- [`bodyText`](https://postext.dev/ja/docs/configuration-text.md#本文), [`calloutStyles`](https://postext.dev/ja/docs/configuration-callouts.md#囲みスタイル), [`captionStyle`](https://postext.dev/ja/docs/configuration-resources.md#キャプションスタイル), [`colorPalette`](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット), [`footer`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`header`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`headingStyles`](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル), [`headings`](https://postext.dev/ja/docs/configuration-headings.md#見出し), [`layout`](https://postext.dev/ja/docs/configuration-page-layout.md#レイアウト), [`locale`](https://postext.dev/ja/docs/configuration-language.md#ハイフネーション), [`math`](https://postext.dev/ja/docs/configuration-lists-math.md#数式), [`orderedLists`](https://postext.dev/ja/docs/configuration-lists-math.md#番号付きリスト), [`page`](https://postext.dev/ja/docs/configuration-page-layout.md#ページ), [`paragraphStyles`](https://postext.dev/ja/docs/configuration-styles.md#段落スタイル), [`resourceTypes`](https://postext.dev/ja/docs/configuration-resources.md#リソースの種類), [`tableStyle`](https://postext.dev/ja/docs/configuration-resources.md#表スタイル)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#レイアウトの前にフォントを読み込む), [`decompressWoff2`](https://postext.dev/ja/docs/configuration-pdf-output.md#ブラウザー向けフォントプロバイダーfontsource--woff2), [`defaultResourceTypes`](https://postext.dev/ja/docs/configuration-resources.md#リソースの種類), [`initMathEngine`](https://postext.dev/ja/docs/document-format-inline.md#数式), [`registerResourceImage`](https://postext.dev/ja/docs/architecture.md#apiの概要), `renderMath`, [`renderPageToCanvas`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#ページをビットマップに描画する), [`renderToPdf`](https://postext.dev/ja/docs/configuration-pdf-output.md#pdfの生成)

**書体**

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

## 作り方

### 1 · 本文・ラベル・大文字を1つのlocaleで

コードは上の[手短な答え](https://postext.dev/ja/cookbook/greek-maths-textbook.md#手短な答え)です。`locale: 'el'`は本文を単調ギリシャ語のパターンで分綴し、リソースの種類をΕικόναとΠίνακαςと呼び、`textTransform: 'uppercase'`にtonosを外させます（[文書の言語](https://postext.dev/ja/docs/configuration-language.md)）。数式は`$`で囲んだTeXで、`await initMathEngine()`の後にMathJaxが組みます（[数式](https://postext.dev/ja/docs/configuration-lists-math.md)）。`\alpha`、`\beta`、`\gamma`が数式のギリシャ文字です。`math.fontSizeScale`で数式を拡大し、xハイトをSource Serifに合わせます。

### 2 · 第3章と大文字の3.1節

```js
// script.js, 行 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="Κεφάλαιο"}`で章番号が3になり、節は3.1、3.2、図と表は3.1と数えます。H2は小文字で«Τι λέει το θεώρημα»と書き、ΤΙ ΛΕΕΙ ΤΟ ΘΕΩΡΗΜΑと印刷されます。`## Ασκήσεις {style="exercises"}`は`numbered: false`の見出しスタイルを使い、練習問題は同じ見出しで番号なしになります。

### 3 · localeから来るΕικόναとΠίνακας

```js
// script.js, 行 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')`が章ごとに番号を振る組み込みのギリシャ語の種類を渡します（[リソース](https://postext.dev/ja/docs/configuration-resources.md)）。変えるのは表のキャプションの位置だけで、表の上に置きます。本文の`Η :ref{id="tetragona" style="full"}`は«Η Εικόνα 3.1»、`Ο :ref{id="triades" style="full"}`は«Ο Πίνακας 3.1»と印刷されます。εικόναは女性名詞、πίνακαςは男性名詞なので、冠詞はMarkdownに書きます。

### 4 · MathJaxでラベルを付けた図

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

画像として描くSVGはページの書体を使えないので、ラベルは`renderMath`が返すMathJaxのパスです。`\mathrm{A}`、`\mathrm{B}`、`\Gamma`が大文字のΑ、Β、Γになります。アルファとベータはAとBと同じ形だからです。図は`placement: { position: 'top' }`で行長の半分の幅にし、2ページ目の頭に置くので、1ページ目の本文は定理の下に続きます。

## レシピの全体

レシピのフォルダーから合成した1つのファイルで、サンプルのテキストとレシピ集の共通キットを埋め込んであり、自分でページを組み立てます。動かすには、空のページの`<script type="module">`に入れるか、新しいCodePenのpenのJSパネルに貼り付けます（モジュールとして）。esm.shからpostextを読み込むので、インストールもビルドも要りません。

- レシピのフォルダー: 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 ───────────────────────────────────────────────────────────────────────
```

## よくあるつまずき

- **数式には最初のビルドの前にawait initMathEngine()が必要.** 数式エンジンが動き出す前にレイアウトした数式は、灰色のプレースホルダーの箱になります。initMathEngineをほかのシンボルと一緒にhttps://esm.sh/postextから読み込み、最初のビルドの前にawaitしてください。数式のある文書をこれなしでビルドすると、コンソールに警告が1つ出ます。postext 1.5からは、MathJaxはinitMathEngineが取得する1つのモジュールとしてパッケージに含まれているので、通常のimportがCDNから使え、?bundleは必要ありません（1.4までは、すべてのシンボルをhttps://esm.sh/postext?bundleから読み込む必要がありました）。読み込むURLは1つだけにしてください。URLが2つあると、エンジンが2つ読み込まれます。

- Markdownでは単位を数字と同じ行に保つためノーブレークスペース（U+00A0）を使います。«10 cm»が2行に分かれると、教科書では読みにくくなります。
- 数式は分けられない1語です。`$30^2 + 40^2 = 900 + 1600 = 2500 = 50^2$`で終わる文は前の行を間延びさせるので、ここではこの和を`$$`の別行立てにしています。
- 三角形の名前ΑΒΓは本文にギリシャ文字の大文字で書き、`$`で囲まないでください。MathJaxの斜体になってしまいます。

## クレジット

- レシピ: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- 書体: Source Serif 4 (OFL-1.1), Fira Sans (OFL-1.1)
- コード: MIT · サンプルの内容: CC-BY-4.0

## 関連レシピ

- [No. 028 · 実験レポート：化学式、上付き下付き、滴定曲線](https://postext.dev/ja/cookbook/lab-report-formulas.md): A4判4ページの化学の実験レポート。本文中の化学式と単位は~と^で示し、反応式と方程式にはTeXを使います。 · 難易度 3 (上級) · 報告書
- [No. 002 · 番号付きの数式を含む2段組みの論文](https://postext.dev/ja/cookbook/journal-article-with-maths.md): 2段組みの物理学論文。本文中の数式と7つの番号付き数式をMathJaxで組み、PDFでもベクターのまま保ちます。 · 難易度 3 (上級) · 論文・学術書
- [No. 201 · 単調正書法でハイフネーションしたギリシャ語の小説](https://postext.dev/ja/cookbook/monotonic-greek-novel.md): テオトキス『Η τιμή και το χρήμα』の第1章を13.5 × 20.5 cmの本に。単調ギリシャ語の分綴、«»の引用符、アクセントを落とした大文字の柱。 · 難易度 2 (中級) · 小説・戯曲・文芸
