# فصل من كتاب رياضيات مدرسي يوناني

> ثلاث صفحات عن مبرهنة فيثاغورس لتلاميذ يونانيين: الأقسام 3.1 إلى 3.3 بحروف كبيرة بلا tonos، وتسميات Εικόνα وΠίνακας، وصيغ MathJax.

- نسخة HTML: https://postext.dev/ar/cookbook/greek-maths-textbook
- وصفة رقم 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/ar/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), [ja](https://postext.dev/ja/cookbook/greek-maths-textbook.md)

## باختصار

ثلاث صفحات من كتاب رياضيات مدرسي يوناني عن المثلث القائم. عناوين الأقسام بحروف كبيرة، والرسم والجدول يحملان تسميات يونانية، والصيغ تستعمل الحروف اليونانية.

## ما الذي ستنضده

مطلع الفصل 3 من كتاب رياضيات متخيَّل للسنة الثانية من المرحلة الإعدادية اليونانية، عن مبرهنة فيثاغورس. يحمل شريط أزرق مخضر ΚΕΦΑΛΑΙΟ 3 وعنوان الفصل؛ وتتبعه الأقسام 3.1 إلى 3.3 بحروف كبيرة متباعدة. تجلس المبرهنة على خلفية زرقاء مخضرة، ويتدلى مثالان محلولان من شريط بلون المغرة، ويحكي إطار مخطط من أين جاءت المبرهنة. يرسم الشكل 3.1 المربعات على أضلاع مثلث 3-4-5؛ ويتحقق الجدول 3.1 من خمس ثلاثيات فيثاغورية. النص بخط Source Serif 4 قياس 10,5 على 15 نقطة، والعناوين والتسميات بخط 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/ar/docs/document-format-inline.md#الصيغ-الرياضية): صيغ LaTeX داخل السطر ومعروضة يصفّها MathJax، على الشبكة ومتجهية في كل مُخرَج، والكيمياء عبر mhchem.
- [«شكل» و«جدول» بلغتك](https://postext.dev/ar/docs/configuration-resources.md#أنواع-الموارد): تُرجع defaultResourceTypes(locale) نوعَي الشكل والجدول المدمجين، بتسمياتهما وإحالاتهما، بلغة المستند.
- [العناوين المرقّمة](https://postext.dev/ar/docs/configuration-headings.md#تجاوزات-كل-مستوى): قوالب ترقيم لكل مستوى (1، 1.1، IV، A، 01) تطبعها أيضًا صفحات الافتتاح والترويسات وجدول المحتويات.

**تستخدم أيضًا**

- [تقسيم الكلمات ولغة المستند](https://postext.dev/ar/docs/justification.md#اللغات-المدعومة)
- [صفحات افتتاح مصمَّمة](https://postext.dev/ar/docs/configuration-headings.md#الامتداد-والتصميم-المتقدم)
- [سمات العنوان](https://postext.dev/ar/docs/document-format.md#سمات-العناوين)
- [فصول بلا أرقام](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين)
- [تثبيت عناصر التصميم](https://postext.dev/ar/docs/configuration-headers-footers.md#تموضع-العناصر)
- [استشهادات تضع الأشكال](https://postext.dev/ar/docs/document-format-resources.md#الإحالة-داخل-السطر-الصيغة-الأساسية)
- [تعليقات مرقّمة](https://postext.dev/ar/docs/document-format-resources.md#الترقيم-بحسب-الإحالة-الأولى)
- [نمط التعليق](https://postext.dev/ar/docs/configuration-resources.md#نمط-التعليقات)
- [جداول من البيانات](https://postext.dev/ar/docs/document-format-resources.md#التضمين-في-كتلة-اختياري-لوضع-صريح-داخل-التدفق)
- [نمط الجدول](https://postext.dev/ar/docs/configuration-resources.md#نمط-الجداول)
- [إطارات التنبيه](https://postext.dev/ar/docs/configuration-callouts.md#أنماط-الإطارات)
- [النصوص والخطوط والمربعات في تصاميم الصفحة](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات)
- [الترويسات وأرقام الصفحات](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات)
- [هوامش متناظرة](https://postext.dev/ar/docs/configuration-page-layout.md#الهوامش-المتناظرة)
- [التصدير إلى PDF](https://postext.dev/ar/docs/configuration-pdf-output.md#توليد-ملفات-pdf)
- [أنماط العناوين](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين)
- [أشكال في هذا الموضع بالضبط](https://postext.dev/ar/docs/document-format-resources.md#التضمين-في-كتلة-اختياري-لوضع-صريح-داخل-التدفق)
- [الترويسات بحسب دور الصفحة](https://postext.dev/ar/docs/configuration-headers-footers.md#عناصر-النص)
- [أنماط الفقرات](https://postext.dev/ar/docs/configuration-styles.md#أنماط-الفقرات)
- [الخطوط المضمَّنة في PDF](https://postext.dev/ar/docs/configuration-pdf-output.md#لماذا-مزوّد-الخطوط)
- [أنواع موارد مخصّصة](https://postext.dev/ar/docs/configuration-resources.md#أنواع-الموارد)
- [الأشكال والجداول بوصفها موارد](https://postext.dev/ar/docs/document-format-resources.md#الموارد)
- [النص المرتفع والمنخفض](https://postext.dev/ar/docs/document-format-inline.md#التنسيق-داخل-السطر)

**الإعدادات في لمحة**

- [`bodyText`](https://postext.dev/ar/docs/configuration-text.md#نص-المتن), [`calloutStyles`](https://postext.dev/ar/docs/configuration-callouts.md#أنماط-الإطارات), [`captionStyle`](https://postext.dev/ar/docs/configuration-resources.md#نمط-التعليقات), [`colorPalette`](https://postext.dev/ar/docs/configuration-fonts-colors-viewers.md#لوحة-الألوان), [`footer`](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات), [`header`](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات), [`headingStyles`](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين), [`headings`](https://postext.dev/ar/docs/configuration-headings.md#العناوين), [`layout`](https://postext.dev/ar/docs/configuration-page-layout.md#التخطيط), [`locale`](https://postext.dev/ar/docs/configuration-language.md#تقسيم-الكلمات-بالواصلة), [`math`](https://postext.dev/ar/docs/configuration-lists-math.md#الصيغ-الرياضية), [`orderedLists`](https://postext.dev/ar/docs/configuration-lists-math.md#القوائم-المرقّمة), [`page`](https://postext.dev/ar/docs/configuration-page-layout.md#الصفحة), [`paragraphStyles`](https://postext.dev/ar/docs/configuration-styles.md#أنماط-الفقرات), [`resourceTypes`](https://postext.dev/ar/docs/configuration-resources.md#أنواع-الموارد), [`tableStyle`](https://postext.dev/ar/docs/configuration-resources.md#نمط-الجداول)

**واجهات API**

- [`buildDocumentWithFonts`](https://postext.dev/ar/docs/configuration-programmatic-usage.md#تحميل-الخطوط-قبل-الإخراج), [`decompressWoff2`](https://postext.dev/ar/docs/configuration-pdf-output.md#مزوّد-الخطوط-في-المتصفح-fontsource--woff2), [`defaultResourceTypes`](https://postext.dev/ar/docs/configuration-resources.md#أنواع-الموارد), [`initMathEngine`](https://postext.dev/ar/docs/document-format-inline.md#الصيغ-الرياضية), [`registerResourceImage`](https://postext.dev/ar/docs/architecture.md#واجهة-البرمجة-المتاحة-api), `renderMath`, [`renderPageToCanvas`](https://postext.dev/ar/docs/configuration-programmatic-usage.md#رسم-صفحة-في-صورة-نقطية), [`renderToPdf`](https://postext.dev/ar/docs/configuration-pdf-output.md#توليد-ملفات-pdf)

**الخطوط**

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

## طريقة التحضير

### 1 · محلية واحدة للنص والتسميات والحروف الكبيرة

الشيفرة هي [الجواب المختصر](https://postext.dev/ar/cookbook/greek-maths-textbook.md#الجواب-المختصر) أعلاه. يقطّع `locale: 'el'` النص بالأنماط أحادية النبر، ويسمي أنواع الموارد Εικόνα وΠίνακας، ويجعل `textTransform: 'uppercase'` يحذف tonos ([لغة الوثيقة](https://postext.dev/ar/docs/configuration-language.md)). الرياضيات TeX بين علامتي `$`، ينضدها MathJax بعد `await initMathEngine()` ([الرياضيات](https://postext.dev/ar/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 · Εικόνα وΠίνακας من المحلية

```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/ar/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 مرسوم كصورة أن يستعمل خطوط الصفحة، فتسمياته مسارات MathJax يعيدها `renderMath`: ‏`\mathrm{A}` و`\mathrm{B}` و`\Gamma` هي الحروف الكبيرة Α وΒ وΓ، لأن ألفا وبيتا تشبهان A وB في الشكل. يأخذ الشكل `placement: { position: 'top' }` ونصف عرض السطر، فيتصدر الصفحة 2 ويتابع نص الصفحة 1 تحت المبرهنة.

## الوصفة كاملة

ملف واحد، مركّب من مجلد الوصفة ومعه نص المثال وأدوات دليل الوصفات المشتركة مضمّنة؛ وهو ينشئ صفحته بنفسه. لتشغيله، ضعه داخل `<script type="module">` في صفحة فارغة أو الصقه في لوحة JS في مثال CodePen جديد (وحدةً). يستورد postext من esm.sh، فلا حاجة إلى تثبيت أو بناء.

- مجلد الوصفة: 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 قبل البناء الأول؛ والمستند الذي فيه رياضيات ويُبنى من دونها يطبع تحذيرًا واحدًا في وحدة التحكم. ومنذ postext 1.5 يأتي MathJax داخل حزمة postext وحدةً واحدة تجلبها initMathEngine، فالاستيراد العادي يعمل من CDN ولا حاجة إلى ?bundle (حتى 1.4 كان يجب أن يأتي كل رمز من https://esm.sh/postext?bundle). استورد من عنوان URL واحد فقط: عنوانان يحمّلان محرّكين.

- أبقِ الوحدة على سطر رقمها بمسافة غير فاصلة (U+00A0) في Markdown: «10 cm» مقسومة على سطرين تُقرأ بصعوبة في كتاب مدرسي.
- الصيغة كلمة واحدة لا تنقسم. الجملة التي تنتهي بـ`$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

## وصفات ذات صلة

- [رقم 028 · تقرير مختبر: صيغ وأحرف سفلية وعلوية ومنحنى معايرة](https://postext.dev/ar/cookbook/lab-report-formulas.md): تقرير كيمياء من أربع صفحات على A4 يعلّم الصيغ والوحدات داخل النص بـ ~ و^ ويحتفظ بـ TeX للتفاعل والمعادلات. · المستوى 3 (متقدم) · التقارير
- [رقم 002 · بحث في عمودين مع معادلات مرقّمة](https://postext.dev/ar/cookbook/journal-article-with-maths.md): بحث في الفيزياء من عمودين تنضّد MathJax صيغه داخل السطر ومعادلاته المرقّمة السبع، وتبقى متجهية في ملف PDF. · المستوى 3 (متقدم) · الأوراق البحثية والأكاديمية
- [رقم 201 · رواية يونانية بتقطيع أحادي النبر](https://postext.dev/ar/cookbook/monotonic-greek-novel.md): الفصل الأول من «Η τιμή και το χρήμα» لثيوتوكيس في كتاب 13,5 × 20,5 سم: أنماط اليونانية أحادية النبر، وعلامات «»، وحروف كبيرة بلا نبر. · المستوى 2 (متوسط) · الأدب القصصي والمسرح والنثر الأدبي
