# Ein arabisches Arbeitsheft, von rechts nach links

> Ein arabisches Grundschulheft von rechts nach links: Auswahl mit أ ب ج, Zuordnungsspalten, Wortkasten, صح oder خطأ, Buchstabensalat, ostarabische Ziffern.

- HTML-Fassung: https://postext.dev/de/cookbook/arabic-workbook-rtl
- Rezept Nº 173 · Schulbücher · Stufe 2 (Mittel) · Ausgaben: Canvas, PDF
- Gattungen: Arbeitshefte und Übungen, Lehrbücher
- Benötigt postext ≥ 1.59.0, postext-pdf ≥ 1.59.0 · getestet mit 1.59.0, postext-pdf 1.59.0 am 2026-10-24
- Seiten: [١](https://postext.dev/cookbook/arabic-workbook-rtl/ar/p01.webp?v=cd08e1dc), [٢](https://postext.dev/cookbook/arabic-workbook-rtl/ar/p02.webp?v=cd08e1dc), [٣](https://postext.dev/cookbook/arabic-workbook-rtl/ar/p03.webp?v=cd08e1dc), [٤](https://postext.dev/cookbook/arabic-workbook-rtl/ar/p04.webp?v=cd08e1dc), [1](https://postext.dev/cookbook/arabic-workbook-rtl/ar/p05.webp?v=cd08e1dc), [2](https://postext.dev/cookbook/arabic-workbook-rtl/ar/p06.webp?v=cd08e1dc), [3](https://postext.dev/cookbook/arabic-workbook-rtl/ar/p07.webp?v=cd08e1dc), [4](https://postext.dev/cookbook/arabic-workbook-rtl/ar/p08.webp?v=cd08e1dc)
- In der Sandbox öffnen: https://postext.dev/de/sandbox#recipe=arabic-workbook-rtl&lang=ar (.postext: https://postext.dev/cookbook/arabic-workbook-rtl/ar/arabic-workbook-rtl.postext)
- Zuletzt aktualisiert: 2026-10-24
- Andere Sprachen: [en](https://postext.dev/en/cookbook/arabic-workbook-rtl.md), [es](https://postext.dev/es/cookbook/arabic-workbook-rtl.md), [ca](https://postext.dev/ca/cookbook/arabic-workbook-rtl.md), [fr](https://postext.dev/fr/cookbook/arabic-workbook-rtl.md), [it](https://postext.dev/it/cookbook/arabic-workbook-rtl.md), [pt](https://postext.dev/pt/cookbook/arabic-workbook-rtl.md), [zh](https://postext.dev/zh/cookbook/arabic-workbook-rtl.md), [ja](https://postext.dev/ja/cookbook/arabic-workbook-rtl.md), [ar](https://postext.dev/ar/cookbook/arabic-workbook-rtl.md)

## Kurz gesagt

Seiten eines arabischen Kinder-Arbeitshefts über einen Schulgarten: die Antwort wählen, Spalten verbinden, Lücken aus einem Wortkasten füllen, richtig oder falsch ankreuzen, Wörter ordnen, Wörter im Gitter finden.

## Was Sie setzen

Eine Einheit aus einem arabischen Arbeitsheft für die zweite Klasse, auf einer Seite von 17 × 24 cm, rund um einen Schulgarten. Sie beginnt mit einem Aquarellband, dem Reiter und dem Titel der Einheit und je einer gepunkteten Linie für Name, Klasse und Datum. Dann folgen die Übungen, die ein arabisches Grundschulbuch druckt: die richtige Antwort wählen, mit أ) ب) ج), drei in einer Reihe; die beiden Spalten verbinden; die Lücken aus einem Wortkasten füllen; صح oder خطأ ankreuzen; Wörter ordnen und den Satz auf die Linie schreiben; sieben Gartenwörter in einem Buchstabengitter finden. Die Lösungen schließen die Einheit ab. Derselbe Text wird zweimal gesetzt: Die Maschrek-Ausgabe zählt alles mit ostarabischen Ziffern, ١ ٢ ٣, die Maghreb-Ausgabe mit europäischen. Beide liest man von rechts, beide sind rechts gebunden.

**Dieses Rezept beantwortet:**

