# Μια ενότητα παιδικού σχολικού βιβλίου σε δέκα γλώσσες

> Εννέα σελίδες της Γ΄ Δημοτικού σε δέκα γλώσσες, από δεξιά προς αριστερά στα αραβικά, κατακόρυφα στα κινεζικά και ιαπωνικά: χρωματιστά δισέλιδα, πλαίσια, χάρτης.

- Έκδοση HTML: https://postext.dev/el/cookbook/children-textbook-pages
- Συνταγή Αρ. 156 · Σχολικά βιβλία · Επίπεδο 3 (Προχωρημένο) · Έξοδοι: 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/children-textbook-pages/en/p01.webp?v=79b1742d), [2](https://postext.dev/cookbook/children-textbook-pages/en/p02.webp?v=79b1742d), [3](https://postext.dev/cookbook/children-textbook-pages/en/p03.webp?v=79b1742d), [4](https://postext.dev/cookbook/children-textbook-pages/en/p04.webp?v=79b1742d), [5](https://postext.dev/cookbook/children-textbook-pages/en/p05.webp?v=79b1742d), [6](https://postext.dev/cookbook/children-textbook-pages/en/p06.webp?v=79b1742d), [7](https://postext.dev/cookbook/children-textbook-pages/en/p07.webp?v=79b1742d), [8](https://postext.dev/cookbook/children-textbook-pages/en/p08.webp?v=79b1742d), [9](https://postext.dev/cookbook/children-textbook-pages/en/p09.webp?v=79b1742d)
- PDF: https://postext.dev/cookbook/children-textbook-pages/en/children-textbook-pages.pdf?v=79b1742d
- Άνοιγμα στο Sandbox: https://postext.dev/el/sandbox#recipe=children-textbook-pages&lang=en (.postext: https://postext.dev/cookbook/children-textbook-pages/en/children-textbook-pages.postext)
- Τελευταία ενημέρωση: 2026-10-31
- Άλλες γλώσσες: [en](https://postext.dev/en/cookbook/children-textbook-pages.md), [es](https://postext.dev/es/cookbook/children-textbook-pages.md), [ca](https://postext.dev/ca/cookbook/children-textbook-pages.md), [de](https://postext.dev/de/cookbook/children-textbook-pages.md), [fr](https://postext.dev/fr/cookbook/children-textbook-pages.md), [it](https://postext.dev/it/cookbook/children-textbook-pages.md), [pt](https://postext.dev/pt/cookbook/children-textbook-pages.md), [zh](https://postext.dev/zh/cookbook/children-textbook-pages.md), [ja](https://postext.dev/ja/cookbook/children-textbook-pages.md), [ar](https://postext.dev/ar/cookbook/children-textbook-pages.md)

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

Μια ενότητα σχολικού βιβλίου για ένα ποτάμι, εννέα σελίδες. Κάθε θέμα είναι δισέλιδο σε χρωματιστό φόντο, με καρτέλα τίτλου, κείμενο, εικόνες και πλαίσια. Ο χάρτης δεν έχει καμία ζωγραφισμένη λέξη: τα ονόματα έρχονται από το κείμενο.

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

Εννέα σελίδες της ενότητας *Our river*, της ενότητας 4 ενός επινοημένου βιβλίου κοινωνικών επιστημών της Γ΄ Δημοτικού, σε σελίδα 210 × 280 mm, σε δέκα γλώσσες: ισπανικά, καταλανικά, αγγλικά, πορτογαλικά, γαλλικά, γερμανικά, ιταλικά, αραβικά, κινεζικά και ιαπωνικά. Μια ζωγραφισμένη κοιλάδα ανοίγει την ενότητα, μια σελίδα περιεχομένων απαριθμεί δύο μέρη, και ακολουθούν τρία θέματα σε δισέλιδα, το καθένα στο δικό του φόντο: μπλε του νερού, πράσινο του χωραφιού, άμμος του ήλιου. Κάθε θέμα έχει μια καρτέλα με τον αριθμό και τον τίτλο του, κείμενο σε δύο στήλες και πλαίσια με καρτέλες που μεγαλώνουν με το κείμενό τους. Το δεύτερο θέμα είναι ένας ζωγραφισμένος χάρτης απλωμένος και στις δύο σελίδες, με το ποτάμι, τα χωριά και τις τρεις διαδρομές ονομασμένα πάνω του από το Markdown, και μια γραμμή από κάθε πλαίσιο διαδρομής ως το τμήμα του ποταμού. Ό,τι επαναλαμβάνεται σχεδιάζεται μία φορά: το πρότυπο απλώνει μία κάρτα εικόνας, ένα πλαίσιο διαδρομής και ένα πλαίσιο με εικόνα όσες φορές ζητά το Markdown, και οι τρεις ερωτήσεις πριν από την ενότητα είναι τρεις χρήσεις μίας μονάδας. Τα κείμενα διαφέρουν σε μήκος κατά ένα πέμπτο ή περισσότερο και βρίσκουν τη θέση τους στα ίδια πρότυπα: ένα πλαίσιο παίρνει το ύψος που χρειάζονται οι λέξεις του και σπρώχνει το επόμενο προς τα κάτω, και ο χάρτης μικραίνει λίγο πριν μικρύνει οποιοδήποτε κείμενο. Το αραβικό βιβλίο τρέχει από δεξιά προς τα αριστερά και το κινεζικό και το ιαπωνικό τρέχουν προς τα κάτω στη σελίδα· και τα τρία δένονται δεξιά και διαβάζονται από τη δεξιά σελίδα κάθε δισέλιδου προς την αριστερή.

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

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

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

```js
// script.js, γραμμές 90–122
// Ground, tab and number are decoration anchored to the title frame; the number,
// `{headingNumber}`, stands over the padding before its words. A topic extends the base.
const ground = () => ({ kind: 'box', id: 'ground',
  placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: 'fill' } },
  style: { backgroundColor: col('tema-ground') } });
const titleTab = () => ({ kind: 'box', id: 'tab', placement: { ...at('#titulo',
  'top-left'), size: { width: { to: '#titulo', edge: 'right' }, height: { to: '#titulo',
    edge: 'bottom' } } }, style: { backgroundColor: col('tema'), borderRadius: mm(4) } });
const badge = () => ({ kind: 'text', id: 'number', content: '{headingNumber}',
  fontFamily: DISPLAY, fontSize: pt(22), fontWeight: fw(700), color: col('tema'), align: 'center',
  box: { backgroundColor: col('paper'), borderRadius: mm(6) }, placement: { ...at('#titulo',
    corner('top'), inward(CJK ? 2.6 : 5), CJK ? 5 : 2.4), size: { width: mm(12), height: mm(12) } },
});
const title = { name: 'titulo', takes: 'h1', style: 'titulo', width: mm(MEASURE),
  placement: at('container', 'top-left') };

const base = {
  id: 'tema', spread: true, gutter: mm(12),
  decoration: { elements: [ground(), titleTab(), badge()] },
  frames: [title, { name: 'texto', flow: true, columns: 2, columnGap: mm(CJK ? 16 : 7), // 段
    width: mm(MEASURE), fit: { minScale: 0.9 } }],
  groups: [{ name: 'izquierda', kind: 'stack', gap: mm(6), frames: ['titulo', 'texto'] }],
};
const topic = (id, f, more) => ({ id, extends: 'tema', palette: swap(f), ...more });
const box = (name, style, minHeight, more) => ({ name, style, width: mm(MEASURE),
  minHeight: mm(minHeight), ...more });
const answer = (name, lines) => ({ name, optional: true, style: 'respuesta', width: mm(MEASURE),
  height: mm(LINE * lines), minHeight: mm(LINE * lines),
  rules: { every: mm(LINE), color: col('rule'), width: pt(0.75) } });
const PIC = CJK ? 30 : 56; // a picture at the end of a box's first lines pushes the text aside
const withPic = (name, style, minHeight, more) => [box(name, style, minHeight,
  { padding: { right: mm(PIC + 8) }, ...more }), { name: `${name}-foto`, layer: 2, width: mm(PIC),
  exclude: 'push', placement: at(`#${name}`, 'top-right', -5, 8) }];
```

## Υλικά

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

- [Στοιχειοθετημένες σελίδες](https://postext.dev/el/docs/composed-pages.md#στοιχειοθετημένες-σελίδες): Μια σελίδα που σελιδοποιείται από ένα πρότυπο με ονομασμένα πλαίσια κειμένου στις ρυθμίσεις και γεμίζει από ένα μπλοκ ::::page, του οποίου το περιεχόμενο ονομάζει κάθε πλαίσιο κειμένου με τη θέση του.
- [Πλέγματα που επαναλαμβάνουν ένα σύνολο πλαισίων](https://postext.dev/el/docs/configuration-composed-pages.md#πλέγματα-που-επαναλαμβάνουν-ένα-σύνολο-πλαισίων): Μια ομάδα grid δηλώνει μία φορά ένα σύνολο πλαισίων κειμένου, μια κάρτα και τη λεζάντα της, και το ξανατοποθετεί για κάθε στοιχείο που της δίνει το Markdown της σελίδας, σε σειρές από ίσες στήλες, ονομάζοντας τα αντίγραφα #card[1], #card[2]…
- [Μονάδες στοιβαγμένες σε μια σελίδα](https://postext.dev/el/docs/configuration-composed-pages.md#μονάδες): Μια μονάδα (module) είναι ένα πρότυπο με λίγα πλαίσια κειμένου, ομάδες και διακόσμηση, φτιαγμένο για επαναχρησιμοποίηση· η ομάδα modules ενός προτύπου σελίδας παίρνει τα μπλοκ :::module της σελίδας με τη σειρά του Markdown και τα στοιβάζει το ένα κάτω από το άλλο.

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

- [Γραμμές οδηγοί και υπομνήματα σε εικόνες](https://postext.dev/el/docs/composed-pages-figures.md#γραμμές-οδηγοί-υπομνήματα-και-σύμβολα)
- [Πλαίσια κειμένου που μεγαλώνουν σε ομάδα](https://postext.dev/el/docs/composed-pages.md#όταν-το-κείμενο-μεγαλώνει)
- [Αριθμημένες καρτέλες πλαισίων](https://postext.dev/el/docs/configuration-callouts.md#στιλ-πλαισίων)
- [Ετικέτες πάνω σε εικόνα](https://postext.dev/el/docs/composed-pages-figures.md#εικόνες-με-ετικέτες)
- [Πίνακας περιεχομένων](https://postext.dev/el/docs/configuration-notes-references.md#πίνακας-περιεχομένων)
- [Πρότυπα δισέλιδων](https://postext.dev/el/docs/composed-pages.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/configuration-headers-footers.md#τοποθέτηση-στοιχείων)
- [Διακόσμηση αγκυρωμένη σε πλαίσια κειμένου](https://postext.dev/el/docs/composed-pages.md#διακόσμηση-τρέχουσες-κεφαλίδες-και-επίπεδα)
- [Συμμετρικά περιθώρια](https://postext.dev/el/docs/configuration-page-layout.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/document-format-resources.md#πόροι)
- [Πλαίσια κειμένου που σπρώχνουν το κείμενο, με το ορθογώνιο ή το περίγραμμά τους](https://postext.dev/el/docs/composed-pages.md#πλαίσια-που-απωθούν-το-κείμενο)
- [Ιδιότητες επικεφαλίδων](https://postext.dev/el/docs/document-format.md#χαρακτηριστικά-επικεφαλίδων)
- [Διαχωριστικές σελίδες μερών](https://postext.dev/el/docs/configuration-styles.md#ο-περιέκτης-part)
- [Εξαγωγή PDF](https://postext.dev/el/docs/configuration-pdf-output.md#παραγωγή-pdf)
- [Γραμματοσειρές ενσωματωμένες στο PDF](https://postext.dev/el/docs/configuration-pdf-output.md#γιατί-πάροχος-γραμματοσειρών)
- [Προσαρμοσμένοι τύποι πόρων](https://postext.dev/el/docs/configuration-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#στιλ-πλαισίων), [`canvasViewer`](https://postext.dev/el/docs/configuration-fonts-colors-viewers.md#προβολή-καμβά), [`captionStyle`](https://postext.dev/el/docs/configuration-resources.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#επικεφαλίδες), [`labelStyles`](https://postext.dev/el/docs/configuration-composed-pages.md#στιλ-ετικετών), [`layout`](https://postext.dev/el/docs/configuration-page-layout.md#διάταξη), [`locale`](https://postext.dev/el/docs/configuration-language.md#συλλαβισμός), [`orderedLists`](https://postext.dev/el/docs/configuration-lists-math.md#αριθμημένες-λίστες), [`page`](https://postext.dev/el/docs/configuration-page-layout.md#σελίδα), [`pageTemplates`](https://postext.dev/el/docs/configuration-composed-pages.md#πρότυπα-σελίδας), [`parts`](https://postext.dev/el/docs/configuration-styles.md#μέρη), [`resourceTypes`](https://postext.dev/el/docs/configuration-resources.md#τύποι-πόρων), [`toc`](https://postext.dev/el/docs/configuration-notes-references.md#πίνακας-περιεχομένων), [`unorderedLists`](https://postext.dev/el/docs/configuration-lists-math.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), `loadVerticalAlternates`, [`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#φόρτωση-γραμματοσειρών-πριν-από-τη-σελιδοποίηση)

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

- Nunito (OFL-1.1), Fredoka (OFL-1.1), Noto Naskh Arabic (OFL-1.1), Baloo Bhaijaan 2 (OFL-1.1), Klee One (OFL-1.1), Zen Maru Gothic (OFL-1.1), Noto Serif SC (OFL-1.1), ZCOOL KuaiLe (OFL-1.1)

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

### 1 · Μάθετε από ποια πλευρά ξεκινά κάθε γλώσσα

```js
// script.js, γραμμές 33–44
// Arabic runs right to left, Chinese and Japanese down the page, all bound on the right. Frames
// stand in the flow (x along the lines, mirrored in Arabic, down the page when vertical).
const AR = LANG === 'ar', CJK = LANG === 'zh' || LANG === 'ja';
const RIGHT_BOUND = AR || CJK, LATIN = !RIGHT_BOUND; // italics, capitals, tracking, hyphens
const [TEXT, DISPLAY] = { ar: ['Noto Naskh Arabic', 'Baloo Bhaijaan 2'], ja: ['Klee One',
  'Zen Maru Gothic'], zh: ['Noto Serif SC', 'ZCOOL KuaiLe'] }[LANG] ?? ['Nunito', 'Fredoka'];
const START = RIGHT_BOUND ? 'right' : 'left'; // the side a page starts reading from
const corner = (v) => `${v}-${START}`, inward = (x) => (RIGHT_BOUND ? -x : x);
const [SLANT, CAPS] = LATIN ? ['italic', 'uppercase'] : ['normal', 'none'];
const LEAD = AR ? 20 : CJK ? 21 : 17.5, track = (v) => (LATIN ? v : 0); // Naskh, ruby need room
const fw = (w) => ({ 'ZCOOL KuaiLe': 400, 'Zen Maru Gothic': w > 550 ? 700 : 500 })[DISPLAY] ?? w;
const BOLD = TEXT === 'Klee One' ? 600 : 700; // and the weights the faces have
```

Τα πλαίσια κειμένου ενός προτύπου στέκονται στο πλαίσιο ροής της σελίδας, όπου το x τρέχει κατά μήκος των γραμμών. Με `locale: 'ar'` η μηχανή κατοπτρίζει αυτό το πλαίσιο, οπότε το αραβικό βιβλίο χρησιμοποιεί τα λατινικά πλαίσια κειμένου χωρίς αλλαγές: ο τίτλος έρχεται πρώτος στη δεξιά σελίδα, οι τρεις φωτογραφίες και τα τρία πλαίσια διαδρομής τρέχουν από δεξιά προς τα αριστερά, και οι καρτέλες, οι λωρίδες και τα εσωτερικά περιθώρια των πλαισίων ακολουθούν τις γραμμές. Με `layout.writingMode: 'vertical-rl'` το x τρέχει προς τα κάτω στη σελίδα και το y από δεξιά προς τα αριστερά: το `width` ενός πλαισίου κειμένου είναι μήκος προς τα κάτω στη σελίδα, μια στοίβα κινείται προς τα αριστερά, το `columns: 2` δίνει δύο ζώνες (段) των 27 χαρακτήρων, και ένα πλαίσιο κειμένου τοποθετημένο `below` ένα άλλο στέκεται στα αριστερά του. Η διακόσμηση (τα φόντα, η καρτέλα τίτλου, ο αριθμός, οι τρέχουσες κεφαλίδες και οι αριθμοί σελίδας) στέκεται πάνω στο ίδιο το φύλλο, γι' αυτό τοποθετείται από το `START`, την πλευρά από την οποία ξεκινά η ανάγνωση μιας σελίδας. Κάθε γραφή έχει μια γραμματοσειρά κειμένου και μια στρογγυλή γραμματοσειρά τίτλων, και η αραβική, η κινεζική και η ιαπωνική έκδοση δεν έχουν πλάγια, κεφαλαία ή αραίωση χαρακτήρων.

### 2 · Χτίστε τα πλαίσια με `extends`

```js
// script.js, γραμμές 59–86
// Two steps of `extends`: the box (shape, type, tab), then the kind. The colours are `tema`
// entries, so one style serves the three topics; paddings, stripes and tabs are in the flow.
const tab = (f) => ({ position: 'top-left', background: col(f), color: col('paper'),
  fontFamily: DISPLAY, fontSize: pt(12), fontWeight: fw(600), height: mm(7), paddingX: mm(3.2),
  offset: mm(7), inset: mm(5), rule: { enabled: false, color: col(f) } });
const boxText = { fontFamily: TEXT, fontSize: pt(12), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), boldFontWeight: BOLD, firstLineIndent: pt(0),
  textAlign: CJK ? 'justify' : 'left', paragraphSpacing: true };
const calloutStyles = [
  { id: 'caja', backgroundEnabled: true, background: col('paper'), borderRadius: mm(3),
    border: { enabled: false }, padding: { top: mm(3.4), right: mm(5), bottom: mm(4), left: mm(5) },
    body: boxText, lists: { color: col('ink'), gap: mm(2), itemSpacing: mm(1.6) } },
  { id: 'caja-tema', extends: 'caja', label: tab('tema'), lists: { color: col('tema') } },
  { id: 'dato', extends: 'caja-tema', background: col('tema-tint') },
  { id: 'palabras', extends: 'caja-tema', border: { enabled: true, color: col('tema'),
    width: pt(1.4) } }, { id: 'actividad', extends: 'caja-tema',
    stripe: { enabled: true, side: 'left', width: pt(4), color: col('tema') } },
  { id: 'titulo', extends: 'caja', backgroundEnabled: false,
    padding: { top: mm(2.6), right: mm(6), bottom: mm(3.2), left: mm(TAB) } },
  { id: 'titulo-plano', extends: 'titulo', padding: { left: mm(8) } },
  { id: 'portada', extends: 'caja', background: col('agua'), borderRadius: mm(4),
    padding: { top: mm(2.6), right: mm(8), bottom: mm(3.6), left: mm(8) } },
  { id: 'foto', extends: 'caja', borderRadius: mm(2),
    padding: { top: mm(1.8), right: mm(1.8), bottom: mm(2.2), left: mm(1.8) } },
  { id: 'respuesta', extends: 'caja', padding: NONE }, { id: 'colofon', extends: 'caja',
    backgroundEnabled: false, padding: NONE,
    body: { ...boxText, fontSize: pt(8), lineHeight: pt(AR ? 13 : 11), color: col('muted') } },
];
```

Ένα στιλ πλαισίου φτιάχνεται σε τρία βήματα. Το `caja` κρατά το σχήμα, τα γράμματα και τη γεωμετρία της καρτέλας· το `caja-tema` βάζει το χρώμα του θέματος στην καρτέλα και στις κουκκίδες· τα `dato`, `palabras` και `actividad` ορίζουν το είδος: ένα χρωματισμένο πλαίσιο, ένα με περίγραμμα ή ένα με λωρίδα. Τα χρώματά τους είναι καταχωρίσεις της παλέτας (`tema`, `tema-tint`), οπότε κάθε στιλ γράφεται μία φορά και το πρότυπο ενός θέματος το χρωματίζει.

### 3 · Αφήστε κάθε θέμα να επεκτείνει ένα πρότυπο βάσης

```js
// script.js, γραμμές 90–122
// Ground, tab and number are decoration anchored to the title frame; the number,
// `{headingNumber}`, stands over the padding before its words. A topic extends the base.
const ground = () => ({ kind: 'box', id: 'ground',
  placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: 'fill' } },
  style: { backgroundColor: col('tema-ground') } });
const titleTab = () => ({ kind: 'box', id: 'tab', placement: { ...at('#titulo',
  'top-left'), size: { width: { to: '#titulo', edge: 'right' }, height: { to: '#titulo',
    edge: 'bottom' } } }, style: { backgroundColor: col('tema'), borderRadius: mm(4) } });
const badge = () => ({ kind: 'text', id: 'number', content: '{headingNumber}',
  fontFamily: DISPLAY, fontSize: pt(22), fontWeight: fw(700), color: col('tema'), align: 'center',
  box: { backgroundColor: col('paper'), borderRadius: mm(6) }, placement: { ...at('#titulo',
    corner('top'), inward(CJK ? 2.6 : 5), CJK ? 5 : 2.4), size: { width: mm(12), height: mm(12) } },
});
const title = { name: 'titulo', takes: 'h1', style: 'titulo', width: mm(MEASURE),
  placement: at('container', 'top-left') };

const base = {
  id: 'tema', spread: true, gutter: mm(12),
  decoration: { elements: [ground(), titleTab(), badge()] },
  frames: [title, { name: 'texto', flow: true, columns: 2, columnGap: mm(CJK ? 16 : 7), // 段
    width: mm(MEASURE), fit: { minScale: 0.9 } }],
  groups: [{ name: 'izquierda', kind: 'stack', gap: mm(6), frames: ['titulo', 'texto'] }],
};
const topic = (id, f, more) => ({ id, extends: 'tema', palette: swap(f), ...more });
const box = (name, style, minHeight, more) => ({ name, style, width: mm(MEASURE),
  minHeight: mm(minHeight), ...more });
const answer = (name, lines) => ({ name, optional: true, style: 'respuesta', width: mm(MEASURE),
  height: mm(LINE * lines), minHeight: mm(LINE * lines),
  rules: { every: mm(LINE), color: col('rule'), width: pt(0.75) } });
const PIC = CJK ? 30 : 56; // a picture at the end of a box's first lines pushes the text aside
const withPic = (name, style, minHeight, more) => [box(name, style, minHeight,
  { padding: { right: mm(PIC + 8) }, ...more }), { name: `${name}-foto`, layer: 2, width: mm(PIC),
  exclude: 'push', placement: at(`#${name}`, 'top-right', -5, 8) }];
```

Η βάση είναι ένα δισέλιδο: ένα φόντο ως το περιθώριο αιμορραγίας, μια καρτέλα τίτλου με τον αριθμό της και ένα κείμενο σε δύο στήλες. Ένα θέμα την επεκτείνει (`extends: 'tema'`), ορίζει την `palette` του (οι τρεις καταχωρίσεις `tema` παίρνουν τα χρώματα της οικογένειας, και το φόντο, η καρτέλα, ο αριθμός και κάθε πλαίσιο αλλάζουν μαζί) και προσθέτει τα δικά του πλαίσια κειμένου. Η καρτέλα και ο αριθμός είναι διακόσμηση αγκυρωμένη στο πλαίσιο του τίτλου, οπότε η καρτέλα έχει το ύψος του τίτλου που χρειάζεται η γλώσσα. Ο αριθμός είναι το `{headingNumber}`, ο μετρητής της επικεφαλίδας που πήρε το πλαίσιο, ζωγραφισμένος πάνω στο εσωτερικό περιθώριο του πλαισίου πριν από τις λέξεις του: κανένα μπλοκ σελίδας δεν τον επαναλαμβάνει, και ένα κλικ πάνω του φτάνει στον αριθμό, όχι στο πλαίσιο.

### 4 · Σχεδιάστε μία φορά ό,τι επαναλαμβάνεται

```js
// script.js, γραμμές 126–131
const grid = (name, frames, columns, placement, more, width = MEASURE) => ({ name, kind: 'grid',
  columns, columnGap: mm(5), rowGap: mm(CJK ? 8 : 12), repeat: { frames },
  placement: { ...placement, size: { width: mm(width), height: 'fill' } }, ...more });
const question = { id: 'pregunta', role: 'module', // a question and the lines to answer it on
  frames: [box('caja', 'dato', CJK ? 22 : 14, { width: 'fill' }), { ...answer('lineas',
    CJK ? 2 : 3), width: 'fill', placement: at('#caja', 'below', 0, CJK ? 4 : 7) }] };
```

Μια ομάδα πλέγματος επαναλαμβάνει ένα σύνολο πλαισίων κειμένου μία φορά για κάθε στοιχείο της σελίδας. Η λωρίδα των εικόνων είναι το `grid('fotos', ['foto'], 3, …)`: τρία μπλοκ `:::figure{slot="foto"}` δίνουν τρεις κάρτες, με τα ονόματα `#foto[1]` έως `#foto[3]`, και το πλαίσιο *Try it* κρέμεται κάτω από το `#foto[1]`. Τα πλαίσια του θέματος του ήλιου είναι ένα πλέγμα μίας στήλης του οποίου το σύνολο είναι ένα πλαίσιο και η εικόνα του (`['uso', 'uso-foto']`): κάθε `:::frame{slot="uso"}` κρατά τις λέξεις του και, μέσα του, το `:::figure{slot="uso-foto"}` που πάει μαζί τους. Η σελίδα των ερωτήσεων στοιβάζει μια μονάδα: το `pregunta` είναι ένα πρότυπο με `role: 'module'`, ένα χρωματισμένο πλαίσιο και οι γραμμές για την απάντηση, και η ομάδα `preguntas` της σελίδας (`modules: true`) απλώνει μία για κάθε `:::module{template="pregunta"}` του Markdown. Ένα πλαίσιο κειμένου έχει το ύψος των λέξεών του, ποτέ λιγότερο από το `minHeight` του, οπότε ένα μακρύτερο ισπανικό κείμενο σπρώχνει προς τα κάτω τις σειρές κάτω από αυτό, και όταν μια σελίδα δεν φτάνει η [κλίμακα αναδιάταξης](https://postext.dev/el/docs/composed-pages.md#όταν-εξακολουθεί-να-μη-χωρά) μικραίνει τον χάρτη και τις εικόνες πριν από το κείμενο, ως το 90%.

Τα πλαίσια διαδρομής είναι ένα πλέγμα τριών κάτω από τον χάρτη (`grid('cursos', ['curso'], 3, …)`), ένα πλαίσιο για κάθε `:::frame{slot="curso"}`. Ο χάρτης ονομάζει τα ίδια τρία τμήματα με ονόματα στο στιλ `curso`, πάνω στο πράσινο των καρτελών των πλαισίων, ώστε ο αναγνώστης να βρίσκει το τμήμα κάθε πλαισίου από το όνομα και το χρώμα του. Σε κατακόρυφη σελίδα οι διαδρομές στέκονται σε μία στήλη δίπλα στον χάρτη.

### 5 · Βάλτε τα ονόματα στον χάρτη από το κείμενο

```js
// script.js, γραμμές 250–290
// An anchor is a point of the painting (fractions of its width and height) and a label style;
// every language's ::label lines use the same anchors. A right-bound book shows the painting
// mirrored, the mountains on the right, so the river runs the way its pages are read: x comes
// from the other edge and a turn goes the other way. `start` is a label's own start, so the
// spring's label keeps it in Arabic and takes `end` in a label set left to right.
const halo = { color: col('paper'), width: pt(1.8) };
const labelStyles = [
  { id: 'sierra', fontFamily: DISPLAY, fontSize: pt(13), fontWeight: fw(600), color: col('ink'),
    textTransform: CAPS, letterSpacing: track(0.14), halo },
  { id: 'agua', fontFamily: TEXT, fontSize: pt(11), fontWeight: BOLD, fontStyle: SLANT,
    color: { hex: '#0b3a5c', model: 'hex' }, halo, // a name set away draws a leader to its point
    leader: { width: pt(1), endCap: 'dot', capSize: mm(1.6) } },
  { id: 'mar', fontFamily: TEXT, fontSize: pt(12), fontWeight: BOLD, fontStyle: SLANT,
    color: col('paper'), halo: { color: { hex: '#0b3a5c', model: 'hex' }, width: pt(1.8) } },
  { id: 'pueblo', fontFamily: DISPLAY, fontSize: pt(12), fontWeight: fw(600), color: col('ink'),
    halo },
  { id: 'curso', fontFamily: DISPLAY, fontSize: pt(10.5), fontWeight: fw(600), color: col('paper'),
    textTransform: CAPS, letterSpacing: track(0.08), background: col('campo'),
    padding: mm(1.6) },
];
const ANCHORS = [
  { id: 'sierra', x: 0.21, y: 0.055, style: 'sierra' },
  // The spring and the dam: the point is the place, `labelAt` where its name stands.
  { id: 'nacimiento', x: 0.049, y: 0.098, labelAt: { x: 0.075, y: 0.115 }, style: 'agua',
    align: 'start' },
  { id: 'fontalba', x: 0.135, y: 0.255, style: 'pueblo', verticalAlign: 'top' },
  { id: 'embalse', x: 0.293, y: 0.275, labelAt: { x: 0.31, y: 0.155 }, style: 'agua',
    width: 0.12 },
  { id: 'molinar', x: 0.505, y: 0.35, style: 'pueblo', verticalAlign: 'bottom' },
  { id: 'aldamar', x: 0.845, y: 0.505, style: 'pueblo', verticalAlign: 'bottom' },
  { id: 'mar', x: 0.965, y: 0.28, style: 'mar' },
  { id: 'rio', x: 0.61, y: 0.715, style: 'agua', rotate: -3 },
  { id: 'alto', x: 0.17, y: 0.45, style: 'curso' },
  { id: 'medio', x: 0.4, y: 0.77, style: 'curso' },
  { id: 'bajo', x: 0.74, y: 0.865, style: 'curso' },
];
const flip = (x) => Math.round((1 - x) * 1000) / 1000;
const flipped = (a) => ({ ...a, x: flip(a.x), ...(a.labelAt && { labelAt: { ...a.labelAt,
    x: flip(a.labelAt.x) } }),
  ...(a.rotate && { rotate: -a.rotate }), ...(a.align && !AR && { align: 'end' }) });
const anchors = RIGHT_BOUND ? ANCHORS.map(flipped) : ANCHORS;
```

Ο χάρτης είναι μια ζωγραφιά χωρίς ούτε ένα γράμμα. Κάθε τόπος είναι ένα σημείο αγκύρωσης της εικόνας, ένα σημείο σε κλάσματα του πλάτους και του ύψους της με ένα στιλ ονόματος, και κάθε έκδοση γράφει τις δικές της γραμμές `::label` σε αυτά τα σημεία. Τα *Penalta Reservoir*, *Pantà de Penyalta* και *Embalse de Peñalta* στέκονται στο ίδιο σημείο, και ένα μακρύτερο όνομα σπάει μέσα στο `width` του σημείου αγκύρωσης. Ένα βιβλίο δεμένο δεξιά δείχνει την ίδια ζωγραφιά κατοπτρισμένη (`mapa-1900-rtl.jpg`), ώστε το ποτάμι να τρέχει από τα βουνά στα δεξιά ως τη θάλασσα στα αριστερά, όπως διαβάζονται οι σελίδες του· το `flipped` πηγαίνει κάθε σημείο αγκύρωσης, και το σημείο όπου μπαίνει το όνομά του, στην άλλη πλευρά και γυρίζει μια περιστροφή ανάποδα. Τα *Spring* και *Penalta Reservoir* τοποθετούνται μακριά από τους τόπους τους με `labelAt`, και η `leader` του στιλ `agua` σχεδιάζει μια γραμμή με κουκκίδα από το όνομα ως την πηγή και ως το φράγμα.

### 6 · Κρατήστε κάθε μέρος των περιεχομένων μαζί

```js
// script.js, γραμμές 227–246
const partAt = (x) => (CJK ? at('container', 'left', x) : at('container', START, inward(x)));
const toc = {
  levels: [{ level: 1, fontFamily: DISPLAY, fontSize: pt(15), lineHeight: pt(22),
    fontWeight: fw(500), color: col('ink'), numberFontWeight: fw(600), numberColor: col('agua'),
    numberWidth: mm(9), marginTop: pt(4) }, { level: 2, fontFamily: TEXT, fontSize: pt(11.5),
    lineHeight: pt(18), indent: mm(9), color: col('ink') }],
  pageNumber: { fontFamily: DISPLAY, fontWeight: fw(500), width: mm(9), color: col('agua') },
  leader: { char: CJK ? '…' : '.', gap: mm(1.5) },
  parts: { height: pt(34), marginTop: pt(12), marginBottom: pt(4), design: { elements: [
    { kind: 'box', id: 'band',
      placement: { ...at('container', 'top-left'), size: { width: 'fill', height: 'fill' } },
      style: { backgroundColor: col('paper'), borderRadius: mm(3) } },
    { kind: 'text', id: 'letter', content: '{number}', fontFamily: DISPLAY, fontSize: pt(16),
      fontWeight: fw(700), color: col('paper'), align: 'center',
      box: { backgroundColor: col('agua'), borderRadius: mm(4) },
      placement: { ...partAt(2), size: { width: mm(8), height: mm(8) } } },
    { kind: 'text', id: 'name', content: '{titleText}', fontFamily: DISPLAY, fontSize: pt(13),
      fontWeight: fw(600), color: col('agua'), align: START, placement: partAt(14) },
  ] } },
};
```

Το `:::toc{keep="part" levels="1-2"}` απαριθμεί τα θέματα και τις ενότητές τους και κρατά κάθε σειρά μέρους με τις καταχωρίσεις της. Ένα μπλοκ `:::part` με `parts.page: false` είναι μόνο μια σειρά των περιεχομένων και μια ενότητα για τις τρέχουσες κεφαλίδες: δεν προσθέτει διαχωριστική σελίδα. Τα περιεχόμενα είναι μια στοιχειοθετημένη σελίδα: το πρότυπό της έχει ένα πλαίσιο κειμένου με `takes: "toc"` που δέχεται το `:::toc` και το απλώνει με τους κανόνες των ίδιων των περιεχομένων, ώστε οι σειρές μερών, οι στιγμές οδηγοί και το `keep` να λειτουργούν όπως στο κυρίως κείμενο, και το ανοιχτόχρωμο φόντο είναι η διακόσμηση του προτύπου.

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

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

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

### script.js

```js
// ═══ Postext Cookbook · Nº 156 · A children's textbook unit in ten languages ═════
// https://postext.dev/en/cookbook/children-textbook-pages
// Code: MIT · Text: original (CC BY 4.0) · Pictures: generated with diffusion models
// Fonts: Nunito, Fredoka and three pairs for Arabic, Chinese, Japanese · Needs postext ≥ 1.65.0
import {
  buildDocument, withLoadedFonts, renderPageToCanvas, registerResourceImage,
  loadVerticalAlternates,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

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

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// One ink and three families (accent, box tint, page ground); a topic swaps the `tema` entries.
const FAMILIES = {
  agua: { main: '#1b6aa0', tint: '#e1f0fa', ground: '#d3e8f6' },
  campo: { main: '#336f27', tint: '#e5f1dc', ground: '#d9ebcb' },
  sol: { main: '#9a5209', tint: '#fcefd2', ground: '#f8e6b8' },
};
const palette = { ink: '#1d2f3f', muted: '#4f6272', rule: '#7e98ab', paper: '#ffffff',
  agua: FAMILIES.agua.main, campo: FAMILIES.campo.main, // the blue of the folios and the contents
  tema: FAMILIES.agua.main, 'tema-tint': FAMILIES.agua.tint, 'tema-ground': FAMILIES.agua.ground };
const swap = (f) => `tema=${FAMILIES[f].main}, tema-tint=${FAMILIES[f].tint}, `
  + `tema-ground=${FAMILIES[f].ground}`;
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: 'water (defaults)', value: { hex: palette.agua, model: 'hex' } },
];

// #region editions: how each language runs and is bound, and the two faces of its script
// Arabic runs right to left, Chinese and Japanese down the page, all bound on the right. Frames
// stand in the flow (x along the lines, mirrored in Arabic, down the page when vertical).
const AR = LANG === 'ar', CJK = LANG === 'zh' || LANG === 'ja';
const RIGHT_BOUND = AR || CJK, LATIN = !RIGHT_BOUND; // italics, capitals, tracking, hyphens
const [TEXT, DISPLAY] = { ar: ['Noto Naskh Arabic', 'Baloo Bhaijaan 2'], ja: ['Klee One',
  'Zen Maru Gothic'], zh: ['Noto Serif SC', 'ZCOOL KuaiLe'] }[LANG] ?? ['Nunito', 'Fredoka'];
const START = RIGHT_BOUND ? 'right' : 'left'; // the side a page starts reading from
const corner = (v) => `${v}-${START}`, inward = (x) => (RIGHT_BOUND ? -x : x);
const [SLANT, CAPS] = LATIN ? ['italic', 'uppercase'] : ['normal', 'none'];
const LEAD = AR ? 20 : CJK ? 21 : 17.5, track = (v) => (LATIN ? v : 0); // Naskh, ruby need room
const fw = (w) => ({ 'ZCOOL KuaiLe': 400, 'Zen Maru Gothic': w > 550 ? 700 : 500 })[DISPLAY] ?? w;
const BOLD = TEXT === 'Klee One' ? 600 : 700; // and the weights the faces have
// #endregion

const PAGE = { w: 210, h: 280, top: 18, bottom: 18, inner: 14, outer: 12 }; // mm, mirrored
const HALF = PAGE.w - PAGE.inner - PAGE.outer, TALL = PAGE.h - PAGE.top - PAGE.bottom; // 184, 244
const MEASURE = CJK ? TALL : HALF; // a page's type area along the lines
const SHEET = 2 * HALF + 2 * PAGE.inner; // a spread's content area: 396 mm
const RIGHT = HALF + 2 * PAGE.inner; // where the second page's type area starts on the sheet
const LINE = 8, TAB = 22; // mm between answer lines; of the title before its words (the badge)
const NONE = { top: mm(0), right: mm(0), bottom: mm(0), left: mm(0) }; // no padding
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const onSecond = at('container', 'top-left', CJK ? 0 : RIGHT, CJK ? RIGHT : 0); // flow x or y
const DOWN = 156; // mm: a vertical field spread's map takes the head, its frames stand under it

// #region boxes: callout styles that extend each other
// Two steps of `extends`: the box (shape, type, tab), then the kind. The colours are `tema`
// entries, so one style serves the three topics; paddings, stripes and tabs are in the flow.
const tab = (f) => ({ position: 'top-left', background: col(f), color: col('paper'),
  fontFamily: DISPLAY, fontSize: pt(12), fontWeight: fw(600), height: mm(7), paddingX: mm(3.2),
  offset: mm(7), inset: mm(5), rule: { enabled: false, color: col(f) } });
const boxText = { fontFamily: TEXT, fontSize: pt(12), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), boldFontWeight: BOLD, firstLineIndent: pt(0),
  textAlign: CJK ? 'justify' : 'left', paragraphSpacing: true };
const calloutStyles = [
  { id: 'caja', backgroundEnabled: true, background: col('paper'), borderRadius: mm(3),
    border: { enabled: false }, padding: { top: mm(3.4), right: mm(5), bottom: mm(4), left: mm(5) },
    body: boxText, lists: { color: col('ink'), gap: mm(2), itemSpacing: mm(1.6) } },
  { id: 'caja-tema', extends: 'caja', label: tab('tema'), lists: { color: col('tema') } },
  { id: 'dato', extends: 'caja-tema', background: col('tema-tint') },
  { id: 'palabras', extends: 'caja-tema', border: { enabled: true, color: col('tema'),
    width: pt(1.4) } }, { id: 'actividad', extends: 'caja-tema',
    stripe: { enabled: true, side: 'left', width: pt(4), color: col('tema') } },
  { id: 'titulo', extends: 'caja', backgroundEnabled: false,
    padding: { top: mm(2.6), right: mm(6), bottom: mm(3.2), left: mm(TAB) } },
  { id: 'titulo-plano', extends: 'titulo', padding: { left: mm(8) } },
  { id: 'portada', extends: 'caja', background: col('agua'), borderRadius: mm(4),
    padding: { top: mm(2.6), right: mm(8), bottom: mm(3.6), left: mm(8) } },
  { id: 'foto', extends: 'caja', borderRadius: mm(2),
    padding: { top: mm(1.8), right: mm(1.8), bottom: mm(2.2), left: mm(1.8) } },
  { id: 'respuesta', extends: 'caja', padding: NONE }, { id: 'colofon', extends: 'caja',
    backgroundEnabled: false, padding: NONE,
    body: { ...boxText, fontSize: pt(8), lineHeight: pt(AR ? 13 : 11), color: col('muted') } },
];
// #endregion

// #region answer: one base template and a family of topics that extend it
// Ground, tab and number are decoration anchored to the title frame; the number,
// `{headingNumber}`, stands over the padding before its words. A topic extends the base.
const ground = () => ({ kind: 'box', id: 'ground',
  placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: 'fill' } },
  style: { backgroundColor: col('tema-ground') } });
const titleTab = () => ({ kind: 'box', id: 'tab', placement: { ...at('#titulo',
  'top-left'), size: { width: { to: '#titulo', edge: 'right' }, height: { to: '#titulo',
    edge: 'bottom' } } }, style: { backgroundColor: col('tema'), borderRadius: mm(4) } });
const badge = () => ({ kind: 'text', id: 'number', content: '{headingNumber}',
  fontFamily: DISPLAY, fontSize: pt(22), fontWeight: fw(700), color: col('tema'), align: 'center',
  box: { backgroundColor: col('paper'), borderRadius: mm(6) }, placement: { ...at('#titulo',
    corner('top'), inward(CJK ? 2.6 : 5), CJK ? 5 : 2.4), size: { width: mm(12), height: mm(12) } },
});
const title = { name: 'titulo', takes: 'h1', style: 'titulo', width: mm(MEASURE),
  placement: at('container', 'top-left') };

const base = {
  id: 'tema', spread: true, gutter: mm(12),
  decoration: { elements: [ground(), titleTab(), badge()] },
  frames: [title, { name: 'texto', flow: true, columns: 2, columnGap: mm(CJK ? 16 : 7), // 段
    width: mm(MEASURE), fit: { minScale: 0.9 } }],
  groups: [{ name: 'izquierda', kind: 'stack', gap: mm(6), frames: ['titulo', 'texto'] }],
};
const topic = (id, f, more) => ({ id, extends: 'tema', palette: swap(f), ...more });
const box = (name, style, minHeight, more) => ({ name, style, width: mm(MEASURE),
  minHeight: mm(minHeight), ...more });
const answer = (name, lines) => ({ name, optional: true, style: 'respuesta', width: mm(MEASURE),
  height: mm(LINE * lines), minHeight: mm(LINE * lines),
  rules: { every: mm(LINE), color: col('rule'), width: pt(0.75) } });
const PIC = CJK ? 30 : 56; // a picture at the end of a box's first lines pushes the text aside
const withPic = (name, style, minHeight, more) => [box(name, style, minHeight,
  { padding: { right: mm(PIC + 8) }, ...more }), { name: `${name}-foto`, layer: 2, width: mm(PIC),
  exclude: 'push', placement: at(`#${name}`, 'top-right', -5, 8) }];
// #endregion

// #region repeats: a grid lays its set once per item (#foto[1], #foto[2]…); a module per use
const grid = (name, frames, columns, placement, more, width = MEASURE) => ({ name, kind: 'grid',
  columns, columnGap: mm(5), rowGap: mm(CJK ? 8 : 12), repeat: { frames },
  placement: { ...placement, size: { width: mm(width), height: 'fill' } }, ...more });
const question = { id: 'pregunta', role: 'module', // a question and the lines to answer it on
  frames: [box('caja', 'dato', CJK ? 22 : 14, { width: 'fill' }), { ...answer('lineas',
    CJK ? 2 : 3), width: 'fill', placement: at('#caja', 'below', 0, CJK ? 4 : 7) }] };
// #endregion
const under = ({ placement, ...frame }) => ({ ...frame, width: mm(TALL - DOWN) }); // the map's
const stack = (name, frames, more) => ({ name, kind: 'stack', frames, gap: mm(CJK ? 8 : 12),
  ...more });
const pageTemplates = [
  base,
  topic('tema-agua', 'agua', {
    frames: [
      { name: 'foto', style: 'foto' },
      box('probar', 'palabras', CJK ? 30 : 46, { placement: at('#foto[1]', 'below', 0, 10) }),
      ...[['sabias', 'dato', 40], ['palabras', 'palabras', CJK ? 50 : 62],
        ['actividades', 'actividad', CJK ? 46 : 58]].map((f) => box(...f, { placement: onSecond })),
    ],
    groups: [grid('fotos', ['foto'], 3, at('#texto', 'below', 0, 8), { rowAlign: 'start' }),
      stack('derecha', ['sabias', 'palabras', 'actividades'])],
  }),
  topic('tema-campo', 'campo', {
    frames: [
      { name: 'mapa', crossGutter: true, width: mm(CJK ? DOWN - 6 : SHEET),
        ...(CJK && { height: mm(SHEET), placement: at('container', 'top-left') }) },
      ...(CJK ? [{ ...under(title), placement: at('container', 'top-left', DOWN) },
        under({ name: 'texto', flow: true, columns: 1 }), under(box('actividad', 'actividad', 24))]
        : [box('actividad', 'actividad', 24)]),
      { name: 'curso', style: 'dato', minHeight: mm(46) },
    ],
    groups: [
      stack('izquierda', CJK ? ['titulo', 'texto', 'actividad'] : ['titulo', 'mapa', 'texto',
        'actividad'], { gap: mm(6), ...(CJK && { placement: at('container', 'top-left', DOWN) }) }),
      grid('cursos', ['curso'], CJK ? 1 : 3, CJK ? at('container', 'top-left', DOWN, RIGHT)
        : at('#mapa', 'below', RIGHT, 6), { columnGap: mm(6), rowGap: mm(6) },
        CJK ? TALL - DOWN : MEASURE),
    ],
  }),
  topic('tema-sol', 'sol', {
    frames: [
      ...withPic('cuidar', 'palabras', CJK ? 52 : 64), box('turno', 'actividad', CJK ? 30 : 40),
      ...withPic('uso', 'dato', CJK ? 52 : 66),
    ],
    groups: [stack('izquierda', ['titulo', 'texto', 'cuidar', 'turno']),
      grid('usos', ['uso', 'uso-foto'], 1, onSecond, { rowAlign: 'start' })],
  }),
  { id: 'saberes', header: false,
    decoration: { elements: [titleTab()] },
    frames: [{ ...title, style: 'titulo-plano' },
      { name: 'texto', flow: true, width: mm(MEASURE) }],
    groups: [stack('pagina', ['titulo', 'texto'], { gap: mm(CJK ? 4 : 7) }),
      { name: 'preguntas', modules: true, gap: mm(CJK ? 4 : 7), placement: { ...at('#texto',
        'below', 0, CJK ? 4 : 7), size: { width: mm(MEASURE), height: 'fill' } } }] },
  question,
  // The contents: a frame takes the :::toc and lays it by the contents' own rules.
  { id: 'indice',
    decoration: { elements: [ground(), titleTab()] },
    frames: [{ ...title, style: 'titulo-plano' },
      { name: 'lista', takes: 'toc', width: mm(MEASURE) },
      { name: 'mapa', style: 'foto', width: mm(CJK ? 44 : HALF), ...(CJK && { height: mm(76) }) }],
    groups: [{ name: 'pagina', kind: 'stack', gap: mm(7), frames: ['titulo', 'lista', 'mapa'] }] },
  // The opener: a painting to the bleed, the title over its foot (down its right when vertical).
  { id: 'unidad', header: false, footer: false,
    decoration: { elements: [
      { kind: 'image', id: 'portada', resourceId: 'portada', decorative: true,
        placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: mm(157.5) } } },
      { kind: 'text', id: 'kicker', content: '{attr.unidad}', fontFamily: DISPLAY, fontSize: pt(11),
        fontWeight: fw(600), letterSpacing: pt(track(1)), textTransform: CAPS, color: col('agua'),
        align: START, box: { backgroundColor: col('paper'), borderRadius: mm(2), padding: {
          left: mm(2), right: mm(2) } }, placement: { ...at('#titulo', corner('top'), 0, -9),
          size: { height: mm(7), ...(CJK && { width: mm(60) }) } } }, // the room over capitals
    ] },
    frames: [
      { name: 'titulo', takes: 'h1', style: 'portada', width: mm(CJK ? TALL - 104 : 120),
        placement: CJK ? at('container', 'top-left', 104) : at('container', 'top-left', 0, 104) },
      { name: 'texto', flow: true, width: mm(CJK ? TALL - 142 : 160) },
      box('aprenderas', 'dato', 36, CJK ? { width: mm(TALL - 142) } : {}),
      { name: 'colofon', style: 'colofon', width: mm(CJK ? TALL - 142 : HALF),
        placement: at('container', CJK ? 'bottom-right' : 'bottom-left') },
    ],
    groups: [{ name: 'pagina', kind: 'stack', gap: mm(7), ...(CJK
      ? { frames: ['texto', 'aprenderas'], placement: at('container', 'top-left', 142, 26) }
      : { frames: ['titulo', 'texto', 'aprenderas'] }) }] },
];

