# Τετράδιο καλλιγραφίας σε δέκα σχολικές γραφές

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

- Έκδοση HTML: https://postext.dev/el/cookbook/handwriting-workbook
- Συνταγή Αρ. 161 · Σχολικά βιβλία · Επίπεδο 2 (Μεσαίο) · Έξοδοι: Canvas, PDF
- Είδη: Τετράδια και ασκήσεις, Σχολικά βιβλία
- Απαιτεί postext ≥ 1.65.0, postext-pdf ≥ 1.65.0 · δοκιμασμένη με 1.65.0, postext-pdf 1.65.0 στις 2026-10-31
- Σελίδες: [1](https://postext.dev/cookbook/handwriting-workbook/en/p01.webp?v=ada3abef), [2](https://postext.dev/cookbook/handwriting-workbook/en/p02.webp?v=ada3abef), [3](https://postext.dev/cookbook/handwriting-workbook/en/p03.webp?v=ada3abef), [4](https://postext.dev/cookbook/handwriting-workbook/en/p04.webp?v=ada3abef), [5](https://postext.dev/cookbook/handwriting-workbook/en/p05.webp?v=ada3abef), [6](https://postext.dev/cookbook/handwriting-workbook/en/p06.webp?v=ada3abef), [7](https://postext.dev/cookbook/handwriting-workbook/en/p07.webp?v=ada3abef), [8](https://postext.dev/cookbook/handwriting-workbook/en/p08.webp?v=ada3abef), [9](https://postext.dev/cookbook/handwriting-workbook/en/p09.webp?v=ada3abef), [10](https://postext.dev/cookbook/handwriting-workbook/en/p10.webp?v=ada3abef), [11](https://postext.dev/cookbook/handwriting-workbook/en/p11.webp?v=ada3abef), [12](https://postext.dev/cookbook/handwriting-workbook/en/p12.webp?v=ada3abef)
- PDF: https://postext.dev/cookbook/handwriting-workbook/en/handwriting-workbook.pdf?v=ada3abef
- Άνοιγμα στο Sandbox: https://postext.dev/el/sandbox#recipe=handwriting-workbook&lang=en (.postext: https://postext.dev/cookbook/handwriting-workbook/en/handwriting-workbook.postext)
- Τελευταία ενημέρωση: 2026-10-31
- Άλλες γλώσσες: [en](https://postext.dev/en/cookbook/handwriting-workbook.md), [es](https://postext.dev/es/cookbook/handwriting-workbook.md), [ca](https://postext.dev/ca/cookbook/handwriting-workbook.md), [de](https://postext.dev/de/cookbook/handwriting-workbook.md), [fr](https://postext.dev/fr/cookbook/handwriting-workbook.md), [it](https://postext.dev/it/cookbook/handwriting-workbook.md), [pt](https://postext.dev/pt/cookbook/handwriting-workbook.md), [zh](https://postext.dev/zh/cookbook/handwriting-workbook.md), [ja](https://postext.dev/ja/cookbook/handwriting-workbook.md), [ar](https://postext.dev/ar/cookbook/handwriting-workbook.md)

## Με λίγα λόγια

Παιδικό βιβλίο γραφής φτιαγμένο δέκα φορές, μία ανά γλώσσα. Κάθε μάθημα δείχνει μια λέξη γραμμένη, έπειτα με στιγμές για να την περάσει το παιδί, έπειτα άδειες γραμμές, με τα ενωμένα γράμματα και το ριγέ χαρτί των σχολείων κάθε χώρας.

## Τι θα στοιχειοθετήσετε

Δώδεκα σελίδες ενός βιβλίου γραφής για την πρώτη τάξη σε A4, σε δέκα εκδόσεις που είναι δέκα διαφορετικά βιβλία. Κάθε γλώσσα παίρνει την ενωμένη γραφή που διδάσκουν τα σχολεία της, από τις οικογένειες Playwrite της Google (GB J, ES, FR Trad, DE VA, IT Trad, BR) ή την Playpen Sans Arabic, πάνω στο χαρτί που γράφουν τα παιδιά της: την ισπανική *pauta*, τα γαλλικά τετράγωνα Seyès με κόκκινο περιθώριο, τη γερμανική *Lineatur* με την κίτρινη μεσαία λωρίδα της, τις βραζιλιάνικες γραμμές *caligrafia*. Η κινεζική έκδοση γράφει σε τετράγωνα 田字格, όπου τα παιδιά ξεσηκώνουν απαλούς κόκκινους χαρακτήρες (描红), με pinyin σε τέσσερις γραμμές· η ιαπωνική σε τετράγωνα マス με έναν σταυρό από στιγμές, με ξεσήκωμα σε γκρι (なぞり書き). Τα μαθήματα ακολουθούν την ορθογραφία κάθε γλώσσας: το ñ και το βουβό h στα ισπανικά, το l·l στα καταλανικά, το ß και τα ουσιαστικά με κεφαλαίο στα γερμανικά, τα μόρια は, を και へ στα ιαπωνικά, τις τέσσερις μορφές ενός γράμματος και τα γράμματα που δεν ενώνονται στα αραβικά. Κάθε σειρά πηγαίνει από ένα υπόδειγμα σε στιγμές και σε τίποτα. Είκοσι εννέα πίνακες, δημιουργημένοι με ένα μοντέλο διάχυσης, είναι κοινοί σε όλες τις εκδόσεις.

**Αυτή η συνταγή απαντά:**

- Πώς φτιάχνω τετράδιο γραφής: υπόδειγμα, γράμματα από στιγμές και άδειες σειρές στις γραμμές κάθε χώρας;
- Πώς φτιάχνω μια σελίδα φύλλου εργασίας: γραμμές για συμπλήρωση, πλαίσια απαντήσεων, τράπεζες λέξεων, λίστες ελέγχου;

## Η σύντομη απάντηση

```js
// script.js, γραμμές 70–93
// :::callout{type="palabra" title="Repasa y escribe"} / niña / ::: draws four rows: the model
// and copies, a row of copies, the model and a copy, an empty row, all of them the box's word
// ({boxText}); a copy has `dotted`, `repeat` fills its row. A design text's baseline falls 0.8
// of its line below its top; a tall line keeps the descenders inside its clip.
const G = CJK ? null : geometry(ED.ruling, ED.u); // rows, baselines and the face's size
const [LABEL_H, GAP] = [7, 3 * ED.u]; // mm: the box's title above its ruling; between copies
const hand = (id, placement, extra) => text(id, '{boxText}', HAND, G.size / 0.3528, placement,
  { lineHeight: mm(G.line), overflow: 'clip', ...extra });
const dots = (many) => ({ color: col('dots'), dotted: { spacing: mm(0.2 * ED.u),
  size: mm(0.11 * ED.u) }, ...(many && { repeat: { gap: mm(GAP) } }) });
const onRow = (n, size) => at('container', 'top-left', 0, G.base[n] - 0.8 * G.line, size);
const model = (n) => hand(`model-${n}`, onRow(n));
// Copies after the model of row n (as many as fit, or one), or from the row's start.
const after = (n, many) => hand(`after-${n}`, { anchor: { to: `#model-${n}`,
  edge: 'right-of' }, offset: { x: mm(GAP) } }, dots(many));
const copies = (n, many) => hand(`copies-${n}`, onRow(n, { width: 'fill' }), dots(many));
const ruled = (rows, picture, texts) => ({ setsContent: true, minHeight: mm(G.height(rows)),
  slot: { elements: [image('ruling', picture, at('container', 'top-left', 0, 0,
    box(W, G.height(rows)))), ...texts] } });
// Every practice box: no frame, its title in the label face LABEL_H above the drawing.
const practice = (id, design, gap = mm(4)) => ({ id, design, backgroundEnabled: false,
  padding: { top: pt(0), right: pt(0), bottom: pt(0), left: pt(0) }, titleStyle: {
    fontFamily: LABEL, fontSize: pt(9), fontWeight: LW, color: col('accent'), lineHeight: mm(5),
    gap: mm(LABEL_H - 5), ...caps(1.2) }, marginTop: gap, marginBottom: mm(5), snapToGrid: false });