- Wie setze ich ein arabisches Arbeitsheft von rechts nach links, mit Zuordnungen und ostarabischen Ziffern?
- Wie setze ich eine Arbeitsheftseite: Nummern im Kreis, Wortspeicher, richtig oder falsch, verbinde?
- Wie mache ich aus einer Wortliste ein Suchsel oder ein Kreuzworträtsel?

## Die kurze Antwort

```js
// script.js, Zeilen 34–53
// The locale sets the direction, the binding and the digits: 'ar' writes the exercise
// numbers, the items and the key in Arabic-Indic digits (١ ٢ ٣), 'ar-MA' in European ones.
// Options take the abjad letters (أ ب ج), true/false the words صح / خطأ, both from the
// language. Nothing below names a side: the engine sets every part from the right.
const tamrin = {
  id: 'tamrin',
  number: { shape: 'disc', fontFamily: LABEL, background: col('accent') },
  instruction: { fontFamily: LABEL, bold: false, color: col('ink') },
  options: { layout: 'row' }, // أ) ب) ج) side by side, three to a row (columns=3)
  blank: { look: 'dots', color: col('muted') }, // a dotted line, as Arab workbooks print it
  match: { color: col('accent') },
  bank: { box: 'sunduq', order: 'shuffle' },
  area: { kind: 'lines', color: col('rule') },
  grid: { fontFamily: TEXT, rule: col('leaf'), uppercase: false }, // Arabic has no capitals
  answers: { color: col('leaf'), fontFamily: TEXT },
  solutions: { box: 'hulul' },
  marginTop: em(1.1), marginBottom: em(0.5),
};
// The solutions where :::solutions stands: at the end of the unit.
const exercises = { solutions: { placement: 'directive' } };
```

## Zutaten

**Zeigt**