// The running heads and the folios, on the outer side: an even page's left when left-bound.
const outside = (parity) => (parity === 'even') !== RIGHT_BOUND ? 'left' : 'right';
const outer = (parity, v, x, y) => at('page', `${v}-${outside(parity)}`,
  outside(parity) === 'left' ? x : -x, y);
const head = (id, content, parity) => ({ kind: 'text', id, content, parity,
  fontFamily: LATIN ? TEXT : DISPLAY, fontSize: pt(8), fontWeight: LATIN ? 700 : fw(500),
  letterSpacing: pt(track(1)), color: col('muted'), textTransform: CAPS, align: outside(parity),
  placement: outer(parity, 'top', PAGE.outer, 9) });
const folio = (id, parity) => ({ kind: 'text', id, content: '{pageNumber}', parity,
  fontFamily: DISPLAY, fontSize: pt(11), fontWeight: fw(600), color: col('paper'), align: 'center',
  box: { backgroundColor: col('agua'), borderRadius: mm(4) },
  placement: { ...outer(parity, 'bottom', PAGE.outer, -8), size: { width: mm(8), height: mm(8) } },
});

// #region contents: the toc settings; a frame of the 'indice' template takes the :::toc
const partAt = (x) => (CJK ? at('container', 'left', x) : at('container', START, inward(x)));
const toc = {
  levels: [{ level: 1, fontFamily: DISPLAY, fontSize: pt(15), lineHeight: pt(22),
    fontWeight: fw(500), color: col('ink'), numberFontWeight: fw(600), numberColor: col('agua'),
    numberWidth: mm(9), marginTop: pt(4) }, { level: 2, fontFamily: TEXT, fontSize: pt(11.5),
    lineHeight: pt(18), indent: mm(9), color: col('ink') }],
  pageNumber: { fontFamily: DISPLAY, fontWeight: fw(500), width: mm(9), color: col('agua') },
  leader: { char: CJK ? '…' : '.', gap: mm(1.5) },
  parts: { height: pt(34), marginTop: pt(12), marginBottom: pt(4), design: { elements: [
    { kind: 'box', id: 'band',
      placement: { ...at('container', 'top-left'), size: { width: 'fill', height: 'fill' } },
      style: { backgroundColor: col('paper'), borderRadius: mm(3) } },
    { kind: 'text', id: 'letter', content: '{number}', fontFamily: DISPLAY, fontSize: pt(16),
      fontWeight: fw(700), color: col('paper'), align: 'center',
      box: { backgroundColor: col('agua'), borderRadius: mm(4) },
      placement: { ...partAt(2), size: { width: mm(8), height: mm(8) } } },
    { kind: 'text', id: 'name', content: '{titleText}', fontFamily: DISPLAY, fontSize: pt(13),
      fontWeight: fw(600), color: col('agua'), align: START, placement: partAt(14) },
  ] } },
};
// #endregion