```

## Υλικά

**Διδάσκει**

- [Σχεδιασμένες εναρκτήριες σελίδες](https://postext.dev/el/docs/configuration-headings.md#πλάτος-και-προηγμένη-σχεδίαση): Μια επικεφαλίδα σχεδιασμένη ως ελεύθερη σύνθεση από κείμενο, γραμμές, πλαίσια και εικόνες, που δεσμεύει το ύψος που χρειάζεται πάνω από το κυρίως κείμενο.
- [Πλαίσια σημειώσεων](https://postext.dev/el/docs/configuration-callouts.md#στιλ-πλαισίων): Ονομασμένα στιλ πλαισίων για σημειώσεις, συμβουλές και προειδοποιήσεις: φόντο, περίγραμμα, ακτίνα γωνιών, λωρίδα, τίτλος και δική τους τυπογραφία για το σώμα και τις λίστες.
- [Γράμματα με στιγμές για αντιγραφή](https://postext.dev/el/docs/configuration-headers-footers.md#στοιχεία-κειμένου): Ένα κείμενο σχεδίασης ή μια ετικέτα των οποίων τα γράμματα ζωγραφίζονται ως σειρές από στιγμές κατά μήκος των γραμμών τους, και ένα κείμενο σχεδίασης που επαναλαμβάνεται κατά μήκος της γραμμής του: τα αντίγραφα που ακολουθεί με το μολύβι ένα παιδί.

**Χρησιμοποιεί επίσης**

- [Εικόνες στις σχεδιάσεις σελίδας](https://postext.dev/el/docs/configuration-headers-footers.md#στοιχεία-εικόνας)
- [Ιδιότητες επικεφαλίδων](https://postext.dev/el/docs/document-format.md#χαρακτηριστικά-επικεφαλίδων)
- [Στιλ επικεφαλίδων](https://postext.dev/el/docs/configuration-styles.md#στιλ-επικεφαλίδων)
- [Εξώφυλλα, σελίδες τίτλου και κολοφώνες](https://postext.dev/el/docs/configuration-styles.md#στιλ-επικεφαλίδων)
- [Κείμενο, γραμμές και πλαίσια στις σχεδιάσεις σελίδας](https://postext.dev/el/docs/configuration-headers-footers.md#κεφαλίδες-και-υποσέλιδα)
- [Ετικέτες μέσα στη γραμμή](https://postext.dev/el/docs/configuration-styles.md#στιλ-ετικετών)
- [Σημασιολογική χρωματική παλέτα](https://postext.dev/el/docs/configuration-fonts-colors-viewers.md#παλέτα-χρωμάτων)
- [Συλλαβισμός και γλώσσα του εγγράφου](https://postext.dev/el/docs/justification.md#υποστηριζόμενες-γλώσσες)
- [Κεφαλίδες ανά ρόλο σελίδας](https://postext.dev/el/docs/configuration-headers-footers.md#στοιχεία-κειμένου)
- [Συμμετρικά περιθώρια](https://postext.dev/el/docs/configuration-page-layout.md#κατοπτρικά-περιθώρια)
- [Αραβικές γραμματοσειρές](https://postext.dev/el/docs/arabic-layout.md#γραμματοσειρές)
- [Κινεζικές, ιαπωνικές και κορεατικές γραμματοσειρές](https://postext.dev/el/docs/configuration-pdf-output.md#γραμματοσειρές-για-κινεζικά-ιαπωνικά-και-κορεατικά)
- [Βιβλία με δέσιμο στα δεξιά](https://postext.dev/el/docs/configuration-page-layout.md#βιβλιοδεσία)
- [Κείμενο από δεξιά προς τα αριστερά](https://postext.dev/el/docs/arabic-layout.md#κατεύθυνση-και-αμφικατευθυντικός-αλγόριθμος)
- [Kana, kanji και rōmaji](https://postext.dev/el/docs/japanese-layout.md#kanji-kana-και-rōmaji)
- [Σελίδες σε καμβά](https://postext.dev/el/docs/configuration-programmatic-usage.md#απόδοση-σελίδας-σε-bitmap)
- [Εξαγωγή PDF](https://postext.dev/el/docs/configuration-pdf-output.md#παραγωγή-pdf)
- [Σκόπιμη έξοδος από το πλέγμα](https://postext.dev/el/docs/architecture.md#στοιχεία-που-σπάνε-το-πλέγμα)
- [Γραμματοσειρές ενσωματωμένες στο PDF](https://postext.dev/el/docs/configuration-pdf-output.md#γιατί-πάροχος-γραμματοσειρών)
- [Προσαρμοσμένοι τύποι πόρων](https://postext.dev/el/docs/configuration-resources.md#τύποι-πόρων)
- [Εικόνες και πίνακες ως πόροι](https://postext.dev/el/docs/document-format-resources.md#πόροι)
- [Τρέχουσες κεφαλίδες ανά ενότητα](https://postext.dev/el/docs/configuration-styles.md#στιλ-επικεφαλίδων)

**Η διαμόρφωση με μια ματιά**

- [`bodyText`](https://postext.dev/el/docs/configuration-text.md#κυρίως-κείμενο), [`calloutStyles`](https://postext.dev/el/docs/configuration-callouts.md#στιλ-πλαισίων), [`chipStyles`](https://postext.dev/el/docs/configuration-styles.md#στιλ-ετικετών), [`colorPalette`](https://postext.dev/el/docs/configuration-fonts-colors-viewers.md#παλέτα-χρωμάτων), [`footer`](https://postext.dev/el/docs/configuration-headers-footers.md#κεφαλίδες-και-υποσέλιδα), [`header`](https://postext.dev/el/docs/configuration-headers-footers.md#κεφαλίδες-και-υποσέλιδα), [`headingStyles`](https://postext.dev/el/docs/configuration-styles.md#στιλ-επικεφαλίδων), [`headings`](https://postext.dev/el/docs/configuration-headings.md#επικεφαλίδες), [`layout`](https://postext.dev/el/docs/configuration-page-layout.md#διάταξη), [`locale`](https://postext.dev/el/docs/configuration-language.md#συλλαβισμός), [`page`](https://postext.dev/el/docs/configuration-page-layout.md#σελίδα), [`resourceTypes`](https://postext.dev/el/docs/configuration-resources.md#τύποι-πόρων)

**API**

- [`buildDocument`](https://postext.dev/el/docs/configuration-programmatic-usage.md#κατασκευή-εγγράφου), [`decompressWoff2`](https://postext.dev/el/docs/configuration-pdf-output.md#πάροχος-γραμματοσειρών-για-τον-browser-fontsource--woff2), [`registerResourceImage`](https://postext.dev/el/docs/architecture.md#η-επιφάνεια-του-api), [`renderPageToCanvas`](https://postext.dev/el/docs/configuration-programmatic-usage.md#απόδοση-σελίδας-σε-bitmap), [`renderToPdf`](https://postext.dev/el/docs/configuration-pdf-output.md#παραγωγή-pdf), [`withLoadedFonts`](https://postext.dev/el/docs/configuration-programmatic-usage.md#φόρτωση-γραμματοσειρών-πριν-από-τη-σελιδοποίηση)

**Γραμματοσειρές**

- Andika (OFL-1.1), Lexend (OFL-1.1), Playwrite GB J (OFL-1.1), Playwrite ES (OFL-1.1), Playwrite FR Trad (OFL-1.1), Playwrite DE VA (OFL-1.1), Playwrite IT Trad (OFL-1.1), Playwrite BR (OFL-1.1), LXGW WenKai TC (OFL-1.1), Noto Serif SC (OFL-1.1), Noto Sans SC (OFL-1.1), Klee One (OFL-1.1), Zen Maru Gothic (OFL-1.1), Playpen Sans Arabic (OFL-1.1), Noto Naskh Arabic (OFL-1.1), Baloo Bhaijaan 2 (OFL-1.1)

## Προετοιμασία

### 1 · Δώστε σε κάθε έκδοση τη σχολική της γραφή και το χαρτί της

```js
// script.js, γραμμές 30–54
// hand: the school model the children copy; ruling: the paper they copy it on; u: its
// x-height in mm (the height of an a), the unit every ruling is drawn in; rise: the room its
// capitals need above a title. The Chinese text is in Song: the Kai face, cut for Hong Kong
// and Taiwan, centres its commas, so it sets only the titles and the squares.
const EDITIONS = {
  en: { hand: 'Playwrite GB J', ruling: 'gb', u: 3.6 },
  es: { hand: 'Playwrite ES', ruling: 'pauta', u: 3.6 },
  ca: { hand: 'Playwrite ES', ruling: 'pauta', u: 3.6 },
  fr: { hand: 'Playwrite FR Trad', ruling: 'seyes', u: 3, rise: 5 },
  de: { hand: 'Playwrite DE VA', ruling: 'lineatur', u: 3.6 },
  it: { hand: 'Playwrite IT Trad', ruling: 'righe', u: 3.6 },
  pt: { hand: 'Playwrite BR', ruling: 'caligrafia', u: 3.2 },
  zh: { hand: 'LXGW WenKai TC', ruling: 'tian', text: 'Noto Serif SC',
    label: 'Noto Sans SC', pinyin: 'Andika', cell: 16 },
  ja: { hand: 'Klee One', ruling: 'masu', text: 'Klee One', label: 'Zen Maru Gothic', cell: 16 },
  ar: { hand: 'Playpen Sans Arabic', ruling: 'satr', u: 3.6,
    text: 'Noto Naskh Arabic', label: 'Baloo Bhaijaan 2' },
};
const ED = { text: 'Andika', label: 'Lexend', rise: 0, ...EDITIONS[LANG] };
const [HAND, TEXT, LABEL] = [ED.hand, ED.text, ED.label];
const CJK = ED.cell !== undefined; // a grid of squares, one character to each
const RTL = LANG === 'ar';
const LW = CJK ? 700 : 600; // the labels' weight: the CJK label faces ship no 600
// Labels in tracked capitals, where the script has capitals.
const caps = (n) => (!CJK && !RTL ? { textTransform: 'uppercase', letterSpacing: pt(n) } : {});
```

Το `u` είναι το ύψος του x σε χιλιοστά, η μονάδα στην οποία σχεδιάζονται όλες οι γραμμές: 3,6 mm για τις περισσότερες εκδόσεις, 3 mm για τα γαλλικά, που οι γραμμές Seyès τους απέχουν ένα ύψος x. Όλες οι οικογένειες Playwrite σχεδιάζουν το ύψος του x στο μισό του em, έτσι το μέγεθος του υποδείγματος είναι `u / 0.5`, και οι γραμμές πέφτουν εκεί όπου οι αναλογίες της ίδιας της γραμματοσειράς βάζουν τις ανιούσες και τις κατιούσες της. Το κινεζικό κείμενο στοιχειοθετείται σε Song (Noto Serif SC): η LXGW WenKai TC κεντράρει τα κόμματά της όπως τα τυπώνουν το Χονγκ Κονγκ και η Ταϊβάν, έτσι η γραμματοσειρά Kai στοιχειοθετεί μόνο τους τίτλους και τα τετράγωνα.

### 2 · Βάλτε το υπόδειγμα στις γραμμές, ως ζωντανό κείμενο

```js
// script.js, γραμμές 70–93
// :::callout{type="palabra" title="Repasa y escribe"} / niña / ::: draws four rows: the model
// and copies, a row of copies, the model and a copy, an empty row, all of them the box's word
// ({boxText}); a copy has `dotted`, `repeat` fills its row. A design text's baseline falls 0.8
// of its line below its top; a tall line keeps the descenders inside its clip.
const G = CJK ? null : geometry(ED.ruling, ED.u); // rows, baselines and the face's size
const [LABEL_H, GAP] = [7, 3 * ED.u]; // mm: the box's title above its ruling; between copies
const hand = (id, placement, extra) => text(id, '{boxText}', HAND, G.size / 0.3528, placement,
  { lineHeight: mm(G.line), overflow: 'clip', ...extra });
const dots = (many) => ({ color: col('dots'), dotted: { spacing: mm(0.2 * ED.u),
  size: mm(0.11 * ED.u) }, ...(many && { repeat: { gap: mm(GAP) } }) });
const onRow = (n, size) => at('container', 'top-left', 0, G.base[n] - 0.8 * G.line, size);
const model = (n) => hand(`model-${n}`, onRow(n));
// Copies after the model of row n (as many as fit, or one), or from the row's start.
const after = (n, many) => hand(`after-${n}`, { anchor: { to: `#model-${n}`,
  edge: 'right-of' }, offset: { x: mm(GAP) } }, dots(many));
const copies = (n, many) => hand(`copies-${n}`, onRow(n, { width: 'fill' }), dots(many));
const ruled = (rows, picture, texts) => ({ setsContent: true, minHeight: mm(G.height(rows)),
  slot: { elements: [image('ruling', picture, at('container', 'top-left', 0, 0,
    box(W, G.height(rows)))), ...texts] } });
// Every practice box: no frame, its title in the label face LABEL_H above the drawing.
const practice = (id, design, gap = mm(4)) => ({ id, design, backgroundEnabled: false,
  padding: { top: pt(0), right: pt(0), bottom: pt(0), left: pt(0) }, titleStyle: {
    fontFamily: LABEL, fontSize: pt(9), fontWeight: LW, color: col('accent'), lineHeight: mm(5),
    gap: mm(LABEL_H - 5), ...caps(1.2) }, marginTop: gap, marginBottom: mm(5), snapToGrid: false });
