# اثنتا عشرة لغة سيريلية في نموذج طباعي

> نموذج طباعي في أربع صفحات: مادة واحدة باثنتي عشرة لغة سيريلية، تُقطَّع كل منها بقواعدها وتُرسم بأشكال حروفها المحلية.

- نسخة HTML: https://postext.dev/ar/cookbook/cyrillic-specimen-twelve-languages
- وصفة رقم 209 · الحروف والنص · المستوى 2 (متوسط) · المخرجات: Canvas, PDF
- الأنواع: الكتالوجات
- تتطلب postext ≥ 1.100.0, postext-pdf ≥ 1.100.0 · اختُبرت مع 1.100.0, postext-pdf 1.100.0 بتاريخ 2026-12-02
- الصفحات: [1](https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/en/p01.webp?v=5029f9ce), [2](https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/en/p02.webp?v=5029f9ce), [3](https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/en/p03.webp?v=5029f9ce), [4](https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/en/p04.webp?v=5029f9ce)
- افتح في Sandbox: https://postext.dev/ar/sandbox#recipe=cyrillic-specimen-twelve-languages&lang=en (.postext: https://postext.dev/cookbook/cyrillic-specimen-twelve-languages/en/cyrillic-specimen-twelve-languages.postext)
- آخر تحديث: 2026-12-02
- لغات أخرى: [en](https://postext.dev/en/cookbook/cyrillic-specimen-twelve-languages.md), [es](https://postext.dev/es/cookbook/cyrillic-specimen-twelve-languages.md), [ca](https://postext.dev/ca/cookbook/cyrillic-specimen-twelve-languages.md), [de](https://postext.dev/de/cookbook/cyrillic-specimen-twelve-languages.md), [el](https://postext.dev/el/cookbook/cyrillic-specimen-twelve-languages.md), [fr](https://postext.dev/fr/cookbook/cyrillic-specimen-twelve-languages.md), [it](https://postext.dev/it/cookbook/cyrillic-specimen-twelve-languages.md), [pt](https://postext.dev/pt/cookbook/cyrillic-specimen-twelve-languages.md), [ru](https://postext.dev/ru/cookbook/cyrillic-specimen-twelve-languages.md), [zh](https://postext.dev/zh/cookbook/cyrillic-specimen-twelve-languages.md), [ja](https://postext.dev/ja/cookbook/cyrillic-specimen-twelve-languages.md)

## باختصار

صفحة نماذج كالتي تصدرها مسابك الحروف، فيها المادة نفسها باثنتي عشرة لغة تُكتب بالسيريلية، من الروسية إلى المنغولية. يقسم كل نص كلماته بقواعد لغته، وتُظهر البلغارية والصربية والمقدونية الحروف التي ترسمها بشكل مختلف.

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

نموذج قياسه 205 × 260 مم في أربع صفحات. الغلاف جدار من اثنتي عشرة بلاطة، في كل منها حرف يميّز إحدى الأبجديات. وفي صفحتين متقابلتين اثنتا عشرة بطاقة: ست لغات سلافية على اليسار، والكازاخية والقرغيزية والتتارية والبشكيرية والطاجيكية والمنغولية على اليمين. في كل بطاقة اسم اللغة، وحروفها الخاصة بالأحمر الزنجفري، والمادة الأولى من الإعلان العالمي لحقوق الإنسان في أعمدة مضبوطة الجانبين، وبيت لأحد كتّاب اللغة، ثم الأبجدية. وتعرض الصفحة الأخيرة الأشكال المحلية بحجم كبير، وكلمة «مكتبة» مقسّمة في اللغات الاثنتي عشرة.

**تجيب هذه الوصفة عن:**

- كيف أنضد عدة لغات سيريلية في مستند واحد، لكل منها تقطيعها وأشكال حروفها؟
- كيف أحصل على ضبط أسطر وتقسيم كلمات جيدين لنص إسباني أو فرنسي أو ألماني؟

## الجواب المختصر

```js
// script.js, سطرًا 40–62
// The document is Russian, so that is what divides and shapes anything left unnamed. A
// passage names its language on its container:
//   :::paragraphs{style="article" lang=bg}
// Its words are divided by Bulgarian patterns and kept together by Bulgarian rules; it is
// measured, painted and embedded with the Bulgarian forms (locl) the font holds, and tagged
// as Bulgarian in the HTML and the PDF. A run inside a line takes :ltr[…]{lang=bg}.
const LOCALE = 'ru';
const bodyText = { // config().bodyText
  fontFamily: SERIF, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  textAlign: 'justify', firstLineIndent: pt(0),
  // 54 mm hold about 32 letters: words are divided at two letters, the spaces give from
  // 0.75 to 1.8 of the face's own, and a line takes up to 20 ‰ of tracking.
  hyphenation: { leftMin: 2, rightMin: 2 }, minWordSpacing: 0.75, maxWordSpacing: 1.8,
  maxJustifyTracking: 20, shapingLanguage: 'document', // the default: locale, then lang
};
const passages = [ // config().paragraphStyles
  { id: 'article', firstLineIndent: pt(0), marginBottom: pt(LEAD / 2) },
  { id: 'line', fontSize: pt(11.2), lineHeight: pt(LEAD), textAlign: 'left',
    italicColor: col('red'), hyphenation: { enabled: false }, marginBottom: pt(LEAD / 2) },
  { id: 'abc', ...face(SANS, 8.4, 400, 'muted'), lineHeight: pt(11.4), textAlign: 'left',
    hyphenation: { enabled: false } },
];
```

## المكونات

**تعلّم**

- [اللغات الكيريلية لغةً للمستند](https://postext.dev/ar/docs/cyrillic-layout.md#البدء-بكتاب-بالسيريلية): تعطي locale 'ru' أو 'uk' أو 'be' أو 'bg' أو 'sr' أو 'mk' أو 'kk' أو 'ky' أو 'tt' أو 'ba' أو 'tg' أو 'mn' الكتابَ ما تقتضيه لغته من تقسيم الكلمات والتعليقات وعناوين الجداول والحواشي والأعداد بالحروف وقياسات الطبق واتجاه كتابة الكعب.
- [تقسيم الكلمات ولغة المستند](https://postext.dev/ar/docs/justification.md#اللغات-المدعومة): تقسيم الكلمات بالواصلة وفق أنماط TeX في إحدى وعشرين لغة منها اليونانية ولغات الأبجدية الكيريلية، تُختار بحسب لغة المستند (locale)، التي تحدّد أيضًا عبارات استمرار الجداول ولغة PDF الموسوم.
- [مقاطع بالاتجاه المعاكس](https://postext.dev/ar/docs/arabic-layout.md#العوازل): يعزل :rtl[…] و:ltr[…] مقطعًا من الاتجاه الآخر داخل السطر (اسم منتج لاتيني في نص عربي، أو عنوان عربي في جملة إنجليزية)، مع سمة lang اختيارية؛ وتعمل محارف العزل U+2066–2069 المكتوبة في النص بالطريقة نفسها.

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

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

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

- [`bodyText`](https://postext.dev/ar/docs/configuration-text.md#نص-المتن), [`characterStyles`](https://postext.dev/ar/docs/configuration-styles.md#أنماط-الحروف), [`colorPalette`](https://postext.dev/ar/docs/configuration-fonts-colors-viewers.md#لوحة-الألوان), [`footer`](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات), [`header`](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات), [`headingStyles`](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين), [`headings`](https://postext.dev/ar/docs/configuration-headings.md#العناوين), [`layout`](https://postext.dev/ar/docs/configuration-page-layout.md#التخطيط), [`locale`](https://postext.dev/ar/docs/configuration-language.md#تقسيم-الكلمات-بالواصلة), [`page`](https://postext.dev/ar/docs/configuration-page-layout.md#الصفحة), [`paragraphStyles`](https://postext.dev/ar/docs/configuration-styles.md#أنماط-الفقرات)

**واجهات API**

- [`buildDocumentWithFonts`](https://postext.dev/ar/docs/configuration-programmatic-usage.md#تحميل-الخطوط-قبل-الإخراج), [`decompressWoff2`](https://postext.dev/ar/docs/configuration-pdf-output.md#مزوّد-الخطوط-في-المتصفح-fontsource--woff2), [`renderPageToCanvas`](https://postext.dev/ar/docs/configuration-programmatic-usage.md#رسم-صفحة-في-صورة-نقطية), [`renderToPdf`](https://postext.dev/ar/docs/configuration-pdf-output.md#توليد-ملفات-pdf)

**الخطوط**

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

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

### 1 · سمِّ لغة كل نص مرتين

الشيفرة هي [الجواب المختصر](https://postext.dev/ar/cookbook/cyrillic-specimen-twelve-languages.md#الجواب-المختصر) أعلاه. يُسمّي `lang` في كتلة `:::paragraphs` لغة نصها: فيختار [الأنماط التي تقسم كلماتها](https://postext.dev/ar/docs/cyrillic-layout.md#تقسيم-الكلمات-في-اثنتي-عشرة-لغة)، ويُقاس النص ويُرسم ويُضمَّن بالأشكال التي يحفظها الخط لتلك اللغة، ويُوسم بها في PDF وHTML. أما المقطع داخل السطر فيأخذ عزلًا `:ltr[…]{lang=bg}`. عرض الأعمدة 54 مم، لذلك يجوز التقسيم بعد حرفين ويقبل السطر حتى 20 ‰ من التباعد.

### 2 · عنوان واحد وأربعة بيانات

```js
// script.js, سطرًا 66–80
// ## Українська {code="uk" letters="33 буквы" special="Ґ Є І Ї"}
const entry = { level: 2, fontFamily: SERIF, fontSize: pt(21), lineHeight: pt(26), fontWeight: 900,
  marginTop: pt(0), marginBottom: pt(LEAD / 4),
  advancedDesign: { enabled: true, minHeight: mm(25.4), slot: { elements: [
    { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(2.5), color: col('ink'),
      placement: { ...at('container', 'top-left'), size: { width: 'fill' } } },
    text('code', '{attr.code}', face(SANS, 8, 700, 'red', { textTransform: 'uppercase',
      letterSpacing: pt(1.2) }), at('container', 'top-left', 0, 2.6)),
    text('count', '{attr.letters}', face(SANS, 8, 400, 'muted', { align: 'right' }),
      at('container', 'top-right', 0, 2.6)),
    text('name', '{titleText}', face(SERIF, 22, 900, 'ink', { lineHeight: 1.1 }),
      at('container', 'top-left', 0, 6.6)),
    text('special', '{attr.special}', face(SERIF, 17, 700, 'red', { lineHeight: 1.2 }),
      at('container', 'top-left', 0, 18)),
  ] } } };
```

ينتقل رمز اللغة وعدد حروفها والحروف التي لا توجد في الروسية في العنوان: `## Українська {code="uk" letters="33 буквы" special="Ґ Є І Ї"}`. يطبعها التصميم تحت خط سميك، ويمنح `minHeight` جميع البطاقات رأسًا متساويًا، فتبدأ نصوص الصف الواحد على سطر واحد.

### 3 · جدار من الحروف

```js
// script.js, سطرًا 94–113
const [TILE_W, TILE_H] = [TRIM_W / 3, 52]; // mm
const INKS = ['red', 'ink', 'ochre', 'pine', 'cream', 'red', 'ink', 'ochre', 'pine', 'red', 'ink',
  'cream']; // ink of each tile, row by row
const tile = (ink, i) => {
  const place = { ...at('page', 'top-left', (i % 3) * TILE_W, Math.floor(i / 3) * TILE_H),
    size: { width: mm(TILE_W), height: mm(TILE_H) } };
  const letter = ink === 'cream' ? 'red' : ink === 'ochre' ? 'ink' : 'cream';
  return [{ kind: 'box', id: `tile-${i}`, style: { backgroundColor: col(ink) }, placement: place },
    text(`letter-${i}`, `{attr.l${i + 1}}`, face(SERIF, 108, 900, letter, { align: 'center',
      verticalAlign: 'center', lineHeight: 1 }), place)];
};
const cover = { id: 'cover', breakBefore: { enabled: true, parity: 'any' },
  header: { elements: [] }, footer: { elements: [] },
  advancedDesign: { enabled: true, minHeight: mm(200), slot: { elements: [
    ...INKS.flatMap(tile),
    text('title', '{titleText}', face(SERIF, 40, 900, 'ink', { lineHeight: 1.05, align: 'left' }),
      { ...at('page', 'top-left', SIDE, 4 * TILE_H + 10), size: { width: mm(TRIM_W - 2 * SIDE) } }),
    text('subtitle', '{subtitle}', face(SANS, 13, 400, 'muted', { lineHeight: 1.3, align: 'left' }),
      { ...at('#title', 'below', 0, 2), size: { width: 'fill' } }),
  ] } } };
```

حروف الغلاف الاثنا عشر هي الخصائص `l1` إلى `l12` في عنوانه، ويبني التصميم لكل حرف صندوقًا ونصًا من قائمة أحبار. ولتغيير حرف يكفي تغيير Markdown. توضع البلاطات من زاوية الصفحة وتصل إلى حد القص.

### 4 · الأشكال المحلية سطرًا بعد سطر

```js
// script.js, سطرًا 117–127
const tabs = (...at) => at.map((x) => ({ position: mm(x), align: 'start' }));
const formsStyles = [ // config().paragraphStyles
  { id: 'forms', fontSize: pt(29), lineHeight: pt(3 * LEAD), textAlign: 'left',
    tabStops: tabs(26, 78), hyphenation: { enabled: false } },
  { id: 'weights', fontSize: pt(15.5), lineHeight: pt(2 * LEAD), textAlign: 'left',
    hyphenation: { enabled: false } },
  { id: 'cuts', fontSize: pt(12), lineHeight: pt(1.5 * LEAD), textAlign: 'left', tabStops: tabs(22),
    hyphenation: { enabled: false } },
  { id: 'colophon', ...face(SANS, 7.8, 400, 'muted'), lineHeight: pt(11), textAlign: 'left',
    marginTop: pt(3 * LEAD), hyphenation: { locale: LANG, enabled: false } },
];
```

تمر السلسلة نفسها في الخط بالروسية ثم بالبلغارية؛ وبالمائل بالروسية والصربية والمقدونية. في Source Serif 4 المجموعات الثلاث. تصف علامات الجدولة السطور، وكل سطر عزل بلغته. وتجد في [التوكيد والأشكال المحلية](https://postext.dev/ar/docs/cyrillic-layout.md#التوكيد-والنبر-والشعر) الحروف التي تتغير.

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

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

- مجلد الوصفة: https://github.com/drnachio/postext/tree/main/cookbook/cyrillic-specimen-twelve-languages

### script.js

```js
// ═══ Postext Cookbook · Nº 209 · Twelve Cyrillic languages in one type specimen ═══════
// https://postext.dev/en/cookbook/cyrillic-specimen-twelve-languages
// Code: MIT · Text: UDHR, article 1 (UN, PD) and lines by twelve authors (PD) · Pictures: none
// Fonts: Source Serif 4, Source Sans 3 (SIL OFL 1.1) · Needs postext ≥ 1.100.0
import { buildDocumentWithFonts, renderPageToCanvas } from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the colophon ('en' | 'es' | 'ru')
const RECIPE = 'cyrillic-specimen-twelve-languages';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// The sheet of a type foundry between the wars: black, vermilion and two dull inks on cream.
const palette = {
  ink: '#1d1b1a', // text, heavy rules, the dark tiles
  red: '#b8321e', // the letters Russian lacks, the plates' titles, red tiles
  pine: '#1f4b4a', // green tiles
  ochre: '#d59b3a', // ochre tiles
  cream: '#f6efdf', // the paper and the letters on the tiles
  muted: '#655d51', // alphabets, author names, the colophon
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = Object.entries({ ...palette, 'main-color': palette.red })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const [SERIF, SANS] = ['Source Serif 4', 'Source Sans 3']; // both draw local forms by language
const [BODY, LEAD] = [10.5, 14]; // pt
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const text = (id, content, look, placement) => ({ kind: 'text', id, content, overflow: 'wrap',
  ...look, placement });
const face = (fontFamily, size, fontWeight, color, extra = {}) => ({ fontFamily,
  fontSize: pt(size), fontWeight, color: col(color), ...extra });

// #region page: 84 × 108/16, 205 × 260 mm trimmed, three columns to a plate
const [TRIM_W, SIDE] = [205, 15]; // mm
const page = { sizePreset: '84x108/16', dpi: 150, backgroundColor: col('cream'),
  margins: { top: mm(18), bottom: mm(17), left: mm(SIDE), right: mm(SIDE), mirror: true } };
const COLUMN_GAP = 6; // mm
// #endregion

// #region answer: each passage named in its own language, for its breaks and its letters
// The document is Russian, so that is what divides and shapes anything left unnamed. A
// passage names its language on its container:
//   :::paragraphs{style="article" lang=bg}
// Its words are divided by Bulgarian patterns and kept together by Bulgarian rules; it is
// measured, painted and embedded with the Bulgarian forms (locl) the font holds, and tagged
// as Bulgarian in the HTML and the PDF. A run inside a line takes :ltr[…]{lang=bg}.
const LOCALE = 'ru';
const bodyText = { // config().bodyText
  fontFamily: SERIF, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  textAlign: 'justify', firstLineIndent: pt(0),
  // 54 mm hold about 32 letters: words are divided at two letters, the spaces give from
  // 0.75 to 1.8 of the face's own, and a line takes up to 20 ‰ of tracking.
  hyphenation: { leftMin: 2, rightMin: 2 }, minWordSpacing: 0.75, maxWordSpacing: 1.8,
  maxJustifyTracking: 20, shapingLanguage: 'document', // the default: locale, then lang
};
const passages = [ // config().paragraphStyles
  { id: 'article', firstLineIndent: pt(0), marginBottom: pt(LEAD / 2) },
  { id: 'line', fontSize: pt(11.2), lineHeight: pt(LEAD), textAlign: 'left',
    italicColor: col('red'), hyphenation: { enabled: false }, marginBottom: pt(LEAD / 2) },
  { id: 'abc', ...face(SANS, 8.4, 400, 'muted'), lineHeight: pt(11.4), textAlign: 'left',
    hyphenation: { enabled: false } },
];
// #endregion

// #region entry: a heavy rule, the language's name and the letters Russian lacks
// ## Українська {code="uk" letters="33 буквы" special="Ґ Є І Ї"}
const entry = { level: 2, fontFamily: SERIF, fontSize: pt(21), lineHeight: pt(26), fontWeight: 900,
  marginTop: pt(0), marginBottom: pt(LEAD / 4),
  advancedDesign: { enabled: true, minHeight: mm(25.4), slot: { elements: [
    { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(2.5), color: col('ink'),
      placement: { ...at('container', 'top-left'), size: { width: 'fill' } } },
    text('code', '{attr.code}', face(SANS, 8, 700, 'red', { textTransform: 'uppercase',
      letterSpacing: pt(1.2) }), at('container', 'top-left', 0, 2.6)),
    text('count', '{attr.letters}', face(SANS, 8, 400, 'muted', { align: 'right' }),
      at('container', 'top-right', 0, 2.6)),
    text('name', '{titleText}', face(SERIF, 22, 900, 'ink', { lineHeight: 1.1 }),
      at('container', 'top-left', 0, 6.6)),
    text('special', '{attr.special}', face(SERIF, 17, 700, 'red', { lineHeight: 1.2 }),
      at('container', 'top-left', 0, 18)),
  ] } } };
// #endregion

// #region plate: the band over a page of six languages
const plate = { id: 'plate', breakBefore: { enabled: true, parity: 'any' }, marginBottom: pt(LEAD),
  advancedDesign: { enabled: true, minHeight: mm(20), slot: { elements: [
    text('title', '{titleText}', face(SERIF, 27, 900, 'red', { lineHeight: 1.1, align: 'left' }),
      { ...at('container', 'top-left'), size: { width: 'fill' } }),
    text('lead', '{attr.lead}', face(SANS, 10.5, 400, 'ink', { lineHeight: 1.3, align: 'left' }),
      { ...at('#title', 'below', 0, 1.5), size: { width: 'fill' } }),
  ] } } };
// #endregion

// #region cover: twelve letters, one from each alphabet, on a wall of tiles
const [TILE_W, TILE_H] = [TRIM_W / 3, 52]; // mm
const INKS = ['red', 'ink', 'ochre', 'pine', 'cream', 'red', 'ink', 'ochre', 'pine', 'red', 'ink',
  'cream']; // ink of each tile, row by row
const tile = (ink, i) => {
  const place = { ...at('page', 'top-left', (i % 3) * TILE_W, Math.floor(i / 3) * TILE_H),
    size: { width: mm(TILE_W), height: mm(TILE_H) } };
  const letter = ink === 'cream' ? 'red' : ink === 'ochre' ? 'ink' : 'cream';
  return [{ kind: 'box', id: `tile-${i}`, style: { backgroundColor: col(ink) }, placement: place },
    text(`letter-${i}`, `{attr.l${i + 1}}`, face(SERIF, 108, 900, letter, { align: 'center',
      verticalAlign: 'center', lineHeight: 1 }), place)];
};
const cover = { id: 'cover', breakBefore: { enabled: true, parity: 'any' },
  header: { elements: [] }, footer: { elements: [] },
  advancedDesign: { enabled: true, minHeight: mm(200), slot: { elements: [
    ...INKS.flatMap(tile),
    text('title', '{titleText}', face(SERIF, 40, 900, 'ink', { lineHeight: 1.05, align: 'left' }),
      { ...at('page', 'top-left', SIDE, 4 * TILE_H + 10), size: { width: mm(TRIM_W - 2 * SIDE) } }),
    text('subtitle', '{subtitle}', face(SANS, 13, 400, 'muted', { lineHeight: 1.3, align: 'left' }),
      { ...at('#title', 'below', 0, 2), size: { width: 'fill' } }),
  ] } } };
// #endregion

// #region forms: the same letters at display size, each row in its own language
const tabs = (...at) => at.map((x) => ({ position: mm(x), align: 'start' }));
const formsStyles = [ // config().paragraphStyles
  { id: 'forms', fontSize: pt(29), lineHeight: pt(3 * LEAD), textAlign: 'left',
    tabStops: tabs(26, 78), hyphenation: { enabled: false } },
  { id: 'weights', fontSize: pt(15.5), lineHeight: pt(2 * LEAD), textAlign: 'left',
    hyphenation: { enabled: false } },
  { id: 'cuts', fontSize: pt(12), lineHeight: pt(1.5 * LEAD), textAlign: 'left', tabStops: tabs(22),
    hyphenation: { enabled: false } },
  { id: 'colophon', ...face(SANS, 7.8, 400, 'muted'), lineHeight: pt(11), textAlign: 'left',
    marginTop: pt(3 * LEAD), hyphenation: { locale: LANG, enabled: false } },
];
// #endregion

const folio = (parity, edge, x) => text(`folio-${parity}`, '{pageNumber}',
  face(SANS, 9, 700, 'ink', { parity }), at('page', edge, x, -9));
const config = () => ({
  locale: LOCALE, // written out, never LANG: the specimen is Russian in every edition
  colorPalette, page, bodyText,
  layout: { layoutType: 'single', gutterWidth: mm(COLUMN_GAP),
    columnRule: { enabled: false, color: col('muted'), lineWidth: pt(0.5) } },
  headings: { fontFamily: SERIF, fontWeight: 900, color: col('ink'), levels: [
    { level: 1, breakBefore: { enabled: true, parity: 'any' } }, entry,
    { level: 3, fontFamily: SANS, fontSize: pt(11), lineHeight: pt(LEAD), fontWeight: 700,
      color: col('red'), marginTop: pt(LEAD), marginBottom: pt(0) },
  ] },
  headingStyles: [cover, plate],
  paragraphStyles: [...passages, ...formsStyles],
  characterStyles: [
    { id: 'who', ...face(SANS, 8.4, 400, 'muted') },
    { id: 'black', fontWeight: 900 },
    { id: 'tag', ...face(SANS, 9, 400, 'muted') },
  ],
  header: { elements: [] },
  footer: { elements: [folio('even', 'bottom-left', SIDE), folio('odd', 'bottom-right', -SIDE)] },
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The specimen (content.text.<lang>.md), then its colophon in the edition's language.
const markdown = [String.raw`---
title: "Двенадцать кириллиц"
subtitle: "Образцы шрифта для набора на двенадцати языках"
---

# Двенадцать кириллиц {style="cover" l1="Ж" l2="Ї" l3="Ў" l4="Ъ" l5="Ђ" l6="Ѓ" l7="Қ" l8="Ң" l9="Җ" l10="Ҙ" l11="Ӯ" l12="Ө"}

# Славянские языки {style="plate" lead="Статья 1 Всеобщей декларации прав человека с переносами по правилам каждого языка"}

:::columns{count=3 breaks="5,9" marginBottom="3em"}
## Русский {code="ru" letters="33 буквы" special="Ё Ъ Ы Э"}

:::paragraphs{style="article" lang=ru}
Все люди рождаются свободными и равными в своем достоинстве и правах. Они наделены разумом и совестью и должны поступать в отношении друг друга в духе братства.
:::

:::paragraphs{style="line" lang=ru}
*Мороз и солнце; день чудесный!*\
:span[А. С. Пушкин]{style="who"}
:::

:::paragraphs{style="abc" lang=ru}
Аа Бб Вв Гг Дд Ее Ёё Жж Зз Ии Йй Кк Лл Мм Нн Оо Пп Рр Сс Тт Уу Фф Хх Цц Чч Шш Щщ Ъъ Ыы Ьь Ээ Юю Яя
:::

## Українська {code="uk" letters="33 буквы" special="Ґ Є І Ї"}

:::paragraphs{style="article" lang=uk}
Всі люди народжуються вільними і рівними у своїй гідності та правах. Вони наділені розумом і совістю і повинні діяти у відношенні один до одного в дусі братерства.
:::

:::paragraphs{style="line" lang=uk}
*Реве та стогне Дніпр широкий*\
:span[Т. Г. Шевченко]{style="who"}
:::

:::paragraphs{style="abc" lang=uk}
Аа Бб Вв Гг Ґґ Дд Ее Єє Жж Зз Ии Іі Її Йй Кк Лл Мм Нн Оо Пп Рр Сс Тт Уу Фф Хх Цц Чч Шш Щщ Ьь Юю Яя
:::

## Беларуская {code="be" letters="32 буквы" special="І Ў Ё Э"}

:::paragraphs{style="article" lang=be}
Усе людзі нараджаюцца свабоднымі і роўнымі ў сваёй годнасці і правах. Яны надзелены розумам і сумленнем і павінны ставіцца адзін да аднаго ў духу брацтва.
:::

:::paragraphs{style="line" lang=be}
*А хто там ідзе, а хто там ідзе?*\
:span[Янка Купала]{style="who"}
:::

:::paragraphs{style="abc" lang=be}
Аа Бб Вв Гг Дд Ее Ёё Жж Зз Іі Йй Кк Лл Мм Нн Оо Пп Рр Сс Тт Уу Ўў Фф Хх Цц Чч Шш Ыы Ьь Ээ Юю Яя
:::
:::

:::columns{count=3 breaks="5,9" marginBottom="3em"}
## Български {code="bg" letters="30 букв" special="Ъ Щ Ю Я"}

:::paragraphs{style="article" lang=bg}
Всички хора се раждат свободни и равни по достойнство и права. Те са надарени с разум и съвест и следва да се отнасят помежду си в дух на братство.
:::

:::paragraphs{style="line" lang=bg}
*Тая прохладна майска вечер*\
:span[Иван Вазов]{style="who"}
:::

:::paragraphs{style="abc" lang=bg}
Аа Бб Вв Гг Дд Ее Жж Зз Ии Йй Кк Лл Мм Нн Оо Пп Рр Сс Тт Уу Фф Хх Цц Чч Шш Щщ Ъъ Ьь Юю Яя
:::

## Српски {code="sr" letters="30 букв" special="Ђ Ј Љ Њ Ћ Џ"}

:::paragraphs{style="article" lang=sr}
Сва људска бића рађају се слободна и једнака у достојанству и правима. Она су обдарена разумом и свешћу и треба једни према другима да поступају у духу братства.
:::

:::paragraphs{style="line" lang=sr}
*Пиши као што говориш*\
:span[Вук Караџић]{style="who"}
:::

:::paragraphs{style="abc" lang=sr}
Аа Бб Вв Гг Дд Ђђ Ее Жж Зз Ии Јј Кк Лл Љљ Мм Нн Њњ Оо Пп Рр Сс Тт Ћћ Уу Фф Хх Цц Чч Џџ Шш
:::

## Македонски {code="mk" letters="31 буква" special="Ѓ Ѕ Ј Љ Њ Ќ Џ"}

:::paragraphs{style="article" lang=mk}
Сите човечки суштества се раѓаат слободни и еднакви по достоинство и права. Тие се обдарени со разум и совест и треба да се однесуваат еден кон друг во духот на општо човечката припадност.
:::

:::paragraphs{style="line" lang=mk}
*Како на вратот ѓердани*\
:span[Кочо Рацин]{style="who"}
:::

:::paragraphs{style="abc" lang=mk}
Аа Бб Вв Гг Дд Ѓѓ Ее Жж Зз Ѕѕ Ии Јј Кк Лл Љљ Мм Нн Њњ Оо Пп Рр Сс Тт Ќќ Уу Фф Хх Цц Чч Џџ Шш
:::
:::

# От Казани до Улан-Батора {style="plate" lead="Тюркские языки, таджикский и монгольский: красным набраны буквы, которых нет в русском алфавите"}

:::columns{count=3 breaks="5,9" marginBottom="1em"}
## Қазақша {code="kk" letters="42 буквы" special="Ә Ғ Қ Ң Ө Ұ Ү Һ І"}

:::paragraphs{style="article" lang=kk}
Барлық адамдар тумысынан азат және қадір-қасиеті мен құқықтары тең болып дүниеге келеді. Адамдарға ақыл-парасат, ар-ождан берілген, сондықтан олар бір-бірімен туыстық, бауырмалдық қарым-қатынас жасаулары тиіс.
:::

:::paragraphs{style="line" lang=kk}
*Ғылым таппай мақтанба*\
:span[Абай]{style="who"}
:::

:::paragraphs{style="abc" lang=kk}
Аа Әә Бб Вв Гг Ғғ Дд Ее Ёё Жж Зз Ии Йй Кк Ққ Лл Мм Нн Ңң Оо Өө Пп Рр Сс Тт Уу Ұұ Үү Фф Хх Һһ Цц Чч Шш Щщ Ъъ Ыы Іі Ьь Ээ Юю Яя
:::

## Кыргызча {code="ky" letters="36 букв" special="Ң Ө Ү"}

:::paragraphs{style="article" lang=ky}
Бардык адамдар өз беделинде жана укуктарында эркин жана тең укуктуу болуп жаралат. Алардын аң-сезими менен абийири бар жана бири-бирине бир туугандык мамиле кылууга тийиш.
:::

:::paragraphs{style="line" lang=ky}
*Дайранын көркү кемеде*\
:span[Токтогул]{style="who"}
:::

:::paragraphs{style="abc" lang=ky}
Аа Бб Вв Гг Дд Ее Ёё Жж Зз Ии Йй Кк Лл Мм Нн Ңң Оо Өө Пп Рр Сс Тт Уу Үү Фф Хх Цц Чч Шш Щщ Ъъ Ыы Ьь Ээ Юю Яя
:::

## Татарча {code="tt" letters="39 букв" special="Ә Җ Ң Ө Ү Һ"}

:::paragraphs{style="article" lang=tt}
Барлык кешеләр дә азат һәм үз абруйлары һәм хокуклары ягыннан тиң булып туалар. Аларга акыл һәм вөҗдан бирелгән һәм бер-берсенә карата туганнарча мөнәсәбәттә булырга тиешләр.
:::

:::paragraphs{style="line" lang=tt}
*И туган тел, и матур тел*\
:span[Габдулла Тукай]{style="who"}
:::

:::paragraphs{style="abc" lang=tt}
Аа Әә Бб Вв Гг Дд Ее Ёё Жж Җҗ Зз Ии Йй Кк Лл Мм Нн Ңң Оо Өө Пп Рр Сс Тт Уу Үү Фф Хх Һһ Цц Чч Шш Щщ Ъъ Ыы Ьь Ээ Юю Яя
:::
:::

:::columns{count=3 breaks="5,9" marginBottom="1em"}
## Башҡортса {code="ba" letters="42 буквы" special="Ғ Ҙ Ҡ Ң Ө Ҫ Ү Һ Ә"}

:::paragraphs{style="article" lang=ba}
Барлыҡ кешеләр ирекле, дәрәжәләре һәм хоҡуҡтары тигеҙ булып тыуалар. Улар аҡыл һәм выждан эйәһе һәм бер-береһенә ҡарата ҡәрҙәшлек рухында хәрәкәт итергә тейештәр.
:::

:::paragraphs{style="line" lang=ba}
*Башҡорттарым, уҡыу кәрәк*\
:span[М. Аҡмулла]{style="who"}
:::

:::paragraphs{style="abc" lang=ba}
Аа Бб Вв Гг Ғғ Дд Ҙҙ Ее Ёё Жж Зз Ии Йй Кк Ҡҡ Лл Мм Нн Ңң Оо Өө Пп Рр Сс Тт Ҫҫ Уу Үү Фф Хх Һһ Цц Чч Шш Щщ Ъъ Ыы Ьь Ээ Әә Юю Яя
:::

## Тоҷикӣ {code="tg" letters="35 букв" special="Ғ Ӣ Қ Ӯ Ҳ Ҷ"}

:::paragraphs{style="article" lang=tg}
Тамоми одамон озод ва аз лиҳози шарафу ҳуқуқ ба ҳам баробар ба дунё меоянд. Онҳо соҳиби ақлу виҷдонанд ва бояд бо якдигар муносибати бародарона дошта бошанд.
:::

:::paragraphs{style="line" lang=tg}
*Бӯи ҷӯи Мӯлиён ояд ҳаме*\
:span[Рӯдакӣ]{style="who"}
:::

:::paragraphs{style="abc" lang=tg}
Аа Бб Вв Гг Ғғ Дд Ее Ёё Жж Зз Ии Ӣӣ Йй Кк Ққ Лл Мм Нн Оо Пп Рр Сс Тт Уу Ӯӯ Фф Хх Ҳҳ Чч Ҷҷ Шш Ъъ Ээ Юю Яя
:::

## Монгол {code="mn" letters="35 букв" special="Ө Ү"}

:::paragraphs{style="article" lang=mn}
Хүн бүр төрж мэндлэхэд эрх чөлөөтэй, адилхан нэр төртэй, ижил эрхтэй байдаг. Оюун ухаан, нандин чанар заяасан хүн гэгч өөр хоорондоо ахан дүүгийн үзэл санаагаар харьцах учиртай.
:::

:::paragraphs{style="line" lang=mn}
*Энэ бол миний төрсөн нутаг*\
:span[Д. Нацагдорж]{style="who"}
:::

:::paragraphs{style="abc" lang=mn}
Аа Бб Вв Гг Дд Ее Ёё Жж Зз Ии Йй Кк Лл Мм Нн Оо Өө Пп Рр Сс Тт Уу Үү Фф Хх Цц Чч Шш Щщ Ъъ Ыы Ьь Ээ Юю Яя
:::
:::

# Местные формы {style="plate" lead="Одна буква, разные рисунки: шрифт берёт их по языку текста"}

### Прямой шрифт: Россия и Болгария

:::paragraphs{style="forms"}
:span[Русский]{style="tag"}	:ltr[в г д ж з и й к л п т ц ш щ ю]{lang=ru}

:span[Български]{style="tag"}	:ltr[в г д ж з и й к л п т ц ш щ ю]{lang=bg}
:::

### Курсив: Россия, Сербия и Македония

:::paragraphs{style="forms"}
:span[Русский]{style="tag"}	:ltr[*б г д п т*]{lang=ru}	:ltr[*Добрый день, город*]{lang=ru}

:span[Српски]{style="tag"}	:ltr[*б г д п т*]{lang=sr}	:ltr[*Добар дан, граде*]{lang=sr}

:span[Македонски]{style="tag"}	:ltr[*б г д п т*]{lang=mk}	:ltr[*Добар ден, граде*]{lang=mk}
:::

### Три насыщенности

:::paragraphs{style="weights"}
Съешь ещё этих мягких французских булок, да выпей чаю

**Съешь ещё этих мягких французских булок, да выпей чаю**

:span[Съешь ещё этих мягких французских булок, да выпей чаю]{style="black"}
:::

### Библиотека на двенадцати языках

:::columns{count=3 breaks="5,9"}
:::paragraphs{style="cuts"}
:span[Русский]{style="tag"}	:ltr[биб·лио·те·ка]{lang=ru}

:span[Українська]{style="tag"}	:ltr[бі·бліо·те·ка]{lang=uk}

:span[Беларуская]{style="tag"}	:ltr[біб·лія·тэ·ка]{lang=be}

:span[Български]{style="tag"}	:ltr[биб·ли·о·те·ка]{lang=bg}

:span[Српски]{style="tag"}	:ltr[би·бли·о·те·ка]{lang=sr}

:span[Македонски]{style="tag"}	:ltr[би·бли·о·те·ка]{lang=mk}

:span[Қазақша]{style="tag"}	:ltr[кі·тап·ха·на]{lang=kk}

:span[Кыргызча]{style="tag"}	:ltr[ки·теп·ка·на]{lang=ky}

:span[Татарча]{style="tag"}	:ltr[ки·тап·ха·нә]{lang=tt}

:span[Башҡортса]{style="tag"}	:ltr[ки·тап·ха·на]{lang=ba}

:span[Тоҷикӣ]{style="tag"}	:ltr[ки·тоб·хо·на]{lang=tg}

:span[Монгол]{style="tag"}	:ltr[хэв·лэл]{lang=mn}
:::
:::

`, String.raw`:::paragraphs{style="colophon"}
Set in Source Serif 4 and Source Sans 3 (SIL OFL) · Text: UDHR, article 1, and lines by the authors named, public domain
:::
`].join('\n\n');

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { // every face the pages use, with the Cyrillic files their letters need
  'Source Serif 4': ['400', '400i', '700', '900'],
  'Source Sans 3': ['400', '700'],
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown }, config(), kitCyrillicFonts(FONTS));
showPages(doc, { title: 'Двенадцать кириллиц' });
offerPdf(() => renderToPdf(doc, { fontProvider: cyrillicPdfProvider }), `${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 · cyrillic v1 ── Cyrillic faces · postext.dev/cookbook
// Fontsource ships a family's Cyrillic letters in files of their own:
// `cyrillic` holds the Russian, Ukrainian, Belarusian, Bulgarian, Serbian and
// Macedonian alphabets, the stress mark and №; `cyrillic-ext` the letters of
// Kazakh, Kyrgyz, Tatar, Bashkir, Tajik and Mongolian. The fonts block loads
// latin, latin-ext and greek; this one adds these.

/** The unicode-ranges Fontsource's stylesheets declare the two files with (a
 *  function: the kit runs after the pen's code). */
function cyrillicRanges() {
  return {
    cyrillic: 'U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116',
    'cyrillic-ext': 'U+0460-052F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F',
  };
}

/** The Cyrillic files `text` needs that `meta`'s family ships. */
function cyrillicSubsetsFor(text, meta) {
  return [[/[́Ѐ-џҐґҰұ№]/u, 'cyrillic'],
    [/[Ѡ-ҏҒ-үҲ-ԯᲀ-ᲊ₴ⷠ-ⷿꙀ-ꚟ]/u, 'cyrillic-ext']]
    .filter(([re, x]) => re.test(text) && meta?.subsets?.includes(x)).map(([, x]) => x);
}

/** kitFonts(FONTS) for a pen in Cyrillic: the fonts block's files, then the
 *  Cyrillic ones `text` needs. A family without them fails, so that no page
 *  is set in a fallback face unseen; list in `latin` the families that set
 *  Latin text alone. */
function kitCyrillicFonts(FONTS = {}, latin = []) {
  return { ...kitFonts(FONTS), resolve: async (family, weight, style, request = {}) => {
    const files = await fontsourceResolver(family, weight, style, request);
    const meta = await fontsourceMeta(family);
    if (!files || latin.includes(family)) return files;
    if (/\p{Script=Cyrillic}/u.test(request.text ?? '') && !meta?.subsets?.includes('cyrillic')) {
      throw new Error(`${family} has no Cyrillic letters at Fontsource`);
    }
    const at = await fontsourceAt(fontsourceId(family));
    return [...files, ...cyrillicSubsetsFor(request.text ?? '', meta).map((subset) => ({
      source: `${at}files/${fontsourceId(family)}-${subset}-${weight}-${style}.woff2`,
      unicodeRange: cyrillicRanges()[subset],
    }))];
  } };
}

/** fontsourceProvider (the pdf block) with the Cyrillic files a face's
 *  letters need, after its others, as the screen added them. */
async function cyrillicPdfProvider(family, weight, style, request) {
  const first = await fontsourceProvider(family, weight, style, request);
  const files = Array.isArray(first) ? first : [first];
  const meta = await fontsourceMeta(family);
  const text = String.fromCodePoint(...(request?.codePoints ?? []));
  const subsets = cyrillicSubsetsFor(text, meta);
  if (!subsets.length) return first;
  const s = style === 'italic' && !meta.styles.includes('italic') ? 'normal' : style;
  const w = (await fontsourceWeights(family, s)).reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const at = await fontsourceAt(fontsourceId(family));
  const more = await Promise.all(subsets.map(async (subset, i) => {
    const url = `${at}files/${fontsourceId(family)}-${subset}-${w}-${s}.woff2`;
    const res = await fetch(url);
    if (!res.ok) throw new Error(`Fontsource file ${url} (${res.status})`);
    return Object.assign(await decompressWoff2(new Uint8Array(await res.arrayBuffer())),
      { unicodeRange: cyrillicRanges()[subset], order: files.length + i });
  }));
  return [...files, ...more];
}

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

## أخطاء شائعة

- يجب أن يحوي الخط هذه الأشكال. ليس في PT Serif شيء منها لهذه اللغات، وفي Vollkorn وLora البلغارية والصربية. وإن غابت ظل العزل يقطّع النص ويسمه، لكن الحروف تبقى روسية الشكل.
- ويجب أن يحوي الحروف أيضًا. الحروف Ә وҒ وҢ وҘ وҶ وӮ في ملف `cyrillic-ext` من العائلة، ويحمّله `kitCyrillicFonts`؛ وينقص بعضها في Literata وSpectral.

## الحقوق

- الوصفة: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- النص: Article 1 of the Universal Declaration of Human Rights in eleven languages, from the plain texts of the UDHR in XML project, with four misprints of the Kazakh, Kyrgyz and Tatar files corrected: United Nations ([المصدر](http://efele.net/udhr/assemblies/first_article_all.txt)), ملكية عامة
- النص: Article 1 in Bashkir: United Nations ([المصدر](https://www.omniglot.com/writing/bashkir.htm)), ملكية عامة
- النص: Opening lines and sayings of Pushkin, Shevchenko, Kupala, Vazov, Vuk Karadžić, Racin, Abai, Toktogul, Tukay, Akmulla, Rudaki and Natsagdorj: The authors named, ملكية عامة
- النص: The titles, the alphabets and the colophon: Postext Cookbook, أصلي
- الخطوط: Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)
- الشيفرة: MIT · محتوى المثال: MIT

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

- [رقم 210 · أباي وخمسة من شعراء السهوب: مختارات كازاخية](https://postext.dev/ar/cookbook/abai-kazakh-anthology.md): مختارات في ثماني صفحات بست لغات سيريلية: كتاب كازاخي، وقصيدة لكل لغة، وشروح في أسفل الصفحة، وزخارف بساط اللباد. · المستوى 2 (متوسط) · الشعر
- [رقم 201 · رواية يونانية بتقطيع أحادي النبر](https://postext.dev/ar/cookbook/monotonic-greek-novel.md): الفصل الأول من «Η τιμή και το χρήμα» لثيوتوكيس في كتاب 13,5 × 20,5 سم: أنماط اليونانية أحادية النبر، وعلامات «»، وحروف كبيرة بلا نبر. · المستوى 2 (متوسط) · الأدب القصصي والمسرح والنثر الأدبي
- [رقم 153 · صفحة واحدة بست لغات](https://postext.dev/ar/cookbook/one-page-six-languages.md): صفحة قصص مصوّرة بتقسيم ورسوم ثابتة، يُكتب حوارها من نصّ لكل لغة: يختار locale الخط، وتُكتب اليابانية عموديًّا، وتُقرأ اليابانية والعربية من اليمين. · المستوى 3 (متقدم) · القصص المصوّرة