// #region art-labels: the map's label styles and anchors; the words are in the Markdown
// An anchor is a point of the painting (fractions of its width and height) and a label style;
// every language's ::label lines use the same anchors. A right-bound book shows the painting
// mirrored, the mountains on the right, so the river runs the way its pages are read: x comes
// from the other edge and a turn goes the other way. `start` is a label's own start, so the
// spring's label keeps it in Arabic and takes `end` in a label set left to right.
const halo = { color: col('paper'), width: pt(1.8) };
const labelStyles = [
  { id: 'sierra', fontFamily: DISPLAY, fontSize: pt(13), fontWeight: fw(600), color: col('ink'),
    textTransform: CAPS, letterSpacing: track(0.14), halo },
  { id: 'agua', fontFamily: TEXT, fontSize: pt(11), fontWeight: BOLD, fontStyle: SLANT,
    color: { hex: '#0b3a5c', model: 'hex' }, halo, // a name set away draws a leader to its point
    leader: { width: pt(1), endCap: 'dot', capSize: mm(1.6) } },
  { id: 'mar', fontFamily: TEXT, fontSize: pt(12), fontWeight: BOLD, fontStyle: SLANT,
    color: col('paper'), halo: { color: { hex: '#0b3a5c', model: 'hex' }, width: pt(1.8) } },
  { id: 'pueblo', fontFamily: DISPLAY, fontSize: pt(12), fontWeight: fw(600), color: col('ink'),
    halo },
  { id: 'curso', fontFamily: DISPLAY, fontSize: pt(10.5), fontWeight: fw(600), color: col('paper'),
    textTransform: CAPS, letterSpacing: track(0.08), background: col('campo'),
    padding: mm(1.6) },
];
const ANCHORS = [
  { id: 'sierra', x: 0.21, y: 0.055, style: 'sierra' },
  // The spring and the dam: the point is the place, `labelAt` where its name stands.
  { id: 'nacimiento', x: 0.049, y: 0.098, labelAt: { x: 0.075, y: 0.115 }, style: 'agua',
    align: 'start' },
  { id: 'fontalba', x: 0.135, y: 0.255, style: 'pueblo', verticalAlign: 'top' },
  { id: 'embalse', x: 0.293, y: 0.275, labelAt: { x: 0.31, y: 0.155 }, style: 'agua',
    width: 0.12 },
  { id: 'molinar', x: 0.505, y: 0.35, style: 'pueblo', verticalAlign: 'bottom' },
  { id: 'aldamar', x: 0.845, y: 0.505, style: 'pueblo', verticalAlign: 'bottom' },
  { id: 'mar', x: 0.965, y: 0.28, style: 'mar' },
  { id: 'rio', x: 0.61, y: 0.715, style: 'agua', rotate: -3 },
  { id: 'alto', x: 0.17, y: 0.45, style: 'curso' },
  { id: 'medio', x: 0.4, y: 0.77, style: 'curso' },
  { id: 'bajo', x: 0.74, y: 0.865, style: 'curso' },
];
const flip = (x) => Math.round((1 - x) * 1000) / 1000;
const flipped = (a) => ({ ...a, x: flip(a.x), ...(a.labelAt && { labelAt: { ...a.labelAt,
    x: flip(a.labelAt.x) } }),
  ...(a.rotate && { rotate: -a.rotate }), ...(a.align && !AR && { align: 'end' }) });