```

Μια σειρά εξάσκησης είναι ένα πλαίσιο, και η λέξη για εξάσκηση είναι το περιεχόμενό του: `:::callout{type="palabra" title="Trace and write"}`, έπειτα το `owl` σε δική του γραμμή, έπειτα `:::`. Όλες οι σειρές του ίδιου σχήματος μοιράζονται ένα στιλ πλαισίου και διαφέρουν μόνο στις λέξεις τους. Το `design` του στιλ σχεδιάζει τις γραμμές ως εικόνα και βάζει πάνω τους τη λέξη ως κείμενο στη σχολική γραμματοσειρά μέσω του `{boxText}`, και το υπόδειγμα και τα αντίγραφά του· το `setsContent` εμποδίζει το πλαίσιο να στοιχειοθετήσει το περιεχόμενό του δεύτερη φορά κάτω από το σχέδιο. Η γραμμή βάσης ενός κειμένου σχεδίασης πέφτει στο 0,8 του διάστιχού του κάτω από την κορυφή του πλαισίου του, έτσι το πλαίσιο του υποδείγματος τοποθετείται στη γραμμή βάσης της σειράς μείον 0,8 της γραμμής του, και τα γράμματα πατούν στη γραμμή που σχεδιάζουν οι γραμμές. Η γραμμή έχει ύψος δέκα ύψη x ώστε η περικοπή του πλαισίου να πέφτει 2 u κάτω από τη γραμμή βάσης, αρκετά βαθιά για την ουρά ενός g. Ο τίτλος του πλαισίου είναι η ετικέτα της σειράς. Οι επικεφαλίδες μένουν στη διάρθρωση του βιβλίου: το εξώφυλλο είναι η μόνη του επικεφαλίδα επιπέδου 1, κάθε μάθημα μία επιπέδου 2, και το `sectionEnd: 'heading'` του στιλ του εξωφύλλου σταματά τις κενές τρέχουσες κεφαλίδες του στο πρώτο μάθημα.

### 3 · Γράψτε τα αντίγραφα με στιγμές

Ένα αντίγραφο είναι το ίδιο `{boxText}` με `dotted`: η μηχανή ζωγραφίζει τα γράμματά του ως σειρές από στιγμές στη μέση κάθε πινελιάς, σε απόσταση 0,2 ύψους x, και αφήνει τη σελιδοποίηση όπως είναι. Οι στιγμές ακολουθούν τη γραμματοσειρά όπως τη διαμορφώνει το πρόγραμμα περιήγησης, έτσι οι ενώσεις της σχολικής γραφής και οι μορφές μιας αραβικής λέξης βγαίνουν σωστά, και η τελεία ενός i ή ενός τόνου είναι μία στιγμή. Το `repeat` βάζει τη λέξη ξανά μετά από τον εαυτό της όσες ολόκληρες φορές χωράει η σειρά, με απόσταση 3 u: τα αντίγραφα μετά το υπόδειγμα είναι ένα κείμενο αγκυρωμένο `right-of` το υπόδειγμα, η πλήρης σειρά ένα κείμενο τόσο φαρδύ όσο το πλαίσιο, το αντίγραφο μετά το δεύτερο υπόδειγμα το ίδιο κείμενο χωρίς `repeat`. Αλλάξτε τη λέξη στο Markdown και κάθε αντίγραφο και οι στιγμές του αλλάζουν μαζί της.

### 4 · Ξεσηκώστε χαρακτήρες στα τετράγωνά τους

```js
// script.js, γραμμές 97–129
// :::callout{type="caracteres" title="写一写"} with one character per list item: each in the
// first square of its row, three copies to trace in the pale red (描红) or grey (なぞり書き) of
// the next squares, then empty ones. A Han or kana character is one em wide, so tracking of
// (square − em) sets one per square.
const [CELL, EM] = [ED.cell ?? 16, (ED.cell ?? 16) * 0.72]; // mm: the square, its character
const SQUARES = Math.floor(W / CELL);
const row = (n, y, content, x, color) => text(`r${n}-${x}`, content, HAND, EM / 0.3528,
  at('container', 'top-left', x * CELL + (CELL - EM) / 2, y + (CELL - EM) / 2 + EM * 0.06,
    box(W - x * CELL, EM)),
  { lineHeight: mm(EM), letterSpacing: mm(CELL - EM), overflow: 'clip', color: col(color) });
// A sentence (type="frase") takes three rows: written out, traced, and a row to write it alone.
const squareBlock = (rows, sentence) => ({ setsContent: true, minHeight: mm(rows * CELL),
  slot: { elements: [image('grid', `squares-${rows}`,
    at('container', 'top-left', 0, 0, box(SQUARES * CELL, rows * CELL))),
  ...(sentence ? [row(0, 0, '{boxText}', 0, 'ink'), row(1, CELL, '{boxText}', 0, 'trace')]
    : Array.from({ length: rows }, (_, n) => [
      row(n, n * CELL, `{boxText.${n + 1}}`, 0, 'ink'),
      row(n, n * CELL, `{boxText.${n + 1}}`.repeat(3), 1, 'trace'),
    ]).flat()),
  ] } });
// Pinyin on four lines and three spaces (四线三格), :::callout{type="pinyin"} / bā / ::: —
// the syllable, copies to trace in the pale red, the syllable again and room after it.
const P = ED.pinyin ? geometry('sixian', 3.6) : null;
const pinyin = (id, n, x, content, color) => text(id, content, ED.pinyin, P.size / 0.3528,
  at('container', 'top-left', x, P.base[n] - 0.8 * P.line, { width: mm(W - x) }),
  { lineHeight: mm(P.line), overflow: 'clip', color: col(color) });
const syllables = Array(5).fill('{boxText}').join('\u00a0\u00a0\u00a0\u00a0');
const pinyinBlock = P && { setsContent: true, minHeight: mm(P.height(3)),
  slot: { elements: [
    image('lines', 'sixian', at('container', 'top-left', 0, 0, box(W, P.height(3)))),
    pinyin('p1', 0, 0, '{boxText}', 'ink'), pinyin('p1-copies', 0, 36, syllables, 'trace'),
    pinyin('p2', 1, 0, syllables, 'trace'), pinyin('p3', 2, 0, '{boxText}', 'ink'),
  ] } };