- [Übungen](https://postext.dev/de/docs/exercises.md#übungen): Der Zaun :::exercise: eine Aufgabe, deren Arbeitsanweisung, Fragen und Lösungen im Markdown stehen, nummeriert und so gesetzt, wie ein Übungsstil es vorgibt, auf Papier wie am Bildschirm.
- [Text von rechts nach links](https://postext.dev/de/docs/arabic-layout.md#richtung-und-bidirektionaler-algorithmus): direction legt die Grundrichtung des Dokuments fest: 'auto' (Standard) übernimmt sie von der Schrift des locale, sodass 'ar', 'fa' oder 'he' von rechts nach links laufen; der bidirektionale Algorithmus (UAX #9) ordnet die lateinischen Wörter und Zahlen innerhalb jeder Zeile, und das Buch wird rechts gebunden.
- [Ziffern der erzeugten Zahlen](https://postext.dev/de/docs/configuration-language.md#dokumentsprache): numerals ('auto', 'latn', 'arab', 'arabext') wählt die Ziffern jeder Zahl, die die Engine schreibt: Seitenzahlen, Listen- und Fußnotennummern, Überschriften- und Abbildungszähler, die Seitenzahlen von Inhaltsverzeichnis und Register. 'auto' folgt dem locale: ١٢٣ für Arabisch, 1 2 3 im Maghreb (ar-MA, ar-DZ, ar-TN). Der eigene Text des Autors wird nie umgeschrieben.

**Verwendet außerdem**

- [Übungsstile](https://postext.dev/de/docs/exercises.md#übungsstile)
- [Auswahl und richtig oder falsch](https://postext.dev/de/docs/exercises.md#auswahl-und-richtig-oder-falsch)
- [Lücken und Wortspeicher](https://postext.dev/de/docs/exercises.md#lückentexte-und-wortspeicher)
- [Zuordnen und sortieren](https://postext.dev/de/docs/exercises.md#zuordnen-und-sortieren)
- [Ordnen](https://postext.dev/de/docs/exercises.md#ordnen)
- [Suchsel und Kreuzworträtsel](https://postext.dev/de/docs/exercises.md#wortsuchrätsel-und-kreuzworträtsel)
- [Lösungen](https://postext.dev/de/docs/exercises.md#lösungen)
- [Arabische Schriften](https://postext.dev/de/docs/arabic-layout.md#schriften)
- [Arabische Nummerierungsstile](https://postext.dev/de/docs/arabic-layout.md#ziffern-und-zahlstile)
- [Rechts gebundene Bücher](https://postext.dev/de/docs/configuration-page-layout.md#bindung)
- [Inline-Chips](https://postext.dev/de/docs/configuration-styles.md#chip-stile)
- [Kästen](https://postext.dev/de/docs/configuration-callouts.md#kastenstile)
- [Gestaltete Auftakte](https://postext.dev/de/docs/configuration-headings.md#seitenbreite-und-erweiterte-gestaltung)
- [Überschriftenattribute](https://postext.dev/de/docs/document-format.md#attribute-von-überschriften)
- [Bilder in Seitengestaltungen](https://postext.dev/de/docs/configuration-headers-footers.md#bildelemente)
- [Semantische Farbpalette](https://postext.dev/de/docs/configuration-fonts-colors-viewers.md#farbpalette)
- [PDF-Export](https://postext.dev/de/docs/configuration-pdf-output.md#pdfs-erzeugen)
- [Kästen, die sich teilen oder ganz bleiben](https://postext.dev/de/docs/configuration-callouts.md#der-container-callout)
- [Spaltenausgleich](https://postext.dev/de/docs/configuration-page-flow.md#spaltenausgleich)
- [Offene Fragen und Schreibflächen](https://postext.dev/de/docs/exercises.md#offene-fragen-und-schreibflächen)
- [Kopfzeilen nach Seitenrolle](https://postext.dev/de/docs/configuration-headers-footers.md#textelemente)
- [Absatzformate](https://postext.dev/de/docs/configuration-styles.md#absatzformate)
- [Im PDF eingebettete Schriften](https://postext.dev/de/docs/configuration-pdf-output.md#warum-ein-font-provider)
- [Abbildungen und Tabellen als Ressourcen](https://postext.dev/de/docs/document-format-resources.md#ressourcen)

**Die Konfiguration auf einen Blick**

- [`bodyText`](https://postext.dev/de/docs/configuration-text.md#fließtext), [`calloutStyles`](https://postext.dev/de/docs/configuration-callouts.md#kastenstile), [`chipStyles`](https://postext.dev/de/docs/configuration-styles.md#chip-stile), [`colorPalette`](https://postext.dev/de/docs/configuration-fonts-colors-viewers.md#farbpalette), `exerciseStyles`, `exercises`, [`footer`](https://postext.dev/de/docs/configuration-headers-footers.md#kopf--und-fußzeilen), [`header`](https://postext.dev/de/docs/configuration-headers-footers.md#kopf--und-fußzeilen), [`headings`](https://postext.dev/de/docs/configuration-headings.md#überschriften), [`layout`](https://postext.dev/de/docs/configuration-page-layout.md#layout), [`locale`](https://postext.dev/de/docs/configuration-language.md#silbentrennung), [`orderedLists`](https://postext.dev/de/docs/configuration-lists-math.md#nummerierte-listen), [`page`](https://postext.dev/de/docs/configuration-page-layout.md#seite), [`paragraphStyles`](https://postext.dev/de/docs/configuration-styles.md#absatzformate)

**APIs**

- [`buildDocument`](https://postext.dev/de/docs/configuration-programmatic-usage.md#ein-dokument-erzeugen), [`decompressWoff2`](https://postext.dev/de/docs/configuration-pdf-output.md#font-provider-im-browser-fontsource--woff2), [`registerResourceImage`](https://postext.dev/de/docs/architecture.md#api-oberfläche), [`renderPageToCanvas`](https://postext.dev/de/docs/configuration-programmatic-usage.md#eine-seite-als-bitmap-rendern), [`renderToPdf`](https://postext.dev/de/docs/configuration-pdf-output.md#pdfs-erzeugen), [`withLoadedFonts`](https://postext.dev/de/docs/configuration-programmatic-usage.md#schriften-vor-dem-layout-laden)

**Schriften**

- Noto Naskh Arabic (OFL-1.1), Baloo Bhaijaan 2 (OFL-1.1)

## Zubereitung

### 1 · Keine Seite nennen

Der Code steht oben in [der kurzen Antwort](https://postext.dev/de/cookbook/arabic-workbook-rtl.md#die-kurze-antwort). `locale: 'ar'` setzt den Text von rechts nach links, bindet das Buch rechts und wählt die Ziffern; der Übungsstil nimmt aus der Sprache die Abdschad-Buchstaben für die Optionen und صح und خطأ für richtig oder falsch. Die Zuordnungsspalten, der Wortkasten, der Buchstabensalat und die Schreiblinien sind als Kastengestaltungen gezeichnet, und eine Seite von rechts nach links spiegelt sie. Die erste Spalte steht dann rechts, ein waagrecht im Gitter gelesenes Wort läuft von rechts nach links, und die Zuordnungspunkte stehen sich in der Mitte gegenüber.

### 2 · Der Auftakt mit dem Garten

```js
// script.js, Zeilen 58–73
const BAND = 170 / 2.4; // mm: the painting's height at the page's width
const opener = { enabled: true, minHeight: mm(BAND - 20 + 21), slot: { elements: [
  { kind: 'image', id: 'picture', resourceId: '{attr.pic}', decorative: true, reserve: false,
    placement: { anchor: { to: 'page', edge: 'top-left' },
      size: { width: mm(170), height: mm(BAND) } } },
  // In the flow of a right-to-left page 'left' is the start of the line: the right.
  { kind: 'text', id: 'unit', content: '{attr.kicker}', fontFamily: LABEL, fontSize: pt(11),
    fontWeight: 700, color: col('paper'), align: 'left',
    box: { backgroundColor: col('accent'), borderRadius: mm(1.5),
      padding: { top: mm(0.6), bottom: mm(0.4), left: mm(2.4), right: mm(2.4) } },
    placement: { anchor: { to: 'container', edge: 'top-left' },
      offset: { x: mm(0), y: mm(BAND - 20 + 3) } } },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: LABEL, fontSize: pt(30),
    fontWeight: 700, color: col('ink'), align: 'left',
    placement: { anchor: { to: '#unit', edge: 'right-of' }, offset: { x: mm(4), y: mm(-5) } } },
] } };
```

Das Bild ist an der Seite verankert und behält seinen Platz. Reiter und Titel stehen im Fluss der Seite, wo `left` der Zeilenanfang ist, und rücken so ohne eigene Koordinate nach rechts. Die Seitenzahlen bleiben physisch, wie Kolumnentitel, und geben jede Seite ausdrücklich an.

### 3 · Zwei Ausgaben, zwei Ziffernsätze

```js
// script.js, Zeilen 227–232
// Both are bound on the right and read from the right; only the locale changes.
const build = () => withLoadedFonts(() => buildDocument({ markdown, resources }, config()),
  { ...kitFonts(FONTS), text: markdown });
const mashriq = await build();
edition = { locale: 'ar-MA' }; // the same book for Morocco: European digits, still right to left
const docs = [mashriq, await build()];
```

Die Konfiguration ist eine Funktion, also bekommt jeder Satzlauf sein eigenes Objekt, und der zweite ändert nur die Locale. `ar-MA` schreibt die Übungsnummern, die Aufgaben, die Lösungen und die Seitenzahlen in europäischen Ziffern und lässt alles andere, wie es war: die Richtung, die Bindung, die Abdschad-Buchstaben und die Wörter der Lösungen.

## Das ganze Rezept

Eine Datei, aus dem Ordner des Rezepts zusammengesetzt, mit dem Beispieltext und dem gemeinsamen Baukasten der Rezepte bereits eingebettet; sie baut ihre eigene Seite auf. Zum Ausführen setzen Sie sie in ein `<script type="module">` auf einer leeren Seite oder fügen sie in das JS-Feld eines neuen CodePen-Pens ein (als Modul). Sie importiert postext von esm.sh, es gibt also nichts zu installieren oder zu bauen.

- Quellordner: https://github.com/drnachio/postext/tree/main/cookbook/arabic-workbook-rtl

### script.js

```js
// ═══ Postext Cookbook · Nº 173 · An Arabic workbook, right to left ═══════════════
// https://postext.dev/en/cookbook/arabic-workbook-rtl
// Code: MIT · Text: original (CC BY 4.0) · Pictures: generated with diffusion models
// Fonts: Noto Naskh Arabic, Baloo Bhaijaan 2 (SIL OFL 1.1) · Needs postext ≥ 1.59.0
import {
  buildDocument, withLoadedFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'ar'; // @lang: the language of the frame; the workbook is Arabic in all
const RECIPE = 'arabic-workbook-rtl';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: a garden workbook: ink, a terracotta accent, a leaf green, sand
const palette = {
  ink: '#22282e', // text
  accent: '#b9542a', // the one accent: exercise numbers, the unit tab, the word bank
  leaf: '#4f7d3a', // the second: rules and the word search's ruling
  sand: '#f8eedf', // the bank's ground, the answers box
  rule: '#c8b49b', // writing lines
  muted: '#6f655c', // folios, the name line, the colophon
  paper: '#ffffff',
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion
// Naskh for the text, a rounded Arabic for the labels a child reads first.
const [TEXT, LABEL] = ['Noto Naskh Arabic', 'Baloo Bhaijaan 2'];

// #region answer: one exercise style read right to left, in the edition's digits
// The locale sets the direction, the binding and the digits: 'ar' writes the exercise
// numbers, the items and the key in Arabic-Indic digits (١ ٢ ٣), 'ar-MA' in European ones.
// Options take the abjad letters (أ ب ج), true/false the words صح / خطأ, both from the
// language. Nothing below names a side: the engine sets every part from the right.
const tamrin = {
  id: 'tamrin',
  number: { shape: 'disc', fontFamily: LABEL, background: col('accent') },
  instruction: { fontFamily: LABEL, bold: false, color: col('ink') },
  options: { layout: 'row' }, // أ) ب) ج) side by side, three to a row (columns=3)
  blank: { look: 'dots', color: col('muted') }, // a dotted line, as Arab workbooks print it
  match: { color: col('accent') },
  bank: { box: 'sunduq', order: 'shuffle' },
  area: { kind: 'lines', color: col('rule') },
  grid: { fontFamily: TEXT, rule: col('leaf'), uppercase: false }, // Arabic has no capitals
  answers: { color: col('leaf'), fontFamily: TEXT },
  solutions: { box: 'hulul' },
  marginTop: em(1.1), marginBottom: em(0.5),
};
// The solutions where :::solutions stands: at the end of the unit.
const exercises = { solutions: { placement: 'directive' } };
// #endregion


// #region opener: the garden to the bleed, the unit's tab and its title under it
const BAND = 170 / 2.4; // mm: the painting's height at the page's width
const opener = { enabled: true, minHeight: mm(BAND - 20 + 21), slot: { elements: [
  { kind: 'image', id: 'picture', resourceId: '{attr.pic}', decorative: true, reserve: false,
    placement: { anchor: { to: 'page', edge: 'top-left' },
      size: { width: mm(170), height: mm(BAND) } } },
  // In the flow of a right-to-left page 'left' is the start of the line: the right.
  { kind: 'text', id: 'unit', content: '{attr.kicker}', fontFamily: LABEL, fontSize: pt(11),
    fontWeight: 700, color: col('paper'), align: 'left',
    box: { backgroundColor: col('accent'), borderRadius: mm(1.5),
      padding: { top: mm(0.6), bottom: mm(0.4), left: mm(2.4), right: mm(2.4) } },
    placement: { anchor: { to: 'container', edge: 'top-left' },
      offset: { x: mm(0), y: mm(BAND - 20 + 3) } } },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: LABEL, fontSize: pt(30),
    fontWeight: 700, color: col('ink'), align: 'left',
    placement: { anchor: { to: '#unit', edge: 'right-of' }, offset: { x: mm(4), y: mm(-5) } } },
] } };
// #endregion

// Folios at the foot's outer corner: running heads stay physical, so each side is named.
const foot = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: LABEL, fontSize: pt(9), color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(-11) } }, ...extra });
const footer = { elements: [
  foot('folio-v', '{pageNumber}', 'even', 'bottom-left', 16,
    { fontWeight: 700, color: col('accent') }),
  foot('title-v', '{title}', 'even', 'bottom-left', 24),
  foot('folio-r', '{pageNumber}', 'odd', 'bottom-right', -16,
    { fontWeight: 700, color: col('accent'), align: 'right' }),
  foot('title-r', '{chapterTitle}', 'odd', 'bottom-right', -24, { align: 'right' }),
] };

let edition = {}; // what the second build below changes: the Maghreb edition's locale
const config = () => ({
  locale: 'ar', // the Mashriq edition: ١ ٢ ٣
  colorPalette,
  exerciseStyles: [tamrin],
  exercises,
  page: { sizePreset: 'custom', width: mm(170), height: mm(240), dpi: 150,
    margins: { top: mm(20), bottom: mm(20), left: mm(18), right: mm(16), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: TEXT, fontSize: pt(13), lineHeight: pt(22), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'justify', firstLineIndent: pt(0), hyphenation: { enabled: false },
    avoidWidows: true, avoidOrphans: true },
  headings: { fontFamily: LABEL, color: col('ink'), fontWeight: 700,
    balancing: { enabled: false },
    levels: [{ level: 1, fontSize: pt(30), breakBefore: { parity: 'any' },
      advancedDesign: opener }] },
  orderedLists: { numberFormat: 'arabic', color: col('ink'), fontWeight: 700 },
  paragraphStyles: [
    { id: 'ism', fontFamily: LABEL, fontSize: pt(11), color: col('muted'), firstLineIndent: pt(0),
      textAlign: 'left', marginBottom: mm(3) },
    { id: 'colophon', fontFamily: LABEL, fontSize: pt(8), lineHeight: pt(13), color: col('muted'),
      textAlign: 'left', firstLineIndent: pt(0), marginTop: mm(6) },
  ],
  chipStyles: [{ id: 'khatt', backgroundEnabled: false, underline: 'dotted', borderWidth: pt(1),
    borderColor: col('muted'), minWidth: mm(26), paddingX: pt(0), paddingY: pt(0) }],
  calloutStyles: [
    { id: 'sunduq', background: col('sand'), border: { enabled: true, color: col('accent'),
      width: pt(1), style: 'dashed' }, borderRadius: mm(2.5),
    padding: { top: mm(2), right: mm(4), bottom: mm(2.5), left: mm(4) },
    body: { fontFamily: LABEL, fontSize: pt(12), textAlign: 'center' },
    marginTop: mm(1.5), marginBottom: mm(2.5) },
    { id: 'hulul', background: col('sand'), borderRadius: mm(2),
      stripe: { enabled: true, side: 'left', width: pt(3), color: col('leaf') },
      padding: { top: mm(3), right: mm(4), bottom: mm(3.5), left: mm(4) },
      titleStyle: { fontFamily: LABEL, fontSize: pt(13), fontWeight: 700, color: col('leaf') },
      body: { fontSize: pt(11), lineHeight: pt(19), color: col('ink'), firstLineIndent: pt(0) },
      marginTop: mm(6), marginBottom: mm(2), keepTogether: false },
  ],
  header: { elements: [] },
  footer,
  ...edition,
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "كراسة التمارين · الصف الثاني"
---

# في الحديقة {kicker="الوحدة الثالثة" pic="garden"}

:::paragraphs{style="ism"}
الاسم: :chip[ ]{style="khatt"}  الصف: :chip[ ]{style="khatt"}  التاريخ: :chip[ ]{style="khatt"}
:::

:::exercise{columns=3}
اخترِ الإجابة الصحيحة.

1. تحتاج النبتة كي تنمو إلى:
   - [ ] الحجارة
   - [x] الماء
   - [ ] الرمل
2. نسقي الحديقة في الصباح الباكر لأنّ الشمس فيه:
   - [x] ليست حارّة
   - [ ] شديدة الحرارة
   - [ ] غائبة
3. يصنع النحل العسل من:
   - [ ] أوراق الشجر
   - [ ] حبّات التراب
   - [x] رحيق الأزهار
:::

:::exercise
صِلْ كلّ كلمة في العمود الأول بما يناسبها في العمود الثاني.

- النحلة -> تصنع العسل
- الشمس -> تمنح الضوء والدفء
- الجذور -> تمتصّ الماء من التربة
- الفراشة -> تنتقل من زهرة إلى زهرة
:::

:::exercise{bank}
أكمِلِ الفراغ بالكلمة المناسبة من الصندوق.

زرعت سلمى بذرة [[الليمون]] في أصيص صغير، ووضعته قرب [[النافذة]] حتى يصله الضوء، وصارت [[تسقيه]] كلّ يومين. وبعد أسبوعين ظهرت ورقتان [[خضراوان]].

::bank[الملح | السيّارة]
:::

:::exercise{type=truefalse}
ضع علامة في المربّع المناسب.

- [x] تصنع النحلة العسل من رحيق الأزهار.
- [ ] تنمو شجرة الليمون في يوم واحد.
- [x] الجذور تثبّت النبتة في التربة.
- [ ] نسقي النباتات بالحليب.
:::

:::exercise{type=scramble}
رتّبِ الكلمات لتكوّن جملة مفيدة، ثمّ اكتبها على السطر.

- تسقي / سلمى / الأزهار / في / الصباح
- يحمل / خالد / أصيص / النعناع
:::

:::exercise{type=wordsearch size=8}
ابحث في الشبكة عن أسماء الأشياء التي نراها في الحديقة، ثمّ لوّنها.

- شجرة
- زهرة
- تربة
- بذرة
- ورقة
- نحلة
- غصن
:::

:::solutions

:::paragraphs{style="colophon"}
الحروف: Noto Naskh Arabic وBaloo Bhaijaan 2 (رخصة SIL OFL) · الرسم: مولَّد بنماذج الانتشار · التمارين: نصّ أصليّ للكتاب (CC BY 4.0)
:::
`; // content.ar.md: one text for both editions

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = {
  'Noto Naskh Arabic': ['400', '700'], // the text, the word search's letters
  'Baloo Bhaijaan 2': ['400', '700'], // instructions, numbers, the title
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
await loadFonts(FONTS, markdown);
// Each Arabic face's letters live in a file of their own (gotcha: arabic-fonts-subset).
await loadArabicFonts(FONTS, markdown);
await loadImage('garden-1600.jpg', asset('garden-1600.jpg'));
const resources = [{ id: 'garden', typeId: 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: 'garden-1600.jpg', format: 'jpeg', width: 1600, height: 667 } }];
// #region editions: one text, two editions: Mashriq digits, then Maghreb digits
// Both are bound on the right and read from the right; only the locale changes.
const build = () => withLoadedFonts(() => buildDocument({ markdown, resources }, config()),
  { ...kitFonts(FONTS), text: markdown });
const mashriq = await build();
edition = { locale: 'ar-MA' }; // the same book for Morocco: European digits, still right to left
const docs = [mashriq, await build()];
// #endregion
showBook(docs, { title: t({ ar: 'كراسة تمارين عربية', en: 'An Arabic workbook, right to left',
  es: 'Un cuaderno de ejercicios árabe, de derecha a izquierda' }) });
offerPdf(() => renderToPdf(docs, { fontProvider: arabicPdfProvider, resourceBytes: imageBytes }),
  `${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 · 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 · book v1 ── books bound on either edge · postext.dev/cookbook
// A book bound on the right (Arabic, Hebrew or Persian text, vertical
// Chinese, or page.binding 'right') opens from what a Latin reader calls
// the back: page 1 lies alone on the left of the spine, then [3 | 2].

/** showPages for a book bound on either edge. A right-bound book (the
 *  document says so: doc.binding is 'right' for page.binding 'right', for
 *  text that runs right to left and for vertical text, when the binding is
 *  left to 'auto') 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-book')) {
    // The pages keep direction ltr, as in a left-bound book: a canvas takes
    // the direction its element inherits, and under the spread's rtl a run
    // painted for an ltr canvas would end where the engine starts it.
    document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit-book">
      .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 ───────────────────────────────────────────────────────────────────────
```

## Varianten

### Das Lehrerheft drucken

Die Antworten stehen dann an ihrem Platz, in der Farbe von `answers`: die Punkte verbunden, die Wörter in ihren Lücken, die richtigen Kästchen gefüllt und die Wörter im Gitter eingekreist.

```diff
-const exercises = { solutions: { placement: 'directive' } };
+const exercises = { edition: 'teacher', solutions: { placement: 'none' } };
```

### Die Übungen auf Chinesisch schreiben

[Das chinesische Übungsheft](https://postext.dev/de/cookbook/chinese-exercise-book.md) setzt dieselben Übungsarten mit eigenen Klammern und Zahlzeichen.

## Häufige Fehler

- **Zeichnen Sie ein arabisches Buch mit 'ar' aus, nicht mit LANG.** Die Ausgaben eines Rezepts sind en und es, ein arabisches Beispiel ist aber in beiden Arabisch: `locale: LANG` würde es von links nach rechts setzen, links binden, seine Seiten 1 2 3 nummerieren und seine Abbildungen mit Figure oder Figura beschriften. Seit postext 1.30 ist die Auszeichnung auch die Sprache, in der der Text geformt wird (gemessen, gezeichnet und eingebettet). Unter einer englischen oder spanischen Auszeichnung zeichnet eine Schrift wie Markazi Text daher die arabischen Formen ihrer Guillemets und Satzzeichen nicht, und die Zeilen brechen an anderer Stelle um. Schreiben Sie die Auszeichnung selbst: 'ar' (arabisch-indische Ziffern, die Maschrek-Konvention), eine Region wie 'ar-EG' oder 'ar-SA', oder 'ar-MA', 'ar-DZ' bzw. 'ar-TN' für eine Maghreb-Ausgabe mit europäischen Ziffern. Eine lateinische Seite, die Arabisch nur zitiert, behält ihr eigenes Gebietsschema.
- **Arabische Schnitte brauchen ihre arabic-Datei, über den Block arabic.** Fontsource liefert Amiri, Noto Naskh Arabic oder Scheherazade New als eine Datei pro Teilmenge aus, und die arabischen Buchstaben stehen in der Datei arabic. loadFonts holt nur latin (und latin-ext), am Bildschirm stammt das Arabische also aus einer Systemschrift und wird falsch gemessen, und fontsourceProvider gibt dem PDF diese latin-Datei, die leere Kästchen druckt. Führen Sie den Kit-Block arabic auf, rufen Sie loadArabicFonts(FONTS, markdown) nach loadFonts auf, mit jeder Schriftstärke, die die Seiten auf Arabisch setzen, in FONTS aufgeführt, und geben Sie renderToPdf fontProvider: arabicPdfProvider.

- Die meisten arabischen Schriften haben weder ✓ noch ✗: Richtig und falsch heißen صح und خطأ, und die Aufgabe verlangt ein Zeichen im Kästchen.
- Der Buchstabensalat füllt seine leeren Felder mit den Buchstaben seiner eigenen Wörter, in ihrer isolierten Form. Wählen Sie Wörter mit verschiedenen Buchstaben, sonst füllt sich das Gitter mit ة.

## Nachweise

- Rezept: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Bilder: A school garden in an Arab town: date palms, a fountain, lemon trees, a girl watering plants and a boy carrying a pot of mint.: Generated With Diffusion Models, Original
- Schrift: Noto Naskh Arabic (OFL-1.1), Baloo Bhaijaan 2 (OFL-1.1)
- Code: MIT · Beispielinhalt: CC-BY-4.0

## Verwandte Rezepte

- [Nº 161 · Schreiblernheft in zehn Schulschriften](https://postext.dev/de/cookbook/handwriting-workbook.md): Ein erstes Schreibheft in jeder Sprache der Website: die Schulschrift jedes Landes auf seiner Lineatur, eine Vorlage, Punkte zum Nachspuren und leere Zeilen. · Stufe 2 (Mittel) · Arbeitshefte und Übungen, Lehrbücher
- [Nº 109 · Arabischer Text für den Maghreb mit europäischen Ziffern](https://postext.dev/de/cookbook/maghreb-edition-european-digits.md): Ein arabisches Kapitel für Marokko: Die Locale „ar-MA“ hält den Text rechts nach links und rechts gebunden und schreibt jede erzeugte Zahl als 1, 2, 3. · Stufe 1 (Einfach) · Handbücher und Nachschlagewerke
- [Nº 171 · Ein chinesisches Übungsheft für Kinder und Lehrkraft](https://postext.dev/de/cookbook/chinese-exercise-book.md): Ein 练习册 für Chinesisch und Mathe: Abschnitte 一、二、, Klammern （　）, 田字格 und schriftliches Rechnen, zweimal aus einem Text gesetzt, für Kinder und Lehrkraft. · Stufe 2 (Mittel) · Arbeitshefte und Übungen, Lehrbücher