const anchors = RIGHT_BOUND ? ANCHORS.map(flipped) : ANCHORS;
// #endregion

const config = {
  canvasViewer: { pageGap: 0 }, // the Canvas joins the two pages of a spread
  locale: t({ es: 'es', en: 'en-gb', ca: 'ca', pt: 'pt-BR', fr: 'fr', de: 'de', it: 'it',
    ar: 'ar', zh: 'zh-Hans', ja: 'ja' }), // written out: Arabic sets its pages right to left
  resourceTypes: [{ id: 'dibujo', name: t({ es: 'Dibujo', en: 'Picture', ca: 'Dibuix',
    pt: 'Desenho', fr: 'Dessin', de: 'Bild', it: 'Disegno', ar: 'رسم', zh: '图', ja: '絵' }),
  shortLabel: '', numberingTemplate: '', resetOn: 'never', counterFormat: 'decimal',
  captionPrefix: '', defaultPlacement: { position: 'here' } }],
  colorPalette,
  page: { sizePreset: 'custom', width: mm(PAGE.w), height: mm(PAGE.h), dpi: 150, margins: {
    top: mm(PAGE.top), bottom: mm(PAGE.bottom), left: mm(PAGE.inner), right: mm(PAGE.outer),
    mirror: true } },
  layout: { layoutType: 'single', ...(CJK && { writingMode: 'vertical-rl' }) }, // right-bound
  bodyText: { fontFamily: TEXT, fontSize: pt(12), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    boldFontWeight: BOLD, textAlign: CJK ? 'justify' : 'left', firstLineIndent: CJK ? em(1) : pt(0),
    paragraphSpacing: !CJK, hyphenation: { enabled: LATIN }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: DISPLAY, fontWeight: fw(600), color: col('ink'), levels: [{ level: 1,
    fontSize: pt(28), lineHeight: pt(AR ? 40 : 32), color: col('paper'), marginTop: pt(0),
    marginBottom: pt(0), breakBefore: { enabled: false } }, { level: 2, fontSize: pt(15),
    lineHeight: pt(AR ? 24 : 19), marginTop: pt(9), marginBottom: pt(3) }] },
  headingStyles: [{ id: 'portada', numbered: false, toc: false, fontSize: pt(46),
    lineHeight: pt(AR ? 64 : 48) }, { id: 'previo', numbered: false, toc: false }],
  toc,
  parts: { page: false }, // a part is a row of the contents, with no divider page
  unorderedLists: { bulletChar: '•', color: col('agua'), fontWeight: BOLD, itemSpacing: pt(3) },
  orderedLists: { numberFormat: { zh: 'simp-chinese-informal', ja: 'japanese-informal' }[LANG]
    ?? 'arabic', fontFamily: DISPLAY, fontWeight: fw(600), color: col('agua'), itemSpacing: pt(4) },
  labelStyles,
  captionStyle: { fontFamily: TEXT, fontSize: pt(9), color: col('ink'), descriptionItalic: LATIN,
    gap: pt(4) },
  calloutStyles,
  header: { elements: [head('materia', '{subtitle}', 'even'), head('unidad', '{title}', 'odd')] },
  footer: { elements: [folio('folio-par', 'even'), folio('folio-impar', 'odd')] },
  pageTemplates,
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "Our river"
subtitle: "Social science · Year 3"
---

::::page{template="unidad" unidad="Unit 4 · Social science"}
# Our river {style="portada"}

Every town you know stands near water. This unit follows one river, the Aldara, from the snow where it starts to the sea where it ends. You will find out where a river is born, how it changes on its way down, and how the people of Fontalba, Molinar and Aldamar live beside it.

:::frame{slot="aprenderas" label="You will learn"}
- How a spring becomes a stream, and a stream becomes a river.
- What the upper, middle and lower course of a river are.
- How people use river water, and how to look after it.
:::

:::frame{slot="colofon"}
Set in Nunito and Fredoka (SIL OFL) · Original text (CC BY 4.0) · Illustrations generated with diffusion models
:::
::::

::::page{template="indice"}
# In this unit {style="previo"}

:::toc{keep="part" levels="1-2"}

:::figure{resource="rio" slot="mapa"}
::alt[Painted map of the valley of the River Aldara, from the snowy mountains to the sea.]
::caption[The River Aldara from its spring to the sea. The map is on pages 6 and 7.]
:::
::::

::::page{template="saberes"}
# What do you know about rivers? {style="previo"}

Before you start, think about the rivers you have seen. Write your ideas on the lines. At the end of the unit, come back to them and see what has changed.

:::module{template="pregunta"}
:::frame{slot="caja" label="Think 1"}
Where do you think a river starts?
:::
:::

:::module{template="pregunta"}
:::frame{slot="caja" label="Think 2"}
What do people use a river for?
:::
:::

:::module{template="pregunta"}
:::frame{slot="caja" label="Think 3"}
Which animals and plants live in or beside a river?
:::
:::
::::

:::part{number="A" title="A river from the mountains to the sea"}
:::

::::page{template="tema-agua" spread}
# Where a river is born

Rain and snow fall on the mountains. Some of the water runs down the slopes and some soaks into the ground. Underground it moves slowly, until it meets rock it cannot cross. Then it comes out into the open. A place where water comes out of the ground is called a **spring**.

## From spring to stream

A spring gives only a trickle. The trickle runs downhill and meets other trickles, and together they make a **stream**. On a steep slope a stream runs fast. It rolls pebbles along and wears them smooth. When streams meet, they make a bigger one. The River Aldara begins like this, in the snow of the White Range, 1,850 metres above the sea.

:::figure{resource="nacimiento" slot="foto"}
::alt[Clear water trickling out between mossy rocks.]
::caption[A spring. The water has been underground for months.]
:::

:::figure{resource="arroyo" slot="foto"}
::alt[A stream tumbling over round stones.]
::caption[A stream, steep and fast, with pebbles worn smooth.]
:::

:::figure{resource="cascada" slot="foto"}
::alt[A small waterfall falling into a green pool.]
::caption[A waterfall, where the stream drops over a step of rock.]
:::

:::frame{slot="probar" label="Try it"}
Hold a wet sponge over a tray and squeeze it gently. Where does the water come out? Watch how it drips and then runs. That is how a spring feeds a stream.
:::

:::frame{slot="sabias" label="Did you know?"}
At its spring, the Aldara is a trickle you could step over. After 94 kilometres it is as wide as a football pitch is long.
:::

:::frame{slot="palabras" label="Words to learn"}
**Spring:** a place where water comes out of the ground.

**Stream:** a small river that runs fast down a slope.

**Tributary:** a stream that flows into a bigger river.

**Bank:** the land along the side of a river.
:::

:::frame{slot="actividades" label="Activities"}
1. Look at the three pictures. Which one shows a spring? How can you tell?
2. Why does a stream run faster in the mountains than in the valley?
3. Which of the four words in the box can you see in the pictures?
:::
::::

::::page{template="tema-campo" spread}
# From the mountains to the sea

The River Aldara is 94 kilometres long. It starts in the White Range, crosses a valley and a plain, and reaches the sea at Aldamar. Geographers split a river into three parts. Each part is called a **course**, and each one looks different.

:::figure{resource="mapa" slot="mapa"}
::alt[A painted map of the valley: snowy mountains and a spring at the left, the village of Fontalba, a reservoir with a dam, the town of Molinar with its bridge and mill, farm fields, the river bending across a plain, and the port of Aldamar by the sea at the right.]
::label[White Range]{at="sierra"}
::label[Spring]{at="nacimiento"}
::label[Fontalba]{at="fontalba"}
::label[Penalta Reservoir]{at="embalse"}
::label[Molinar]{at="molinar"}
::label[Aldamar]{at="aldamar"}
::label[Sea]{at="mar"}
::label[River Aldara]{at="rio"}
::label[Upper course]{at="alto"}
::label[Middle course]{at="medio"}
::label[Lower course]{at="bajo"}
:::

:::frame{slot="actividad" label="Look at the map"}
Follow the river with your finger from the spring to the sea. Which town is nearest to the sea?
:::

:::frame{slot="curso" label="Upper course"}
The slope is steep. The water is cold, clear and fast, and it cuts into the rock. Fontalba stands here.
:::

:::frame{slot="curso" label="Middle course"}
The valley is wider and the river slows down. Farmers water their fields, and Molinar grew around a bridge and a mill.
:::

:::frame{slot="curso" label="Lower course"}
The land is almost flat. The river is wide and slow, and it bends in great loops. At Aldamar it flows into the sea.
:::
::::

:::part{number="B" title="People and the river"}
:::

::::page{template="tema-sol" spread}
# People and the river

People have always settled near rivers. They need water to drink, to wash and to grow food. A river also gives fish, a road for boats and the push that turns a wheel.

## Looking after the river

A river stays clean only if we keep it clean. Rubbish, oil and dirty water make the river sick, and the fish and plants that live in it suffer. Everything that goes down a drain or a street ends up in a river or in the sea.

:::frame{slot="cuidar" label="We look after our river"}
- We put rubbish in the bin, never in the water.
- We use water carefully and turn off the tap.
- We keep to the paths and leave plants and animals alone.
- We help to clean the bank when the school organises it.
:::

:::frame{slot="turno" label="Your turn"}
1. Draw a poster with three rules to keep our river clean.
2. Ask at home: where does the water from your tap come from?
:::

:::figure{resource="limpieza" slot="cuidar-foto"}
::alt[Children with gloves and paper bags picking up litter on a river bank.]
:::

:::frame{slot="uso" label="1 · Water for the fields"}
In the middle course, farmers open small canals so the river water runs between the rows. Without it, tomatoes and lettuces would not grow in summer. A single canal can carry water for many kilometres.

:::figure{resource="riego" slot="uso-foto"}
::alt[A farmer lifting a gate in an irrigation canal in a field of vegetables.]
:::
:::

:::frame{slot="uso" label="2 · Mills"}
Long ago the falling water turned the wheel of the mill at Molinar. The wheel moved the stones that ground wheat into flour for the whole valley. Today the old mill is a small museum.

:::figure{resource="molino" slot="uso-foto"}
::alt[An old stone mill with a big wooden wheel beside a river.]
:::
:::

:::frame{slot="uso" label="3 · Sport and play"}
Now the calm lower course is a place for canoes. On summer mornings children from Aldamar learn to paddle with a monitor, and everyone wears a life jacket.

:::figure{resource="piraguas" slot="uso-foto"}
::alt[Children in life jackets paddling two canoes on a calm river.]
:::
:::
::::
`; // content.<lang>.md, inlined by the Cookbook

// #region art: nine paintings (JPEGs in assets/), the pictures of the unit
// Painted with a diffusion model in a coloured-pencil and watercolour manner, cut to the shape
// of the frames that show them and declared with their pixels. Nothing is written on them: the
// names on the map are ::label lines of the Markdown, standing at the anchors above. A
// right-bound book's map is the same painting mirrored.
const ART = { portada: ['portada-1400.jpg', 1400, 1021, 165],
  mapa: [RIGHT_BOUND ? 'mapa-1900-rtl.jpg' : 'mapa-1900.jpg', 1900, 730, 122],
  ...Object.fromEntries(['nacimiento', 'arroyo', 'cascada', 'riego', 'molino', 'piraguas',
    'limpieza'].map((id) => [id, [`${id}-720.jpg`, 720, 540, 330]])) };
const resources = await Promise.all(Object.entries(ART).map(async ([id, [fileId, w, h, ppi]]) => {
  await loadImage(fileId, asset(fileId));
  return { id, typeId: 'dibujo', kind: 'bitmap', caption: '', altText: '', createdAt: 0,
    updatedAt: 0, bitmap: { fileId, format: 'jpeg', width: w, height: h, resolution: ppi },
    ...(id === 'mapa' && { anchors }) };
}));
// The map again with no anchors, small, under the contents.
resources.push({ ...resources.find((r) => r.id === 'mapa'), id: 'rio', anchors: [] });
// #endregion

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
// Every face of the ten editions; each loads its own two, with the cjk and arabic blocks' files.
const FONTS = {
  Nunito: ['400', '400i', '700'], Fredoka: ['500', '600', '700'],
  'Noto Naskh Arabic': ['400', '700'], 'Baloo Bhaijaan 2': ['500', '600', '700'],
  'Klee One': ['400', '600'], 'Zen Maru Gothic': ['500', '700'], // a textbook hand, rounded heads
  'Noto Serif SC': ['400', '700'], 'ZCOOL KuaiLe': ['400'],
};
for (const face of Object.keys(FONTS)) if (![TEXT, DISPLAY].includes(face)) delete FONTS[face];
await loadFonts(FONTS, markdown);
await loadCjkFonts(FONTS, markdown, { vertical: CJK });
await loadArabicFonts(FONTS, markdown);

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await withLoadedFonts(() => buildDocument({ markdown, resources }, config),
  { ...kitFonts(FONTS), text: markdown });
showBook(doc, { title: t({ es: 'Nuestro río', en: 'Our river', ca: 'El nostre riu',
  pt: 'Nosso rio', fr: 'Notre fleuve', de: 'Unser Fluss', it: 'Il nostro fiume', ar: 'نهرنا',
  zh: '我们的河流', ja: 'わたしたちの川' }) });
offerPdf(() => renderToPdf(doc, { resourceBytes: imageBytes,
  fontProvider: { zh: cjkPdfProvider, ja: cjkPdfProvider, ar: arabicPdfProvider }[LANG]
    ?? fontsourceProvider }), `${RECIPE}.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 ───────────────────────────────────────────────────────────────────────
```

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

### Προσθέστε μια τέταρτη οικογένεια

Ένα θέμα για τη θάλασσα είναι μια τέταρτη καταχώριση στο `FAMILIES` και ένα πρότυπο φτιαγμένο με `topic('tema-mar', 'mar', { frames })`. Το `swap('mar')` γράφει την παλέτα του, και τα πλαίσια και το φόντο την ακολουθούν.

```diff
-  sol: { main: '#9a5209', tint: '#fcefd2', ground: '#f8e6b8' },
+  sol: { main: '#9a5209', tint: '#fcefd2', ground: '#f8e6b8' },
+  mar: { main: '#0f5a6b', tint: '#dcf0f2', ground: '#cbe6ea' },
```

### Κρατήστε το κείμενο στο μέγεθός του

Ένα πλαίσιο κειμένου που δεν πρέπει να μικρύνει το κείμενό του παίρνει `fit: { shrinkText: false }`. Ένα μακρύτερο κείμενο πιέζει τότε περισσότερο τα πλαίσια γύρω του, και η κλίμακα αναδιάταξης φτάνει πρώτα στις εικόνες.

```diff
   frames: [title, { name: 'texto', flow: true, columns: 2, columnGap: mm(CJK ? 16 : 7), // 段
-    width: mm(MEASURE), fit: { minScale: 0.9 } }],
+    width: mm(MEASURE), fit: { shrinkText: false } }],
```

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

- Ένα όνομα ζωγραφισμένο μέσα σε μια εικόνα δεν θα μπορούσε να αλλάξει με τη γλώσσα: ο χάρτης δεν έχει καμία λέξη, και κάθε όνομα είναι ετικέτα `::label`.
- Η παλέτα ενός θέματος αλλάζει μόνο τις καταχωρίσεις `tema`. Οι αριθμοί σελίδας και τα περιεχόμενα χρησιμοποιούν το `agua`, που έχει το ίδιο μπλε, οπότε μένουν μπλε στις πράσινες σελίδες και στις σελίδες άμμου· συνδέστε τα με το `tema` και θα ακολουθούν το θέμα.
- Ένα ινδοαραβικό ψηφίο δίπλα σε μια μέση τελεία διαβάζεται ως δύο ψηφία: το `١ · ماء` μοιάζει με `٠١ ماء`, επειδή το αραβικό μηδέν είναι μια τελεία. Η αραβική έκδοση γράφει `١- ماء للحقول` και γράφει ολογράφως τον αριθμό της ενότητας.
- Ένα στοιχείο διακόσμησης στέκεται πάνω στο φύλλο, όχι στη ροή: ένα σήμα τοποθετημένο `top-left` ενός πλαισίου κειμένου μένει αριστερά στα αραβικά. Το `corner('top')` και το `inward(x)` το τοποθετούν από την πλευρά από την οποία ξεκινά η ανάγνωση της σελίδας.
- Σε ένα πλέγμα, κάθε στοιχείο είναι δικό του μπλοκ: η εικόνα ενός πλαισίου ανήκει στο σύνολό του μόνο όταν το `:::figure` της γράφεται μέσα στο `:::frame` του πλαισίου. Γραμμένη μετά από αυτό, η εικόνα είναι αυτόνομο στοιχείο και παίρνει δικό της κελί.
- Δύο εικόνες που στοιχειοθετούν τον ίδιο πόρο παίρνουν τις λέξεις της πρώτης: ο μικρός χάρτης στη σελίδα περιεχομένων είναι το ίδιο αρχείο με δικό του πόρο, το `rio`, χωρίς σημεία αγκύρωσης.

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

- Συνταγή: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Κείμενο: Our river, a children's textbook unit written for this recipe in Spanish and set in ten languages: Postext Cookbook, CC-BY-4.0
- Εικόνες: The valley of the River Aldara, painted from the mountains to the sea, with two children watching the water.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: The painted map of the valley, from the spring to the port, with no lettering: the names are labels set from the Markdown.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: The same painted map mirrored, the mountains on the right, for the books bound on the right (Arabic, Chinese, Japanese).: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A spring between mossy rocks.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A mountain stream over round stones.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A small waterfall into a green pool.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: A farmer opening the gate of an irrigation canal.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: An old stone watermill with its wheel.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: Children paddling canoes on a calm river.: Generated With Diffusion Models, πρωτότυπο
- Εικόνες: Children and a teacher picking up litter on a river bank.: Generated With Diffusion Models, πρωτότυπο
- Γραμματοσειρές: Nunito (OFL-1.1), Fredoka (OFL-1.1), Noto Naskh Arabic (OFL-1.1), Baloo Bhaijaan 2 (OFL-1.1), Klee One (OFL-1.1), Zen Maru Gothic (OFL-1.1), Noto Serif SC (OFL-1.1), ZCOOL KuaiLe (OFL-1.1)
- Κώδικας: MIT · Δείγμα περιεχομένου: CC-BY-4.0

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

- [Αρ. 157 · Ένας σχολικός άτλαντας με ονόματα από το Markdown](https://postext.dev/el/cookbook/school-atlas-labelled-maps.md): Χάρτες χωρίς ούτε ένα γράμμα, με ονόματα από γραμμές ::label στα σημεία αγκύρωσης κάθε πόρου, σε στοιχειοθετημένες σελίδες και σε δισέλιδο, σε τρεις γλώσσες. · Επίπεδο 3 (Προχωρημένο) · Σχολικά βιβλία
- [Αρ. 158 · Εικονογραφημένο χρονολόγιο σε δισέλιδο](https://postext.dev/el/cookbook/illustrated-timeline-spread.md): Πρότυπο δισέλιδου για το χρονολόγιο σχολικού βιβλίου: ζώνη πάνω από τη ράχη, πλέγμα με μία κάρτα ανά χρονολογία, γραμμή σύνδεσης ως κάθε κάρτα. · Επίπεδο 3 (Προχωρημένο) · Σχολικά βιβλία
- [Αρ. 008 · Μια οικογένεια πλαισίων σχολικού βιβλίου με χρωματικό κώδικα](https://postext.dev/el/cookbook/textbook-box-family.md): Έξι πλαίσια σχολικού βιβλίου σε τρία χρώματα, που ξεχωρίζουν με λωρίδα και εικονίδιο, σήμα, αριθμημένη καρτέλα, σειρά εικονογραμμάτων ή σημάδι εκτός πλαισίου. · Επίπεδο 2 (Μεσαίο) · Σχολικά βιβλία