```

Ένας χαρακτήρας Han ή ένα kana έχει πλάτος ένα em, έτσι μια αραίωση χαρακτήρων ίση με το τετράγωνο μείον το em βάζει έναν χαρακτήρα σε κάθε τετράγωνο, όπως σε ένα 字帖. Το πρώτο τετράγωνο μιας σειράς έχει τον χαρακτήρα σε μελάνι, τα επόμενα τρία τον ίδιο χαρακτήρα στο απαλό κόκκινο του 描红 (γκρι στην ιαπωνική έκδοση), και τα υπόλοιπα μένουν άδεια. Ένα πλαίσιο σειράς γράφει τους τέσσερις χαρακτήρες του ως στοιχεία λίστας, που η σχεδίαση τα διαβάζει ένα ένα με `{boxText.1}` ως `{boxText.4}`. Μια πρόταση (ένα πλαίσιο `frase`) πιάνει τρεις σειρές: γραμμένη, για ξεσήκωμα, έπειτα άδεια, με τα σημεία στίξης σε δικό τους τετράγωνο. Οι σειρές pinyin της κινεζικής έκδοσης χρησιμοποιούν τις τέσσερις γραμμές των λατινικών εκδόσεων με την Andika, που τα μονώροφα a και g της είναι αυτά που μαθαίνουν τα παιδιά.

### 5 · Τίποτα δεν καθρεφτίζεται στο χέρι για τα αραβικά

Η αραβική έκδοση μοιράζεται κάθε σχεδίαση με τις άλλες. Μια σχεδίαση που μπαίνει στη ροή μιας σελίδας από δεξιά προς τα αριστερά, μιας επικεφαλίδας ή ενός πλαισίου, καθρεφτίζεται από τη μηχανή, έτσι ο δίσκος του γράμματος, το υπόδειγμα, τα αντίγραφά του και η πρώτη εικόνα του λεξικού μετακινούνται μόνα τους δεξιά· ένα επαναλαμβανόμενο κείμενο αρχίζει από την πλευρά όπου αρχίζει η κατεύθυνσή του. Μόνο τα κύματα της προθέρμανσης, σχεδιασμένα μέσα σε μια εικόνα, τρέχουν από δεξιά προς τα αριστερά στον κώδικα. Το `locale: 'ar'` δένει το βιβλίο στα δεξιά.

## Η πλήρης συνταγή

Ένα αρχείο, συντεθειμένο από τον φάκελο της συνταγής με το δείγμα κειμένου και το κοινό κιτ του Συνταγολογίου ενσωματωμένα· φτιάχνει τη δική του σελίδα. Για να το εκτελέσετε, βάλτε το σε ένα `<script type="module">` σε μια κενή σελίδα, ή επικολλήστε το στο πάνελ JS ενός νέου CodePen (ως module). Εισάγει το postext από το esm.sh, οπότε δεν χρειάζεται εγκατάσταση ούτε build.

- Φάκελος πηγής: https://github.com/drnachio/postext/tree/main/cookbook/handwriting-workbook

### script.js

```js
// ═══ Postext Cookbook · Nº 161 · Handwriting workbook in ten scripts ═══════════════
// https://postext.dev/en/cookbook/handwriting-workbook
// Code: MIT · Text: original (CC BY 4.0) · Pictures: generated with diffusion models
// Fonts: Playwrite, Playpen Sans Arabic, Klee One and others (SIL OFL) · Needs postext ≥ 1.65.0
import {
  buildDocument, withLoadedFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the workbook (en es ca fr de it pt zh ja ar)
const RECIPE = 'handwriting-workbook';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: a navy ink, one coral accent, the sun and the pale fields of the bands
const palette = {
  ink: '#22304a', accent: '#bf4630', // text and models; kickers, labels, folios
  sun: '#f4b73f', tint: '#fdf0da', // the boxes' stripe; opener bands, boxes
  rule: '#7f9ccc', dots: '#4d5b76', // the ruling; the dotted letters
  trace: LANG === 'ja' ? '#b4bccb' : '#e7a9a0', // traced over: 描红 in red, なぞり書き in grey
  paper: '#ffffff',
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion

// #region editions: each language its school's script, its ruling and its faces
// hand: the school model the children copy; ruling: the paper they copy it on; u: its
// x-height in mm (the height of an a), the unit every ruling is drawn in; rise: the room its
// capitals need above a title. The Chinese text is in Song: the Kai face, cut for Hong Kong
// and Taiwan, centres its commas, so it sets only the titles and the squares.
const EDITIONS = {
  en: { hand: 'Playwrite GB J', ruling: 'gb', u: 3.6 },
  es: { hand: 'Playwrite ES', ruling: 'pauta', u: 3.6 },
  ca: { hand: 'Playwrite ES', ruling: 'pauta', u: 3.6 },
  fr: { hand: 'Playwrite FR Trad', ruling: 'seyes', u: 3, rise: 5 },
  de: { hand: 'Playwrite DE VA', ruling: 'lineatur', u: 3.6 },
  it: { hand: 'Playwrite IT Trad', ruling: 'righe', u: 3.6 },
  pt: { hand: 'Playwrite BR', ruling: 'caligrafia', u: 3.2 },
  zh: { hand: 'LXGW WenKai TC', ruling: 'tian', text: 'Noto Serif SC',
    label: 'Noto Sans SC', pinyin: 'Andika', cell: 16 },
  ja: { hand: 'Klee One', ruling: 'masu', text: 'Klee One', label: 'Zen Maru Gothic', cell: 16 },
  ar: { hand: 'Playpen Sans Arabic', ruling: 'satr', u: 3.6,
    text: 'Noto Naskh Arabic', label: 'Baloo Bhaijaan 2' },
};
const ED = { text: 'Andika', label: 'Lexend', rise: 0, ...EDITIONS[LANG] };
const [HAND, TEXT, LABEL] = [ED.hand, ED.text, ED.label];
const CJK = ED.cell !== undefined; // a grid of squares, one character to each
const RTL = LANG === 'ar';
const LW = CJK ? 700 : 600; // the labels' weight: the CJK label faces ship no 600
// Labels in tracked capitals, where the script has capitals.
const caps = (n) => (!CJK && !RTL ? { textTransform: 'uppercase', letterSpacing: pt(n) } : {});
// #endregion

const W = 176; // mm: the type area's width, and every practice block's
// A design laid in the flow of a right-to-left page is mirrored by the engine, so 'left' is
// the start side in every edition: the Arabic book needs no coordinates of its own.
const box = (width, height) => ({ width: mm(width), height: mm(height) });
const at = (to, edge, x = 0, y = 0, size) => ({ anchor: { to, edge },
  offset: { x: mm(x), y: mm(y) }, ...(size && { size }) });
const text = (id, content, fontFamily, size, placement, extra = {}) => ({ kind: 'text', id,
  content, fontFamily, fontSize: pt(size), color: col('ink'), align: 'left', placement,
  ...extra });
const image = (id, resourceId, placement) => ({ kind: 'image', id, resourceId, placement,
  decorative: true });

// #region answer: a practice box: the model in the school face, then dots, then nothing
// :::callout{type="palabra" title="Repasa y escribe"} / niña / ::: draws four rows: the model
// and copies, a row of copies, the model and a copy, an empty row, all of them the box's word
// ({boxText}); a copy has `dotted`, `repeat` fills its row. A design text's baseline falls 0.8
// of its line below its top; a tall line keeps the descenders inside its clip.
const G = CJK ? null : geometry(ED.ruling, ED.u); // rows, baselines and the face's size
const [LABEL_H, GAP] = [7, 3 * ED.u]; // mm: the box's title above its ruling; between copies
const hand = (id, placement, extra) => text(id, '{boxText}', HAND, G.size / 0.3528, placement,
  { lineHeight: mm(G.line), overflow: 'clip', ...extra });
const dots = (many) => ({ color: col('dots'), dotted: { spacing: mm(0.2 * ED.u),
  size: mm(0.11 * ED.u) }, ...(many && { repeat: { gap: mm(GAP) } }) });
const onRow = (n, size) => at('container', 'top-left', 0, G.base[n] - 0.8 * G.line, size);
const model = (n) => hand(`model-${n}`, onRow(n));
// Copies after the model of row n (as many as fit, or one), or from the row's start.
const after = (n, many) => hand(`after-${n}`, { anchor: { to: `#model-${n}`,
  edge: 'right-of' }, offset: { x: mm(GAP) } }, dots(many));
const copies = (n, many) => hand(`copies-${n}`, onRow(n, { width: 'fill' }), dots(many));
const ruled = (rows, picture, texts) => ({ setsContent: true, minHeight: mm(G.height(rows)),
  slot: { elements: [image('ruling', picture, at('container', 'top-left', 0, 0,
    box(W, G.height(rows)))), ...texts] } });
// Every practice box: no frame, its title in the label face LABEL_H above the drawing.
const practice = (id, design, gap = mm(4)) => ({ id, design, backgroundEnabled: false,
  padding: { top: pt(0), right: pt(0), bottom: pt(0), left: pt(0) }, titleStyle: {
    fontFamily: LABEL, fontSize: pt(9), fontWeight: LW, color: col('accent'), lineHeight: mm(5),
    gap: mm(LABEL_H - 5), ...caps(1.2) }, marginTop: gap, marginBottom: mm(5), snapToGrid: false });
// #endregion

// #region squares: the Chinese and Japanese boxes, a character to a square
// :::callout{type="caracteres" title="写一写"} with one character per list item: each in the
// first square of its row, three copies to trace in the pale red (描红) or grey (なぞり書き) of
// the next squares, then empty ones. A Han or kana character is one em wide, so tracking of
// (square − em) sets one per square.
const [CELL, EM] = [ED.cell ?? 16, (ED.cell ?? 16) * 0.72]; // mm: the square, its character
const SQUARES = Math.floor(W / CELL);
const row = (n, y, content, x, color) => text(`r${n}-${x}`, content, HAND, EM / 0.3528,
  at('container', 'top-left', x * CELL + (CELL - EM) / 2, y + (CELL - EM) / 2 + EM * 0.06,
    box(W - x * CELL, EM)),
  { lineHeight: mm(EM), letterSpacing: mm(CELL - EM), overflow: 'clip', color: col(color) });
// A sentence (type="frase") takes three rows: written out, traced, and a row to write it alone.
const squareBlock = (rows, sentence) => ({ setsContent: true, minHeight: mm(rows * CELL),
  slot: { elements: [image('grid', `squares-${rows}`,
    at('container', 'top-left', 0, 0, box(SQUARES * CELL, rows * CELL))),
  ...(sentence ? [row(0, 0, '{boxText}', 0, 'ink'), row(1, CELL, '{boxText}', 0, 'trace')]
    : Array.from({ length: rows }, (_, n) => [
      row(n, n * CELL, `{boxText.${n + 1}}`, 0, 'ink'),
      row(n, n * CELL, `{boxText.${n + 1}}`.repeat(3), 1, 'trace'),
    ]).flat()),
  ] } });
// Pinyin on four lines and three spaces (四线三格), :::callout{type="pinyin"} / bā / ::: —
// the syllable, copies to trace in the pale red, the syllable again and room after it.
const P = ED.pinyin ? geometry('sixian', 3.6) : null;
const pinyin = (id, n, x, content, color) => text(id, content, ED.pinyin, P.size / 0.3528,
  at('container', 'top-left', x, P.base[n] - 0.8 * P.line, { width: mm(W - x) }),
  { lineHeight: mm(P.line), overflow: 'clip', color: col(color) });
const syllables = Array(5).fill('{boxText}').join('\u00a0\u00a0\u00a0\u00a0');
const pinyinBlock = P && { setsContent: true, minHeight: mm(P.height(3)),
  slot: { elements: [
    image('lines', 'sixian', at('container', 'top-left', 0, 0, box(W, P.height(3)))),
    pinyin('p1', 0, 0, '{boxText}', 'ink'), pinyin('p1-copies', 0, 36, syllables, 'trace'),
    pinyin('p2', 1, 0, syllables, 'trace'), pinyin('p3', 2, 0, '{boxText}', 'ink'),
  ] } };
// #endregion

// #region opener: a tinted band with the lesson's letters in a disc and its picture
const BAND = 40; // mm
const opener = { enabled: true, minHeight: mm(BAND + 7), slot: { elements: [
  { kind: 'box', id: 'band', style: { backgroundColor: col('tint'),
    borderRadius: mm(5) }, placement: at('container', 'top-left', 0, 0, box(W, BAND)) },
  text('letters', '{attr.letras}', HAND, CJK ? 30 : 26, at('container', 'top-left', 5, 5,
    box(40, 30)),
  { align: 'center', verticalAlign: 'middle', color: col('accent'), overflow: 'clip',
    box: { backgroundColor: col('paper'), borderRadius: mm(15) } }),
  text('kicker', '{attr.kicker}', LABEL, 9, at('container', 'top-left', 52, 8),
    { fontWeight: LW, color: col('accent'), ...caps(1.2) }),
  text('title', '{titleText}', HAND, CJK ? 26 : 24, at('container', 'top-left', 52,
    15 + ED.rise, { width: mm(80) }), { lineHeight: 1.25 }),
  { kind: 'box', id: 'card', style: { backgroundColor: col('paper'),
    borderRadius: mm(4) }, placement: at('container', 'top-right', -4, 3, box(34, 34)) },
  image('picture', '{attr.pic}', at('container', 'top-right', -5, 4, box(32, 32))),
] } };
// #endregion

// #region pages: the cover, the certificate and the picture dictionary
// The cover: a painted scene to the bleed, the title in the school face, a line for a name.
const COVER = 178; // mm from the top edge: the foot of the painting
const cover = { id: 'portada', header: { elements: [] }, footer: { elements: [] },
  sectionEnd: 'heading', // the book's only h1: its blank running heads end at the first h2
  advancedDesign: { enabled: true, slot: { elements: [
    image('scene', 'cover', at('page', 'top-left', 0, 0, { width: 'fill', height: mm(COVER) })),
    text('kicker', '{attr.kicker}', LABEL, 11, at('page', 'top', 0, COVER + 10),
      { align: 'center', fontWeight: LW, color: col('accent'), ...caps(1.6) }),
    text('title', '{titleText}', HAND, CJK ? 48 : 46, at('page', 'top', 0, COVER + 18 + ED.rise),
      { align: 'center', lineHeight: 1.2 }),
    text('name', '{attr.nombre}', LABEL, 12, at('page', 'top', -W / 2 + 24, COVER + 58),
      { color: col('ink') }),
    { kind: 'rule', id: 'name-line', direction: 'horizontal', thickness: pt(1),
      color: col('rule'), placement: at('page', 'top', 14, COVER + 64, { width: mm(110) }) },
    text('colophon', '{attr.colofon}', LABEL, 7, at('page', 'top', 0, 262, { width: mm(W) }),
      { align: 'center', color: col('dots'), lineHeight: 1.4 }),
  ] } } };
// The last page: the same frame as a certificate, the child's name and the date to fill in.
const diploma = { id: 'diploma', header: { elements: [] }, footer: { elements: [] },
  advancedDesign: { enabled: true, minHeight: mm(250), slot: { elements: [
    { kind: 'box', id: 'frame', style: { borderColor: col('sun'),
      borderWidth: pt(5), borderRadius: mm(8), backgroundColor: col('paper') },
    placement: at('container', 'top-left', 0, 4, box(W, 244)) },
    image('picture', 'medal', at('container', 'top', 0, 22, box(70, 70))),
    text('title', '{titleText}', HAND, CJK ? 40 : 38, at('container', 'top', 0, 104,
      { width: mm(W - 20) }), { align: 'center', color: col('accent'), lineHeight: 1.2 }),
    text('body', '{attr.texto}', TEXT, 15, at('container', 'top', 0, 136, { width: mm(130) }),
      { align: 'center', lineHeight: 1.45 }),
    ...[0, 1].map((n) => text(`field-${n}`, `{attr.${['nombre', 'fecha'][n]}}`, LABEL, 11,
      at('container', 'top-left', 28, 186 + n * 22), { color: col('dots') })),
    ...[0, 1].map((n) => ({ kind: 'rule', id: `line-${n}`, direction: 'horizontal',
      thickness: pt(1), color: col('rule'),
      placement: at('container', 'top-left', 28, 192 + n * 22, { width: mm(W - 56) }) })),
  ] } } };
// The picture dictionary, :::callout{type="diccionario" p1="cat" …} with the four words as a
// list: four pictures to a row, each word under its picture in the school face, and a line to
// copy it on.
const SLOT = W / 4;
const dictionary = { setsContent: true, minHeight: mm(58),
  slot: { elements: [0, 1, 2, 3].flatMap((n) => [
    image(`p${n}`, `{attr.p${n + 1}}`, at('container', 'top-left', n * SLOT + (SLOT - 34) / 2,
      0, box(34, 34))),
    text(`w${n}`, `{boxText.${n + 1}}`, HAND, CJK ? 20 : 17, at('container', 'top-left',
      n * SLOT, 36, box(SLOT, 10)), { align: 'center', overflow: 'clip' }),
    { kind: 'rule', id: `l${n}`, direction: 'horizontal', thickness: pt(0.75),
      color: col('rule'), placement: at('container', 'top-left', n * SLOT + 4, 54,
        { width: mm(SLOT - 8) }) },
  ]) } };
// #endregion

// The folio in an accent disc at the outer foot, the book's title beside it.
const foot = (parity, edge, side) => [
  text(`folio-${parity}`, '{pageNumber}', LABEL, 10, { anchor: { to: 'page', edge },
    offset: { x: mm(18 * side), y: mm(-9) }, size: box(8, 8) }, { parity, align: 'center',
    verticalAlign: 'middle', fontWeight: 700, color: col('paper'), lineHeight: 1.17,
    box: { backgroundColor: col('accent'), borderRadius: mm(4) } }),
  text(`title-${parity}`, '{title} · {subtitle}', LABEL, 7.5, { anchor: { to: 'page', edge },
    offset: { x: mm(29 * side), y: mm(-11) } },
  { parity, color: col('dots'), align: side > 0 ? 'left' : 'right', ...caps(1) }),
];

const config = {
  // Hyphenation, punctuation, direction and binding follow the edition's language.
  locale: t({ en: 'en-gb', es: 'es', ca: 'ca', fr: 'fr', de: 'de', it: 'it', pt: 'pt-BR',
    zh: 'zh-Hans', ja: 'ja', ar: 'ar' }),
  resourceTypes: [{ id: 'dibujo', name: 'Dibujo', shortLabel: '', captionPrefix: '',
    numberingTemplate: '', resetOn: 'never', counterFormat: 'decimal',
    defaultPlacement: { position: 'here' } }],
  colorPalette,
  page: { sizePreset: 'custom', width: mm(210), height: mm(297), dpi: 150,
    margins: { top: mm(16), bottom: mm(22), left: mm(18), right: mm(16), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: {
    fontFamily: TEXT, fontSize: pt(CJK ? 13.5 : 14), lineHeight: pt(RTL ? 25 : 20),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'),
    referenceColor: col('ink'), textAlign: RTL || CJK ? 'justify' : 'left',
    firstLineIndent: pt(0), paragraphSpacing: true, hyphenation: { enabled: !CJK && !RTL },
    optimalLineBreaking: true, avoidWidows: true, avoidOrphans: true, avoidRunts: true,
  },
  headings: {
    fontFamily: HAND, color: col('ink'), fontWeight: 400,
    levels: [ // h1 is the book (the cover style draws it), h2 each section; exercises are boxes
      { level: 1, breakBefore: { enabled: true, parity: 'any' }, marginTop: pt(0),
        marginBottom: mm(3) },
      { level: 2, breakBefore: { enabled: true, parity: 'any' }, marginTop: pt(0),
        marginBottom: mm(3), advancedDesign: opener },
    ],
  },
  headingStyles: [cover, diploma],
  chipStyles: [ // a blank to write a letter in, a letter tile, a word in dots to trace
    { id: 'hueco', fontFamily: LABEL, background: col('paper'), borderColor: col('rule'),
      borderWidth: pt(1), borderRadius: mm(1.2), paddingX: mm(4), paddingY: em(0.12) },
    { id: 'letra', fontFamily: HAND, background: col('tint'), borderColor: col('sun'),
      borderWidth: pt(1), borderRadius: mm(1.6), paddingX: mm(2), paddingY: em(0.08) },
    { id: 'puntos', fontFamily: HAND, fontSize: em(1.25), color: col('dots'), dotted: {},
      backgroundEnabled: false, borderWidth: pt(0), paddingX: pt(0), paddingY: pt(0) }],
  calloutStyles: [{ id: 'recuerda', background: col('tint'), borderRadius: mm(3),
    stripe: { enabled: true, side: 'left', width: pt(4), color: col('sun') },
    padding: { top: mm(3), right: mm(5), bottom: mm(3.5), left: mm(5) },
    titleStyle: { fontFamily: LABEL, fontSize: pt(9), fontWeight: LW, color: col('accent'),
      ...caps(1.2) },
    body: { fontFamily: TEXT, fontSize: pt(12), lineHeight: pt(RTL ? 21 : 17),
      color: col('ink'), boldColor: col('ink'), italicColor: col('ink'),
      firstLineIndent: pt(0) } },
    // One style per shape of exercise, whatever its words (the box's content).
    ...(CJK ? [practice('caracteres', squareBlock(4)), practice('frase', squareBlock(3, true))] : [
      practice('trazos', ruled(4, 'trazo-{attr.pattern}', [])),
      practice('palabra', ruled(4, 'ruling-4',
        [model(0), after(0, true), copies(1, true), model(2), after(2)])),
      practice('frase', ruled(3, 'ruling-3', [model(0), copies(1)]))]), // a sentence: once
    ...(P ? [practice('pinyin', pinyinBlock)] : []),
    { ...practice('diccionario', dictionary, mm(3)), marginBottom: mm(3) }],
  header: { elements: [] },
  footer: { elements: [...foot('even', 'bottom-left', 1), ...foot('odd', 'bottom-right', -1)] },
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "I Can Write"
subtitle: "Handwriting book 1"
---

# I can write {style="portada" kicker="Handwriting book · Joined writing" nombre="My name is" colofon="Set in Playwrite GB J, Andika and Lexend (SIL OFL) · Original text (CC BY 4.0) · Pictures generated with diffusion models"}

## Warm up {kicker="Before you start" letras="a b c" pic="grip"}

Sit up straight with both feet on the floor. Hold your pencil between your thumb and first finger, resting on your middle finger, and do not squeeze. Trace the dots from left to right without lifting your pencil.


:::callout{type="trazos" title="Waves on the sea" pattern="waves"}
:::

:::callout{type="trazos" title="Loops like a spring" pattern="loops"}
:::

## Round letters {kicker="Lesson 1" letras="c a d" pic="duck"}

The letters **c, a, d, g, o** and **q** all start the same way: go up to the top of the middle line and round back like a **c**. Each one ends with a little flick that joins it to the next letter.

:::callout{type="palabra" title="Trace and write"}
c a d g o
:::

:::callout{type="palabra" title="Trace and write"}
dog
:::

Which letter is missing? :chip[ ]{style="hueco"}at · d:chip[ ]{style="hueco"}g · c:chip[ ]{style="hueco"}t · b:chip[ ]{style="hueco"}d

:::callout{type="recuerda" title="Remember"}
Start every round letter at the top, at **one o'clock**, and go round anticlockwise.
:::

## Sh, ch and th {kicker="Lesson 2" letras="sh ch th" pic="fish"}

Two letters can make one sound. **sh** is the sound in fish and shop, **ch** is the sound in chip and lunch, and **th** is the sound in thumb and this. Join the two letters without lifting your pencil.

:::callout{type="palabra" title="Trace and write"}
fish
:::

:::callout{type="palabra" title="Trace and write"}
chip
:::

sh, ch or th? :chip[ ]{style="hueco"}op · lun:chip[ ]{style="hueco"} · ba:chip[ ]{style="hueco"} · :chip[ ]{style="hueco"}in

:::callout{type="recuerda" title="Remember"}
The **h** is a tall letter: its loop reaches the top line.
:::

## Ck and ng {kicker="Lesson 3" letras="ck ng" pic="kite"}

After a short vowel, the sound **k** at the end of a word is spelt **ck**: duck, sock, back. The sound in ring and long is spelt **ng**, and the g hangs below the line.

:::callout{type="palabra" title="Trace and write"}
duck
:::

:::callout{type="palabra" title="Trace and write"}
ring
:::

Finish the word: so:chip[ ]{style="hueco"} · si:chip[ ]{style="hueco"} · ba:chip[ ]{style="hueco"} · lo:chip[ ]{style="hueco"}

:::callout{type="recuerda" title="Remember"}
**ck** never starts a word. Cat and kit start with c and k.
:::

## Magic e {kicker="Lesson 4" letras="a–e" pic="cake"}

An **e** at the end of a word is silent, but it changes the vowel before it: it says its name. **kit** becomes **kite**, **cap** becomes **cape** and **hop** becomes **hope**.

:::callout{type="palabra" title="Trace and write"}
kite
:::

:::callout{type="palabra" title="Trace and write"}
cake
:::

Add the magic e and read: tap, :chip[tape]{style="puntos"} · pin, :chip[pine]{style="puntos"} · cub, :chip[cube]{style="puntos"}

:::callout{type="recuerda" title="Remember"}
The magic e joins to the letter before it like any other letter.
:::

## Ee, ai and oa {kicker="Lesson 5" letras="ee oa" pic="bee"}

Two vowels can work together. **ee** says its name in bee and tree, **ai** in rain and snail, and **oa** in boat and coat. Join the two vowels with a short line along the middle.

:::callout{type="palabra" title="Trace and write"}
bee
:::

:::callout{type="palabra" title="Trace and write"}
boat
:::

ee, ai or oa? tr:chip[ ]{style="hueco"} · r:chip[ ]{style="hueco"}n · g:chip[ ]{style="hueco"}t · sh:chip[ ]{style="hueco"}p

:::callout{type="recuerda" title="Remember"}
The join from **o** starts at the top, along the middle line.
:::

## Tricky words {kicker="Lesson 6" letras="th" pic="owl"}

Some words do not sound the way they are spelt. You learn them by heart: **the**, **said**, **was**, **they**, **you**. Look at the word, say it, cover it and write it.

:::callout{type="palabra" title="Trace and write"}
said
:::

:::callout{type="palabra" title="Trace and write"}
they
:::

Copy each word once: the · was · you · said

:::callout{type="recuerda" title="Remember"}
Look, say, cover, write and check: five steps for every tricky word.
:::

## Capital letters {kicker="Lesson 7" letras="A B" pic="house"}

Names and the first word of a sentence start with a **capital letter**. Capital letters do not join to the letter after them, so lift your pencil after each one.

:::callout{type="palabra" title="Trace and write"}
Anna
:::

:::callout{type="palabra" title="Trace and write"}
Leeds
:::

Write each name with a capital: tom · leeds · may · london

:::callout{type="recuerda" title="Remember"}
**I** is always a capital when you write about yourself.
:::

## My first words {kicker="Picture dictionary" letras="abc" pic="tree"}

Read each word and copy it on the line underneath in your best handwriting.

:::callout{type="diccionario" p1="sun" p2="moon" p3="cat" p4="fish"}
- sun
- moon
- cat
- fish
:::

:::callout{type="diccionario" p1="house" p2="boat" p3="duck" p4="key"}
- house
- boat
- duck
- key
:::

:::callout{type="diccionario" p1="shoe" p2="apple" p3="bee" p4="tree"}
- shoe
- apple
- bee
- tree
:::

## Copy a sentence {kicker="Lesson 8" letras="Aa" pic="butterfly"}

A sentence starts with a capital letter and ends with a full stop. Leave a space the size of a small o between words.

:::callout{type="frase" title="Copy the sentence"}
My cat sleeps in the sun.
:::

:::callout{type="frase" title="Copy the sentence"}
The moon is up at night.
:::

:::callout{type="frase" title="Copy the sentence"}
I like to write.
:::

## I can write! {style="diploma" texto="You have practised round letters, sh, ch and th, ck and ng, magic e, vowel teams and tricky words. Now you can write your own stories." nombre="Name" fecha="Date"}
`; // content.<lang>.md, inlined by the Cookbook

// #region art: the edition's ruling and the warm-up strokes, drawn in code
// Each country's paper, in x-heights (u) above and below the baseline. lines: [height,
// weight] pairs; band: a filled band; seyes: the French grid of 1 u squares, a heavy line
// every 4 u, verticals every 4 u; Seyès and the Italian page rule a red margin where the
// writing starts.
function geometry(style, u) {
  const R = {
    pauta: { above: 2, below: 1, gap: 1, lines: [[-1, 0.4], [0, 0.9], [1, 0.9], [2, 0.4]] },
    gb: { above: 2, below: 1, gap: 0.8,
      lines: [[-0.8, 0.5], [0, 0.9], [1, 0.5, 'dash'], [1.8, 0.5]] },
    lineatur: { above: 2, below: 1, gap: 1, lines: [[-1, 0.6], [0, 0.6], [1, 0.6], [2, 0.6]],
      band: [0, 1, '#fdf3c7'] },
    righe: { above: 2, below: 1, gap: 1, lines: [[-1, 0.4], [0, 0.8], [1, 0.8], [2, 0.4]],
      margin: true },
    caligrafia: { above: 2.4, below: 1.4, gap: 0.8, lines: [[-1.3, 0.4], [0, 0.9], [1, 0.9],
      [2.3, 0.4]], band: [0, 1, '#e8f0fb'] },
    satr: { above: 2, below: 1, gap: 1, lines: [[-1, 0.4], [0, 0.9], [1, 0.5, 'dash'], [2, 0.4]] },
    seyes: { above: 4, below: 2, gap: -2, seyes: true }, // a row on every heavy line
    sixian: { above: 2, below: 1, gap: 1, lines: [[-1, 0.6], [0, 0.9], [1, 0.6], [2, 0.6]] },
  }[style];
  const pitch = (R.above + R.below + R.gap) * u;
  const base = [0, 1, 2, 3].map((n) => n * pitch + R.above * u);
  // The faces set their x-height at half the em, Playpen Sans Arabic its tooth at 0.4.
  const xh = { satr: 0.4, sixian: 0.508 }[style] ?? 0.5; // Andika's x-height for pinyin
  // line: a tall box for the models, whose clip falls 2 u under the baseline.
  return { ...R, u, pitch, base, size: u / xh, line: u * 10,
    height: (rows) => (rows - 1) * pitch + (R.above + R.below) * u };
}
const n2 = (v) => +v.toFixed(2);
function ruling(g, rows) {
  const out = [];
  const h = g.height(rows);
  const hline = (y, w, dash) => out.push(`<path d="M0 ${n2(y)}H${W}" stroke="${palette.rule}" `
    + `stroke-width="${n2(w * 0.3528)}" stroke-opacity="${w < 0.6 ? 0.55 : 1}"`
    + `${dash ? ' stroke-dasharray="1.2 1"' : ''}/>`);
  if (g.seyes) {
    for (let k = 0; k <= h / g.u + 1e-6; k++) hline(k * g.u, k % 4 === 0 ? 0.9 : 0.35);
    for (let x = 4 * g.u; x <= W; x += 4 * g.u) out.push(`<path d="M${n2(x)} 0V${n2(h)}" `
      + `stroke="${palette.rule}" stroke-width=".12"/>`);
    out.push(`<path d="M.2 0V${n2(h)}" stroke="#d9534f" stroke-width=".3"/>`);
    return out.join('');
  }
  for (const b of g.base.slice(0, rows)) {
    if (g.band) out.push(`<rect x="0" y="${n2(b - g.band[1] * g.u)}" width="${W}" `
      + `height="${n2((g.band[1] - g.band[0]) * g.u)}" fill="${g.band[2]}"/>`);
    for (const [k, w, dash] of g.lines) hline(b - k * g.u, w, dash);
  }
  if (g.margin) out.push(`<path d="M.2 0V${n2(h)}" stroke="#d9534f" stroke-width=".3"/>`);
  return out.join('');
}
// Warm-up strokes: curves drawn by code, in dots as far apart as the letters' copies.
const PATTERNS = { // s runs along the stroke; x and y in 2 u, from the baseline up
  lines: (s) => [Math.floor(s) * 0.5, s % 1], // sticks, each drawn from the foot up
  waves: (s) => [s * 0.5, (1 - Math.cos(s * Math.PI)) / 4], // waves in the x-height band
  loops: (s) => [s * 0.5 - 0.2 * Math.sin(2 * Math.PI * s), (1 - Math.cos(2 * Math.PI * s)) / 2],
};
function pattern(name, x0, x1, base, u) {
  const f = PATTERNS[name]; const pts = []; const pitch = 0.2 * u;
  let prev = null; let acc = 0;
  for (let s = 0; s < 400; s += 0.002) {
    const [px, py] = f(s); const p = [x0 + px * u * 2, base - py * u * 2];
    if (p[0] > x1) break;
    acc += prev ? Math.hypot(p[0] - prev[0], p[1] - prev[1]) : pitch;
    prev = p;
    if (acc < pitch) continue;
    pts.push(`M${n2(RTL ? W - p[0] : p[0])} ${n2(p[1])}h.01`); acc = 0;
  }
  return `<path d="${pts.join('')}" stroke="${palette.dots}" stroke-width="${n2(0.11 * u)}" `
    + 'stroke-linecap="round" fill="none"/>';
}
// The pictures the practice boxes name: the ruling of a word (four rows) and of a sentence
// (three), a warm-up pattern on its ruling (two rows of it and the start of a third), or the
// edition's squares and its pinyin lines.
async function practicePictures(add) {
  const svg = (w, h, body) => `<svg xmlns="http://www.w3.org/2000/svg" width="${W * 10}" `
    + `height="${n2(h * 10)}" viewBox="0 0 ${w} ${n2(h)}">${body}</svg>`;
  const put = async (id, rows, body) => {
    await loadSvg(`${id}.svg`, svg(W, G.height(rows), body));
    add(id, `${id}.svg`, 'svg', W * 10, G.height(rows) * 10);
  };
  if (G) {
    for (const rows of [3, 4]) await put(`ruling-${rows}`, rows, ruling(G, rows));
    for (const name of Object.keys(PATTERNS)) await put(`trazo-${name}`, 4, ruling(G, 4)
      + [W, W, W * 0.4].map((end, row) => pattern(name, 2, end - 2, G.base[row], G.u)).join(''));
  }
  if (P) {
    await loadSvg('sixian.svg', svg(W, P.height(3), ruling(P, 3)));
    add('sixian', 'sixian.svg', 'svg', W * 10, P.height(3) * 10);
  }
  if (CJK) for (const rows of [3, 4]) {
    await loadSvg(`squares-${rows}.svg`, squaresSvg(rows));
    add(`squares-${rows}`, `squares-${rows}.svg`, 'svg', SQUARES * CELL * 10, rows * CELL * 10);
  }
}
// The squares: 田字格 in red with a dashed cross, or マス with a dotted cross in grey-blue.
function squaresSvg(rows) {
  const c = CELL; const n = SQUARES; const red = ED.ruling === 'tian';
  const ink = red ? '#d0574b' : palette.rule;
  const cross = Array.from({ length: rows }, (_, r) => Array.from({ length: n }, (_, k) =>
    `M${k * c + c / 2} ${r * c + 0.6}V${r * c + c - 0.6}M${k * c + 0.6} ${r * c + c / 2}`
    + `H${k * c + c - 0.6}`).join('')).join('');
  const grid = Array.from({ length: n + 1 }, (_, k) => `M${k * c} 0V${rows * c}`).join('')
    + Array.from({ length: rows + 1 }, (_, r) => `M0 ${r * c}H${n * c}`).join('');
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${n * c * 10}" height="${rows * c * 10}" `
    + `viewBox="0 0 ${n * c} ${rows * c}"><path d="${cross}" fill="none" stroke="${ink}" `
    + `stroke-opacity=".55" stroke-width=".2" stroke-dasharray="${red ? '.9 .6' : '.25 .55'}"/>`
    + `<path d="${grid}" fill="none" stroke="${ink}" stroke-width=".35"/></svg>`;
}
// #endregion


// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = {
  Andika: ['400', '700'], // the text: drawn for children learning to read
  Lexend: ['400', '600', '700'], // labels, kickers, folios
  // The school models, one per country: Google's Playwrite families follow each one.
  'Playwrite GB J': ['400'], 'Playwrite ES': ['400'], 'Playwrite FR Trad': ['400'],
  'Playwrite DE VA': ['400'], 'Playwrite IT Trad': ['400'], 'Playwrite BR': ['400'],
  'LXGW WenKai TC': ['400'], // 楷: the Chinese titles and squares
  'Noto Serif SC': ['400', '700'], // 宋: the Chinese text
  'Noto Sans SC': ['400', '700'], // 黑: Chinese labels
  'Klee One': ['400'], // 教科書体: the Japanese text and its squares
  'Zen Maru Gothic': ['400', '700'], // Japanese labels
  'Playpen Sans Arabic': ['400'], // the Arabic model
  'Noto Naskh Arabic': ['400', '700'], // the Arabic text, vocalised
  'Baloo Bhaijaan 2': ['400', '600', '700'], // Arabic labels
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
// The edition loads its own faces only: its school face, its text and its labels.
const used = [HAND, TEXT, LABEL, ED.pinyin];
for (const family of Object.keys(FONTS)) if (!used.includes(family)) delete FONTS[family];
await loadFonts(FONTS, markdown);
await loadCjkFonts(FONTS, markdown);
await loadArabicFonts(FONTS, markdown);
const resources = []; // every picture, painted or drawn
const add = (id, fileId, kind, width, height, more = {}) => resources.push({ id, kind,
  typeId: 'dibujo', createdAt: 0, updatedAt: 0, [kind]: { fileId, width, height, ...more } });
// The paintings the edition names (pic="…", p1="…"), from one shared set, at their pixels.
const named = new Set(['medal',
  ...[...markdown.matchAll(/\b(?:pic|p\d)="(\w+)"/g)].map((m) => m[1])]);
await Promise.all([['cover', 'cover-1600.jpg', 1600, 1356],
  ...[...named].map((id) => [id, `${id}-480.jpg`, 480, 480])].map(async ([id, file, w, h]) => {
  await loadImage(file, asset(file)); add(id, file, 'bitmap', w, h, { format: 'jpeg' });
}));
await practicePictures(add); // the rulings, the warm-up strokes and the squares (#region art)
const doc = await withLoadedFonts(() => buildDocument({ markdown, resources }, config),
  { ...kitFonts(FONTS), text: markdown });
showBook(doc, { title: t({ en: 'Handwriting workbook', es: 'Cuaderno de caligrafía',
  ca: 'Quadern de cal·ligrafia', fr: 'Cahier d’écriture', de: 'Schreibheft',
  it: 'Quaderno di scrittura', pt: 'Caderno de caligrafia', zh: '写字练习册',
  ja: 'かきかたれんしゅうちょう', ar: 'كراسة الخط' }) });
offerPdf(() => renderToPdf(doc, { resourceBytes: imageBytes,
  fontProvider: { zh: cjkPdfProvider, ja: cjkPdfProvider, ar: arabicPdfProvider }[LANG]
    ?? fontsourceProvider }), `${RECIPE}-${LANG}.pdf`);

// ─── 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 · cjk v2 ── Chinese, Japanese and Korean books · postext.dev/cookbook
// Fontsource ships a CJK family as about a hundred files per weight, each
// declared in its stylesheet with the unicode-range it covers. The screen
// loads the files the sample touches; the PDF gets the same files for the
// characters its pages set in each face, and embeds each as a subset.
// A book bound on the right (vertical text) is shown with its spreads
// mirrored: page 1 alone on the left of the spine, then [3 | 2].

/** The files of a Fontsource face, read from its stylesheet: { url, range,
 *  ranges }, the last declared first (the order the browser tries them in). */
function cjkSlices(family, weight, style) {
  cjkSlices.cache ??= new Map();
  const id = fontsourceId(family);
  const css = `${id}/${weight}${style === 'italic' ? '-italic' : ''}.css`;
  if (!cjkSlices.cache.has(css)) {
    let at;
    cjkSlices.cache.set(css, fontsourceAt(id).then((a) => fetch(at = a + css.slice(id.length + 1)))
      .then((res) => {
        if (!res.ok) throw new Error(`Fontsource has no ${family} ${weight} ${style} (${res.status})`);
        return res.text();
      })
      .then((text) => [...text.matchAll(/@font-face\s*{([^}]*)}/g)].map(([, rule]) => {
        const range = /unicode-range:\s*([^;]+);/.exec(rule)?.[1].trim() ?? 'U+0-10FFFF';
        const ranges = range.split(',').map((part) => {
          const [lo, hi = lo] = part.trim().slice(2).split('-');
          return [parseInt(lo, 16), parseInt(hi, 16)];
        });
        return { url: new URL(/url\(([^)]+?\.woff2)\)/.exec(rule)[1], at).href, range, ranges };
      }).reverse()));
  }
  return cjkSlices.cache.get(css);
}

/** The file of `slices` the screen sets code point `cp` in, if any: the
 *  last one loadCjkFonts adds whose range holds it. A numbered file that
 *  repeats a letter of latin is added after latin, and wins it. */
function cjkSliceFor(slices, cp) {
  const holds = (slice) => slice.ranges.some(([lo, hi]) => cp >= lo && cp <= hi);
  return slices.reduce((last, slice) => (holds(slice) ? slice : last), undefined);
}

/** Whether Fontsource serves `family` as a Chinese, Japanese or Korean
 *  family (its subsets name the script). Fails when the API does not
 *  answer: a CJK face taken for a Latin one would paint in a system face. */
async function isCjkFamily(family) {
  const meta = await fontsourceMeta(family);
  if (!meta) throw new Error(`api.fontsource.org did not describe ${family}: reload to try again`);
  return !!meta.subsets?.some((subset) => /^(chinese|japanese|korean)/.test(subset));
}

/** faces = { 'Noto Serif TC': ['400', '700'] }, as for loadFonts: the
 *  whole FONTS object may be passed, its other families are left to
 *  loadFonts. Adds one FontFace per file of each CJK face with its
 *  unicodeRange, then loads the files `text` touches. `text` is what the
 *  faces set: the sample for the text face; a book in several voices calls
 *  it once per voice (loadCjkFonts({ 'LXGW WenKai TC': ['400'] }, quotes)),
 *  so the heading and quotation faces fetch and check only their own
 *  characters. Fails when a character of `text` is in no file of a face.
 *  List every weight the pages use: a weight left to the engine's later round
 *  gets the latin file only. With { vertical: true } it also loads each
 *  family's vertical forms (brackets, quotes, pause marks) for the canvas,
 *  which needs loadVerticalAlternates imported from postext. Resolves to
 *  the number of files loaded. */
async function loadCjkFonts(faces, text, { vertical = false } = {}) {
  kitStatus('Loading fonts…');
  let loaded = 0;
  try {
    if (vertical && typeof loadVerticalAlternates !== 'function') {
      throw new Error('loadCjkFonts(…, { vertical: true }) needs loadVerticalAlternates imported from postext');
    }
    for (const [family, specs] of Object.entries(faces)) {
      if (!(await isCjkFamily(family))) continue;
      const twin = [];
      for (const spec of new Set(specs)) {
        const weight = parseInt(spec, 10);
        const style = spec.endsWith('i') ? 'italic' : 'normal';
        const slices = await cjkSlices(family, weight, style);
        const missing = [...new Set(text)].filter((ch) => /\S/.test(ch) && !cjkSliceFor(slices, ch.codePointAt(0)));
        if (missing.length) {
          throw new Error(`${family} ${spec} has no file for ${missing.slice(0, 12).join(' ')}: `
            + `give each face the text it sets (loadCjkFonts({ '${family}': ['${spec}'] }, text))`);
        }
        for (const slice of slices) {
          document.fonts.add(new FontFace(family, `url(${slice.url}) format('woff2')`,
            { weight: String(weight), style, unicodeRange: slice.range }));
          twin.push({ source: slice.url, weight: String(weight), style, unicodeRange: slice.range });
        }
        const font = `${style === 'italic' ? 'italic ' : ''}${weight} 16px "${family}"`;
        loaded += (await document.fonts.load(font, text)).length;
        if (!document.fonts.check(font, text)) throw new Error(`${family} ${spec} did not load for the sample`);
      }
      // The same files under a twin name with the `vert` feature on: the
      // canvas paints the punctuation of vertical lines with it.
      if (vertical && twin.length) await loadVerticalAlternates(family, twin);
    }
  } catch (error) {
    kitFail(error);
    throw error;
  }
  return loaded;
}

/** The PDF font provider for recipes with CJK faces: a family whose
 *  Fontsource subsets are Chinese, Japanese or Korean gets the files the
 *  screen set its pages' characters in (`request.codePoints`), each marked
 *  with its unicode-range and its place in the order loadCjkFonts added
 *  them: postext-pdf sets a character two files hold in the one added
 *  last, as the browser does. Any other family gets the latin file
 *  fontsourceProvider fetches (the "pdf" block) and, when the face sets
 *  letters only latin-ext has, that file too. */
async function cjkPdfProvider(family, weight, style, request) {
  if (!(await isCjkFamily(family))) return cjkLatinPdfFiles(family, weight, style, request);
  const meta = await fontsourceMeta(family);
  const weights = meta.weights?.length ? meta.weights : [400, 700];
  const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const s = style === 'italic' && !meta.styles.includes('italic') ? 'normal' : style;
  const slices = await cjkSlices(family, w, s);
  const picked = new Set();
  for (const cp of request?.codePoints ?? []) {
    const slice = cjkSliceFor(slices, cp);
    if (slice) picked.add(slice);
  }
  if (!picked.size) picked.add(slices[0]);
  return Promise.all(slices.map(async (slice, order) => {
    if (!picked.has(slice)) return null;
    const res = await fetch(slice.url);
    if (!res.ok) throw new Error(`Fontsource file ${slice.url} (${res.status})`);
    const bytes = await decompressWoff2(new Uint8Array(await res.arrayBuffer()));
    return Object.assign(bytes, { unicodeRange: slice.range, order });
  })).then((files) => files.filter(Boolean));
}

/** A Latin family set next to the CJK faces: its latin file, then its
 *  latin-ext file when the face sets letters only latin-ext has (ō ū in
 *  Hepburn rōmaji, ǎ in pinyin), the file loadFonts adds on screen for
 *  them, each marked with its unicode-range and its place in that order:
 *  the PDF sets a character in the file the browser took it from. A face
 *  Fontsource ships without latin-ext, or whose file does not come, gets
 *  latin alone, and the PDF names the letters it lacks. */
async function cjkLatinPdfFiles(family, weight, style, request) {
  const meta = await fontsourceMeta(family);
  const beyond = [...(request?.codePoints ?? [])].some(cjkLatinExtOnly);
  if (!beyond || !meta?.subsets?.includes('latin-ext')) return fontsourceProvider(family, weight, style);
  const weights = meta.weights?.length ? meta.weights : [400, 700];
  const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const s = style === 'italic' && !meta.styles.includes('italic') ? 'normal' : style;
  const id = fontsourceId(family);
  const url = `${await fontsourceAt(id)}files/${id}-latin-ext-${w}-${s}.woff2`;
  const [latin, ext] = await Promise.all([fontsourceProvider(family, weight, style), fetch(url)
    .then(async (res) => (res.ok ? decompressWoff2(new Uint8Array(await res.arrayBuffer())) : null), () => null)]);
  const ranges = kitRanges();
  return ext ? [Object.assign(latin, { unicodeRange: ranges.latin, order: 0 }),
    Object.assign(ext, { unicodeRange: ranges['latin-ext'], order: 1 })] : latin;
}

/** Whether code point `cp` is in Fontsource's latin-ext file and not in
 *  its latin file: Latin Extended-A and -B, IPA, the spacing modifiers and
 *  Latin Extended Additional (loadFonts's test for latin-ext), less the
 *  few latin holds too (ı Œ œ ʻ ʼ ˆ ˚ ˜). */
function cjkLatinExtOnly(cp) {
  if (!((cp >= 0x100 && cp <= 0x2ff) || (cp >= 0x1e00 && cp <= 0x1eff))) return false;
  return ![0x131, 0x152, 0x153, 0x2bb, 0x2bc, 0x2c6, 0x2da, 0x2dc].includes(cp);
}

/** showPages for a book bound on either edge. A right-bound book (the
 *  document says so: doc.binding is 'right' for page.binding 'right' and
 *  for vertical text) lies on the desk as it opens: page 1 alone on the
 *  left of the spine, then [3 | 2], the spine shade on each page's inner
 *  edge. `binding` ('left' | 'right') overrides the document's. */
function showBook(docs, { binding, ...options } = {}) {
  const count = showPages(docs, options);
  const right = (binding ?? [docs].flat()[0]?.binding) === 'right';
  if (!document.getElementById('pt-kit-cjk')) {
    // The pages keep direction ltr: a canvas draws text in the direction its
    // element inherits, and under rtl each run would end where the engine
    // starts it, its brackets mirrored.
    document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit-cjk">
      .pt-spread[dir="rtl"] canvas { direction: ltr; }
      .pt-spread[dir="rtl"] 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); }
    </style>`);
  }
  // Each pair stays [verso, recto] in the page; right to left, the verso
  // sits on the right. Phones stack the pages in reading order either way.
  for (const spread of document.querySelectorAll('#pages > .pt-spread')) spread.dir = right ? 'rtl' : 'ltr';
  document.getElementById('pages').dataset.binding = right ? 'right' : 'left';
  return count;
}

// ─── Kit · arabic v2 ── Arabic-script faces · postext.dev/cookbook
// Fontsource ships an Arabic family as one file per subset and weight: the
// `arabic` file holds the letters, the harakat, the Arabic-Indic digits, the
// Arabic punctuation and the presentation forms; `latin` and `latin-ext`
// hold the rest. loadFonts loads the latin files; this block adds the arabic
// file of every Arabic family, for the canvas and for the PDF, which shapes
// the letters with HarfBuzz from the same bytes.

/** The code points of Fontsource's `arabic` subset, as its stylesheets
 *  declare them (the same unicode-range the browser picks the file by). A
 *  function, not a const: the kit is inlined after the recipe's top-level
 *  awaits, and a const read before its line throws, where a function
 *  declaration is hoisted. */
function arabicRange() {
  return 'U+0600-06FF,U+0750-077F,U+0870-088E,U+0890-0891,U+0897-08E1,U+08E3-08FF,'
    + 'U+200C-200E,U+2010-2011,U+204F,U+2E41,U+FB50-FDFF,U+FE70-FE74,U+FE76-FEFC,U+102E0-102FB,'
    + 'U+10E60-10E7E,U+10EC2-10EC4,U+10EFC-10EFF,U+1EE00-1EEFF';
}

/** Whether code point `cp` is in the arabic file. */
function inArabicRange(cp) {
  inArabicRange.ranges ??= arabicRange().split(',').map((part) => {
    const [lo, hi = lo] = part.slice(2).split('-');
    return [parseInt(lo, 16), parseInt(hi, 16)];
  });
  return inArabicRange.ranges.some(([lo, hi]) => cp >= lo && cp <= hi);
}

/** Whether Fontsource serves `family` with an `arabic` subset. Fails when
 *  the API does not answer: an Arabic face taken for a Latin one would set
 *  its letters in a system face. */
async function isArabicFamily(family) {
  const meta = await fontsourceMeta(family);
  if (!meta) throw new Error(`api.fontsource.org did not describe ${family}: reload to try again`);
  return !!meta.subsets?.includes('arabic');
}

/** The arabic file of a face. */
async function arabicFileUrl(family, weight, style) {
  const id = fontsourceId(family);
  return `${await fontsourceAt(id)}files/${id}-arabic-${weight}-${style}.woff2`;
}

/** faces = { Amiri: ['400', '700'] }, as for loadFonts, after it: the whole
 *  FONTS object may be passed, its families without an arabic subset are
 *  left alone. Adds the arabic file of every listed weight of each Arabic
 *  family (the latin files come from loadFonts) and loads it. `text` is
 *  the sample: fails when it holds an Arabic-script character the arabic
 *  file does not cover. List every weight the pages set in Arabic: a weight
 *  left to the engine's later round gets the latin file only, and its Arabic letters
 *  fall back to a system face. Resolves to the number of files loaded. */
async function loadArabicFonts(faces, text = '') {
  kitStatus('Loading fonts…');
  let loaded = 0;
  try {
    const outside = [...new Set(text)].filter((ch) => /\p{Script=Arabic}/u.test(ch) && !inArabicRange(ch.codePointAt(0)));
    if (outside.length) throw new Error(`Fontsource's arabic files have no ${outside.slice(0, 12).join(' ')}`);
    for (const [family, specs] of Object.entries(faces)) {
      if (!(await isArabicFamily(family))) continue;
      for (const spec of new Set(specs)) {
        const weight = parseInt(spec, 10);
        const style = spec.endsWith('i') ? 'italic' : 'normal';
        const face = new FontFace(family, `url(${await arabicFileUrl(family, weight, style)}) format('woff2')`,
          { weight: String(weight), style, unicodeRange: arabicRange() });
        document.fonts.add(await face.load().catch(() => {
          throw new Error(`Fontsource has no arabic file for ${family} ${weight} ${style}`);
        }));
        loaded++;
      }
    }
  } catch (error) {
    kitFail(error);
    throw error;
  }
  return loaded;
}

/** The PDF font provider for recipes with Arabic faces: a family with an
 *  arabic subset gets its arabic file when its pages set Arabic letters
 *  (`request.codePoints`), then its latin file, and its latin-ext file for
 *  the letters beyond latin (transliteration: ā ḥ ʿ), each marked with its
 *  unicode-range and its place in the order the screen added them (latin
 *  and latin-ext by loadFonts, then arabic): the arabic file also has a
 *  space and brackets, which the browser takes from latin, the file whose
 *  range holds them, and postext-pdf follows it. Any other family goes to
 *  fontsourceProvider (the "pdf" block). */
async function arabicPdfProvider(family, weight, style, request) {
  if (!(await isArabicFamily(family))) return fontsourceProvider(family, weight, style, request);
  const meta = await fontsourceMeta(family);
  const weights = meta.weights?.length ? meta.weights : [400, 700];
  const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const s = style === 'italic' && !meta.styles.includes('italic') ? 'normal' : style;
  const wanted = [...(request?.codePoints ?? [])];
  const id = fontsourceId(family);
  const subsets = !wanted.length || wanted.some(inArabicRange) ? ['arabic', 'latin'] : ['latin'];
  if (meta.subsets.includes('latin-ext') && wanted.some((cp) => /[Ā-˿Ḁ-ỿ]/u.test(String.fromCodePoint(cp)))) {
    subsets.push('latin-ext');
  }
  const at = await fontsourceAt(id);
  return Promise.all(subsets.map(async (subset) => {
    const url = `${at}files/${id}-${subset}-${w}-${s}.woff2`;
    const res = await fetch(url);
    if (!res.ok) throw new Error(`Fontsource file ${url} (${res.status})`);
    const bytes = await decompressWoff2(new Uint8Array(await res.arrayBuffer()));
    return Object.assign(bytes, { unicodeRange: subset === 'arabic' ? arabicRange() : kitRanges()[subset],
      order: ['latin', 'latin-ext', 'greek', 'arabic'].indexOf(subset) });
  }));
}

// ─── /Kit ───────────────────────────────────────────────────────────────────────
```

## Παραλλαγές

### Χρησιμοποιήστε την αμερικανική καλλιγραφική γραφή

Η Playwrite έχει οικογένεια για πολλά σχολικά υποδείγματα. Για την αμερικανική καλλιγραφική γραφή, αλλάξτε την αγγλική γραμματοσειρά· οι στιγμές την ακολουθούν.

```diff
-  en: { hand: 'Playwrite GB J', ruling: 'gb', u: 3.6 },
+  en: { hand: 'Playwrite US Trad', ruling: 'gb', u: 3.6 },
```

### Γράψτε σε κάθε δεύτερη γραμμή Seyès

Τα παιδιά που ξεκινούν το σχολείο γράφουν συχνά σε κάθε δεύτερη έντονη γραμμή. Δώστε στις γαλλικές σειρές βήμα οκτώ γραμμών.

```diff
-    seyes: { above: 4, below: 2, gap: -2, seyes: true }, // a row on every heavy line
+    seyes: { above: 4, below: 2, gap: 2, seyes: true },
```

## Συνήθη λάθη

- Ένα κείμενο σχεδίασης κόβεται στο πλαίσιό του. Ένα πλαίσιο με ύψος μίας γραμμής κόβει τις κατιούσες του g και του p του υποδείγματος: δώστε του ψηλή γραμμή και τοποθετήστε το από τη γραμμή βάσης.
- Το `loadCjkFonts` φορτώνει κάθε γραμματοσειρά για ολόκληρο το δείγμα: μια κινεζική γραμματοσειρά που δεν έχει έναν χαρακτήρα που χρησιμοποιεί το κείμενο οπουδήποτε κάνει τη φόρτωση να αποτύχει. Σε ένα κολοφώνιο γράψτε τα ονόματα των γραμματοσειρών με λατινικά γράμματα.

## Ευχαριστίες

- Συνταγή: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Εικόνες: Two children writing in notebooks at a school table, a cat asleep on a chair beside them.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A smiling sun.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A crescent moon with three stars.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A ginger cat sitting.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A brown and white puppy.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: An orange fish with blue stripes.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A honey bee flying.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A little black spider on a thread.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A red apple.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A golden key.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A red child's shoe.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A small house with a red roof.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A small sailing boat.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A yellow duckling.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A colourful kite.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A birthday cake with three candles.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A penguin.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: An owl on a branch.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A red umbrella in the rain.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: An ice-cream cone with two scoops.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A blue and orange butterfly.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A leafy tree.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A snowy mountain.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A daisy.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A small blue bird on a twig.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: Splashing water.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A small campfire.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A child's hand holding a pencil with the tripod grip.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A golden star medal with coloured pencils.: Generated With Diffusion Models, πρωτότυπο
- Γραμματοσειρές: Andika (OFL-1.1), Lexend (OFL-1.1), Playwrite GB J (OFL-1.1), Playwrite ES (OFL-1.1), Playwrite FR Trad (OFL-1.1), Playwrite DE VA (OFL-1.1), Playwrite IT Trad (OFL-1.1), Playwrite BR (OFL-1.1), LXGW WenKai TC (OFL-1.1), Noto Serif SC (OFL-1.1), Noto Sans SC (OFL-1.1), Klee One (OFL-1.1), Zen Maru Gothic (OFL-1.1), Playpen Sans Arabic (OFL-1.1), Noto Naskh Arabic (OFL-1.1), Baloo Bhaijaan 2 (OFL-1.1)
- Κώδικας: MIT · Δείγμα περιεχομένου: CC-BY-4.0

## Σχετικές συνταγές

- [Αρ. 169 · Ένα φύλλο εργασίας σε δέκα σχολικές παραδόσεις](https://postext.dev/el/cookbook/school-traditions-worksheet.md): Τα ίδια επτά μπλοκ :::exercise σε δέκα γλώσσες, κάθε έκδοση με στιλ ασκήσεων ρυθμισμένο όπως τις στοιχειοθετούν τα σχολικά βιβλία της χώρας της. · Επίπεδο 2 (Μεσαίο) · Τετράδια και ασκήσεις, Σχολικά βιβλία
- [Αρ. 173 · Ένα αραβικό τετράδιο ασκήσεων, από τα δεξιά προς τα αριστερά](https://postext.dev/el/cookbook/arabic-workbook-rtl.md): Αραβικό τετράδιο δημοτικού από δεξιά προς τα αριστερά: επιλογές أ ب ج, αντιστοίχιση, τράπεζα λέξεων, κουτάκια صح ή خطأ, κρυπτόλεξο, ινδοαραβικά ψηφία. · Επίπεδο 2 (Μεσαίο) · Τετράδια και ασκήσεις, Σχολικά βιβλία
- [Αρ. 159 · Τετράδιο δραστηριοτήτων με πλαίσια που μεγαλώνουν](https://postext.dev/el/cookbook/activity-book-growing-boxes.md): Τετράδιο δραστηριοτήτων σε πρότυπα σελίδας: πλαίσια σε στοίβα μεγαλώνουν με το κείμενο, γραμμές απαντήσεων σε κενά πλαίσια, μια εργασία συνεχίζει πίσω. · Επίπεδο 3 (Προχωρημένο) · Τετράδια και ασκήσεις, Σχολικά βιβλία
