# قصائد أوكرانية في طبعة هدية

> ثلاث قصائد لشيفتشينكو بقياس 130 × 200 مم: مقاطع موسّطة، وحواشٍ بنجوم لكل صفحة، وتواريخ أسفلها، وأشرطة غرز مرسومة بالشيفرة.

- نسخة HTML: https://postext.dev/ar/cookbook/kobzar-ukrainian-poems
- وصفة رقم 208 · الحروف والنص · المستوى 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/kobzar-ukrainian-poems/en/p01.webp?v=1e5a4dab), [2](https://postext.dev/cookbook/kobzar-ukrainian-poems/en/p02.webp?v=1e5a4dab), [3](https://postext.dev/cookbook/kobzar-ukrainian-poems/en/p03.webp?v=1e5a4dab), [4](https://postext.dev/cookbook/kobzar-ukrainian-poems/en/p04.webp?v=1e5a4dab), [5](https://postext.dev/cookbook/kobzar-ukrainian-poems/en/p05.webp?v=1e5a4dab), [6](https://postext.dev/cookbook/kobzar-ukrainian-poems/en/p06.webp?v=1e5a4dab)
- PDF: https://postext.dev/cookbook/kobzar-ukrainian-poems/en/kobzar-ukrainian-poems.pdf?v=1e5a4dab
- افتح في Sandbox: https://postext.dev/ar/sandbox#recipe=kobzar-ukrainian-poems&lang=en (.postext: https://postext.dev/cookbook/kobzar-ukrainian-poems/en/kobzar-ukrainian-poems.postext)
- آخر تحديث: 2026-12-02
- لغات أخرى: [en](https://postext.dev/en/cookbook/kobzar-ukrainian-poems.md), [es](https://postext.dev/es/cookbook/kobzar-ukrainian-poems.md), [ca](https://postext.dev/ca/cookbook/kobzar-ukrainian-poems.md), [de](https://postext.dev/de/cookbook/kobzar-ukrainian-poems.md), [el](https://postext.dev/el/cookbook/kobzar-ukrainian-poems.md), [fr](https://postext.dev/fr/cookbook/kobzar-ukrainian-poems.md), [it](https://postext.dev/it/cookbook/kobzar-ukrainian-poems.md), [pt](https://postext.dev/pt/cookbook/kobzar-ukrainian-poems.md), [ru](https://postext.dev/ru/cookbook/kobzar-ukrainian-poems.md), [zh](https://postext.dev/zh/cookbook/kobzar-ukrainian-poems.md), [ja](https://postext.dev/ja/cookbook/kobzar-ukrainian-poems.md)

## باختصار

كتاب هدية صغير لقصائد أوكرانية لتاراس شيفتشينكو: صفحة عنوان حمراء بتطريز، وشريط مطرز فوق عنوان كل قصيدة، وحواشٍ قصيرة معلّمة بالنجوم.

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

ست صفحات من طبعة هدية لديوان تاراس شيفتشينكو *Кобзар*، بقياس 130 × 200 مم، وهو القطع 84 × 108/32 بعد القص: صفحة عنوان بلون الكرز وعليها أشرطة غرز، وملاحظة عن النص، وثلاث قصائد. من «Причинна» مطلعها الشهير «Реве та стогне Дніпр широкий»؛ و«Заповіт» و«Садок вишневий коло хати» كاملتان. تبدأ كل قصيدة تحت شريط من غرز حمراء وسوداء. الشعر بخط Vollkorn قياس 11 على 15,5 نقطة، والعناوين بخط Yeseva One، وهو حرف سمين مستدير يقارب فن الكتاب في كييف نحو 1917. التواريخ والأماكن مائلة تحت القصائد، والحواشي بالنجوم. وتتبع الملاحظة عن النص لغة الطبعة، وتبقى القصائد أوكرانية.

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

- كيف أنضد كتاب قصائد بالأوكرانية، بمقاطعه وتواريخه وحواشيه؟
- كيف أنضد الشعر: سطر لكل بيت، وفراغ بين المقاطع، ومسافة بادئة معلّقة للأسطر الملتفّة، وبلا تقسيم كلمات؟

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

```js
// script.js, سطرًا 36–52
// locale 'uk' is the language of the hyphenation, the ties (no line of the note parts «і», «в»,
// «на» from its word) and the footnotes, which start again on every page, indented. The
// apostrophe is typed ’ (U+2019): сем’ї, кров’ю stay whole words.
const LOCALE = 'uk';
// A poem is one :::verse block, written as it is printed, a blank line between two stanzas. A
// poem longer than its page goes on overleaf after a whole stanza or between two lines.
const verse = { align: 'center', hang: em(2) }; // bodyText.verse: centred on its longest line
// The note's mark follows its word: «півні[^1] не співали».
// Asterisks count a page's notes: *, **, ***, the custom of a book with few of them.
const footnotes = { numberFormat: 'symbols', fontFamily: TEXT, fontSize: pt(8.2),
  lineHeight: pt(11), color: col('muted'),
  separator: { enabled: true, width: 0.2, lineWidth: pt(0.5), color: col('cherry') } };
// The date and the place, in italics under the poem, drawn in to 16 mm from the
// right edge, under the ends of the lines.
const date = { id: 'date', fontSize: pt(9.2), color: col('muted'), textAlign: 'right',
  italic: true, endIndent: mm(16), firstLineIndent: pt(0), marginTop: pt(LEAD),
  hyphenation: false };
```

## المكونات

**تعلّم**

- [الشعر سطرًا سطرًا](https://postext.dev/ar/docs/document-format-directives.md#verse): يصفّ :::verse القصيدة كما كُتبت: سطر من الشعر في كل سطر من Markdown، وأسطر فارغة بين المقاطع، والمسافات البادئة إزاحة؛ والسطر الأطول من اللازم يُكمَل بإزاحة معلّقة أو إلى الطرف بعد قوس معقوف، ولا ينفصل عن سطره عند فاصل الصفحة، ويمكن إبقاء المقاطع القصيرة كاملة.
- [اللغات الكيريلية لغةً للمستند](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/document-format-notes-references.md#الحواشي-السفلية): حواشٍ يُستشهد بها بالصيغة [^id] وتوضع أسفل العمود الذي يستشهد بها، أو بعد الفصل، مرقّمة لكل فصل أو على امتداد الكتاب.

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

- [كلمات لا تُفصل عند نهاية السطر](https://postext.dev/ar/docs/cyrillic-layout.md#الكلمات-المتلازمة)
- [تقسيم الكلمات ولغة المستند](https://postext.dev/ar/docs/justification.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-styles.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-styles.md#أنماط-الفقرات)
- [البيانات الوصفية للمستند](https://postext.dev/ar/docs/document-format.md#البيانات-التمهيدية-frontmatter)
- [الترويسات وأرقام الصفحات](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات)
- [الترويسات بحسب دور الصفحة](https://postext.dev/ar/docs/configuration-headers-footers.md#عناصر-النص)
- [هوامش متناظرة](https://postext.dev/ar/docs/configuration-page-layout.md#الهوامش-المتناظرة)
- [لون الورق](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-resources.md#الموارد)
- [هندسة القسم](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين)
- [ترويسات لكل قسم](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين)

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

- [`bodyText`](https://postext.dev/ar/docs/configuration-text.md#نص-المتن), [`colorPalette`](https://postext.dev/ar/docs/configuration-fonts-colors-viewers.md#لوحة-الألوان), [`footer`](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات), [`footnotes`](https://postext.dev/ar/docs/configuration-notes-references.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), [`registerResourceImage`](https://postext.dev/ar/docs/architecture.md#واجهة-البرمجة-المتاحة-api), [`renderPageToCanvas`](https://postext.dev/ar/docs/configuration-programmatic-usage.md#رسم-صفحة-في-صورة-نقطية), [`renderToPdf`](https://postext.dev/ar/docs/configuration-pdf-output.md#توليد-ملفات-pdf)

**الخطوط**

- Vollkorn (OFL-1.1), Yeseva One (OFL-1.1)

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

### 1 · المحلية الأوكرانية وكتلة الشعر

الشيفرة هي [الجواب المختصر](https://postext.dev/ar/cookbook/kobzar-ukrainian-poems.md#الجواب-المختصر) أعلاه. يختار `locale: 'uk'` تقطيع الكلمات الأوكراني وروابطها، ويعيد عد الحواشي في كل صفحة ويزيحها ([الإخراج السيريلي](https://postext.dev/ar/docs/cyrillic-layout.md)). كل قصيدة كتلة `:::verse` ([التوجيهات](https://postext.dev/ar/docs/document-format-directives.md)) مكتوبة كما تُطبع، وبين المقطعين سطر فارغ. ويوسّط `align: 'center'` الكتلة على أطول بيت، وتبدأ الأبيات كلها من حافة واحدة. وتلي `[^1]` كلمتها، فيعلّمها `numberFormat: 'symbols'` بالنجمة * ([الحواشي](https://postext.dev/ar/docs/configuration-notes-references.md)). ويضع `:::paragraphs{style="date"}` التاريخ.

### 2 · 84 × 108/32 و28 سطرًا

```js
// script.js, سطرًا 56–63
const [TRIM_W, TRIM_H, TOP, INNER, OUTER, LINES] = [130, 200, 22, 19, 21, 28]; // mm, lines
const page = {
  sizePreset: '84x108/32', dpi: 150, backgroundColor: col('paper'),
  margins: { top: mm(TOP), bottom: mm(TRIM_H - TOP - LINES * LINE), left: mm(INNER),
    right: mm(OUTER), mirror: true },
};
const MEASURE = TRIM_W - INNER - OUTER; // mm: 90
const SHIFT = (INNER - OUTER) / 2; // mm: the text block's centre is off the page's centre
```

القيمة `sizePreset: '84x108/32'` قياس ورق سوفييتي وأوكراني يُقص إلى 130 × 200 مم. والهامش السفلي هو ما تتركه 28 سطرًا، فتنتهي كتلة النص دائمًا عند سطر كامل. والهوامش الخارجية أوسع من الداخلية وتتبادل مع `mirror`. ويوسّط `SHIFT` الترويسات وأرقام الصفحات فوق النص الذي يبعد 1 مم عن وسط الصفحة.

### 3 · صفحة حمراء ثم شريط لكل قصيدة

```js
// script.js, سطرًا 67–98
const none = { header: { elements: [] }, footer: { elements: [] } };
// No margins on that page: the ground and the bands reach the trim on all four sides.
const flush = { span: 'page',
  margins: { top: mm(0), bottom: mm(0), left: mm(0), right: mm(0) } };
const titlePage = { id: 'title-page', ...none, ...flush, marginBottom: pt(0),
  breakBefore: { enabled: true, parity: 'odd' },
  advancedDesign: { enabled: true, minHeight: mm(TRIM_H), slot: { elements: [
    { kind: 'box', id: 'ground', style: { backgroundColor: col('cherry') },
      placement: { ...at('page', 'top-left'), size: { width: 'fill', height: mm(TRIM_H) } } },
    image('head', 'linen', { ...at('page', 'top-left'), size: { width: mm(TRIM_W) } }),
    image('foot', 'linen', { ...at('page', 'bottom-left'), size: { width: mm(TRIM_W) } }),
    text('author', '{author}', DISPLAY, 13, 'paper', at('page', 'top', 0, 58), wide),
    text('title', '{titleText}', DISPLAY, 58, 'paper', at('page', 'top', 0, 67)),
    text('subtitle', '{subtitle}', TEXT, 14, 'paper', at('page', 'top', 0, 96), italic),
    image('star', 'star', { ...at('page', 'top', 0, 116), size: { width: mm(22) } }),
    text('place', '{attr.place}', DISPLAY, 10, 'paper', at('page', 'bottom', 0, -32), wide),
  ] } } };
const poem = { id: 'poem', breakBefore: { enabled: true, parity: 'any' }, marginBottom: pt(0),
  numbered: false, advancedDesign: { enabled: true, minHeight: pt(7 * LEAD), slot: { elements: [
    image('band', 'band', { ...at('container', 'top', 0, -TOP + 14),
      size: { width: mm(MEASURE) } }),
    text('title', '{titleText}', DISPLAY, 16, 'cherry', at('container', 'top', 0, 14)),
    text('kicker', '{attr.kicker}', TEXT, 9.5, 'muted', at('#title', 'below', 0, 1.5), italic),
  ] } } };
// The note stands low on the verso behind the title page, under a star.
const notePage = { id: 'note-page', ...none, breakBefore: { enabled: true, parity: 'any' },
  marginBottom: pt(0), advancedDesign: { enabled: true, minHeight: pt(15 * LEAD), slot: {
    elements: [
      image('star', 'redstar', { ...at('container', 'top', 0, 10 * LINE),
        size: { width: mm(13) } }),
      text('label', '{titleText}', DISPLAY, 10, 'cherry', at('container', 'top', 0, 13.2 * LINE)),
    ] } } };
```

يملأ `# Кобзар {style="title-page" place="Київ"}` الصفحة 1: مع `span: 'page'` وبلا هوامش يصل التصميم إلى حافة القص، ويأخذ المؤلف والعنوان الفرعي من frontmatter. ويعطي `# Заповіт {style="poem" kicker="…"}` كل قصيدة شريطها وعنوانها وسطرًا مائلًا؛ ويجعل `minHeight` بسبعة أسطر القصائد كلها تبدأ من ارتفاع واحد.

### 4 · تطريز معدود على شبكة

```js
// script.js, سطرًا 102–141
// Every stitch is an ×, so the pattern is counted, not drawn: the rose is the cells of a petal,
// b from 1 to 4 and a from b + 1 to b + 4, mirrored into its eight octants; a lozenge with a
// cross in it fills the gap every 24 stitches. Red and black threads on the paper, linen on red.
const [PERIOD, HALF] = [24, 11]; // stitches: one rose to the next, the middle row to the edge
const rose = (x, y) => { const [b, a] = [Math.abs(x), Math.abs(y)].sort((p, q) => p - q);
  return b >= 1 && b <= 4 && a >= b + 1 && a <= b + 4; };
function thread(x, y) { // 'A' the main thread, 'B' the second, '' bare cloth
  const u = ((x % PERIOD) + PERIOD) % PERIOD; // 0 at the middle of a rose
  const [dx, v] = [u > PERIOD / 2 ? u - PERIOD : u, Math.abs(y)];
  const r = Math.abs(u - PERIOD / 2) + v; // from the middle of the lozenge
  if (v === HALF) return 'B';
  if (v === HALF - 1) return x % 2 === 0 ? 'A' : '';
  if (rose(dx, y)) return 'A';
  if (r === 5 || r === 0) return 'B';
  if (r === 2 && (y === 0 || u === PERIOD / 2)) return 'A';
  // Small pyramids above and below the lozenge, hanging from the border.
  return Math.abs(u - PERIOD / 2) + (9 - v) <= 2 && v <= 9 ? 'B' : '';
}
function stitches(x0, x1, y0, y1, colours, cellAt = thread) { // one path per thread, 1 unit a cell
  const d = { A: '', B: '' };
  for (let y = y0; y <= y1; y++) {
    for (let x = x0; x <= x1; x++) {
      const t = cellAt(x, y);
      if (t) d[t] += `M${x - x0 + 0.14} ${y - y0 + 0.14}l.72 .72m0 -.72l-.72 .72`;
    }
  }
  const [w, h] = [x1 - x0 + 1, y1 - y0 + 1];
  return { width: w * 10, height: h * 10,
    markup: `<svg xmlns="http://www.w3.org/2000/svg" width="${w * 10}" height="${h * 10}" `
      + `viewBox="0 0 ${w} ${h}" fill="none" stroke-width=".4" stroke-linecap="round">`
      + `<path d="${d.A}" stroke="${palette[colours[0]]}"/>`
      + `<path d="${d.B}" stroke="${palette[colours[1]]}"/></svg>` };
}
const whole = (x, y) => (rose(x, y) ? 'A' : Math.abs(x) + Math.abs(y) === 0 ? 'B' : '');
const ART = {
  linen: stitches(-72, 72, -HALF, HALF, ['paper', 'paper']), // the width of the title page
  band: stitches(-60, 60, -HALF, HALF, ['cherry', 'ink']), // over a poem, at the measure
  star: stitches(-8, 8, -8, 8, ['paper', 'paper'], whole),
  redstar: stitches(-8, 8, -8, 8, ['cherry', 'ink'], whole),
};
```

الأشرطة SVG من غرز ×، ولكل خيط مسار. البتلة هي الخانات التي فيها b من 1 إلى 4 وa من b + 1 إلى b + 4، تُنقل إلى الأثمان الثمانية بالقيم المطلقة؛ ويملأ معيّن وهرمان الفراغ كل 24 خانة. 121 غرزة تغطي عرض النص و145 عرض الصفحة، ففي الوسط وردة كاملة دائمًا.

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

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

- مجلد الوصفة: https://github.com/drnachio/postext/tree/main/cookbook/kobzar-ukrainian-poems

### script.js

```js
// ═══ Postext Cookbook · Nº 208 · Shevchenko's poems in a gift edition of the Kobzar ══════
// https://postext.dev/en/cookbook/kobzar-ukrainian-poems
// Code: MIT · Text: T. Shevchenko, 1837–1847 (PD, litopys.org.ua) · Embroidery: drawn in code
// Fonts: Vollkorn, Yeseva One (SIL OFL 1.1) · Needs postext ≥ 1.100.0
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the note on the text ('en' | 'es' | 'ru')
const RECIPE = 'kobzar-ukrainian-poems';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// The red and black thread of a Dnipro embroidery on linen-coloured paper, and the round, dark
// capitals of the Kyiv book art of the 1910s and 1920s.
const palette = {
  ink: '#231b18', // the poems, the black thread
  cherry: '#a3221f', // the title page, the titles, the red thread
  muted: '#6f5e52', // notes, dates, running heads
  paper: '#fbf5e8', // the page, the linen thread on the red
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = Object.entries({ ...palette, 'main-color': palette.cherry })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const [TEXT, DISPLAY] = ['Vollkorn', 'Yeseva One']; // both with ґ є і ї
const [BODY, LEAD, LINE] = [11, 15.5, (15.5 * 25.4) / 72]; // pt, pt, and a line in mm: 5.47
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const text = (id, content, family, size, color, placement, extra = {}) => ({ kind: 'text', id,
  content, fontFamily: family, fontSize: pt(size), color: col(color), align: 'center',
  lineHeight: 1.15, overflow: 'wrap', ...extra,
  placement: { ...placement, size: { width: 'fill' } } });
const [wide, italic] = [{ letterSpacing: pt(1) }, { italic: true }];
const image = (id, resourceId, placement) => ({ kind: 'image', id, resourceId, placement });

// #region answer: the Ukrainian locale, a :::verse block a poem, its date and its notes
// locale 'uk' is the language of the hyphenation, the ties (no line of the note parts «і», «в»,
// «на» from its word) and the footnotes, which start again on every page, indented. The
// apostrophe is typed ’ (U+2019): сем’ї, кров’ю stay whole words.
const LOCALE = 'uk';
// A poem is one :::verse block, written as it is printed, a blank line between two stanzas. A
// poem longer than its page goes on overleaf after a whole stanza or between two lines.
const verse = { align: 'center', hang: em(2) }; // bodyText.verse: centred on its longest line
// The note's mark follows its word: «півні[^1] не співали».
// Asterisks count a page's notes: *, **, ***, the custom of a book with few of them.
const footnotes = { numberFormat: 'symbols', fontFamily: TEXT, fontSize: pt(8.2),
  lineHeight: pt(11), color: col('muted'),
  separator: { enabled: true, width: 0.2, lineWidth: pt(0.5), color: col('cherry') } };
// The date and the place, in italics under the poem, drawn in to 16 mm from the
// right edge, under the ends of the lines.
const date = { id: 'date', fontSize: pt(9.2), color: col('muted'), textAlign: 'right',
  italic: true, endIndent: mm(16), firstLineIndent: pt(0), marginTop: pt(LEAD),
  hyphenation: false };
// #endregion

// #region page: 84 × 108/32, the sheet format of a book of poems, 28 lines of 15.5 pt
const [TRIM_W, TRIM_H, TOP, INNER, OUTER, LINES] = [130, 200, 22, 19, 21, 28]; // mm, lines
const page = {
  sizePreset: '84x108/32', dpi: 150, backgroundColor: col('paper'),
  margins: { top: mm(TOP), bottom: mm(TRIM_H - TOP - LINES * LINE), left: mm(INNER),
    right: mm(OUTER), mirror: true },
};
const MEASURE = TRIM_W - INNER - OUTER; // mm: 90
const SHIFT = (INNER - OUTER) / 2; // mm: the text block's centre is off the page's centre
// #endregion

// #region openers: a red title page, and a stitched band over the title of each poem
const none = { header: { elements: [] }, footer: { elements: [] } };
// No margins on that page: the ground and the bands reach the trim on all four sides.
const flush = { span: 'page',
  margins: { top: mm(0), bottom: mm(0), left: mm(0), right: mm(0) } };
const titlePage = { id: 'title-page', ...none, ...flush, marginBottom: pt(0),
  breakBefore: { enabled: true, parity: 'odd' },
  advancedDesign: { enabled: true, minHeight: mm(TRIM_H), slot: { elements: [
    { kind: 'box', id: 'ground', style: { backgroundColor: col('cherry') },
      placement: { ...at('page', 'top-left'), size: { width: 'fill', height: mm(TRIM_H) } } },
    image('head', 'linen', { ...at('page', 'top-left'), size: { width: mm(TRIM_W) } }),
    image('foot', 'linen', { ...at('page', 'bottom-left'), size: { width: mm(TRIM_W) } }),
    text('author', '{author}', DISPLAY, 13, 'paper', at('page', 'top', 0, 58), wide),
    text('title', '{titleText}', DISPLAY, 58, 'paper', at('page', 'top', 0, 67)),
    text('subtitle', '{subtitle}', TEXT, 14, 'paper', at('page', 'top', 0, 96), italic),
    image('star', 'star', { ...at('page', 'top', 0, 116), size: { width: mm(22) } }),
    text('place', '{attr.place}', DISPLAY, 10, 'paper', at('page', 'bottom', 0, -32), wide),
  ] } } };
const poem = { id: 'poem', breakBefore: { enabled: true, parity: 'any' }, marginBottom: pt(0),
  numbered: false, advancedDesign: { enabled: true, minHeight: pt(7 * LEAD), slot: { elements: [
    image('band', 'band', { ...at('container', 'top', 0, -TOP + 14),
      size: { width: mm(MEASURE) } }),
    text('title', '{titleText}', DISPLAY, 16, 'cherry', at('container', 'top', 0, 14)),
    text('kicker', '{attr.kicker}', TEXT, 9.5, 'muted', at('#title', 'below', 0, 1.5), italic),
  ] } } };
// The note stands low on the verso behind the title page, under a star.
const notePage = { id: 'note-page', ...none, breakBefore: { enabled: true, parity: 'any' },
  marginBottom: pt(0), advancedDesign: { enabled: true, minHeight: pt(15 * LEAD), slot: {
    elements: [
      image('star', 'redstar', { ...at('container', 'top', 0, 10 * LINE),
        size: { width: mm(13) } }),
      text('label', '{titleText}', DISPLAY, 10, 'cherry', at('container', 'top', 0, 13.2 * LINE)),
    ] } } };
// #endregion

// #region embroidery: an eight-petalled rose and a lozenge, counted on a grid of crosses
// Every stitch is an ×, so the pattern is counted, not drawn: the rose is the cells of a petal,
// b from 1 to 4 and a from b + 1 to b + 4, mirrored into its eight octants; a lozenge with a
// cross in it fills the gap every 24 stitches. Red and black threads on the paper, linen on red.
const [PERIOD, HALF] = [24, 11]; // stitches: one rose to the next, the middle row to the edge
const rose = (x, y) => { const [b, a] = [Math.abs(x), Math.abs(y)].sort((p, q) => p - q);
  return b >= 1 && b <= 4 && a >= b + 1 && a <= b + 4; };
function thread(x, y) { // 'A' the main thread, 'B' the second, '' bare cloth
  const u = ((x % PERIOD) + PERIOD) % PERIOD; // 0 at the middle of a rose
  const [dx, v] = [u > PERIOD / 2 ? u - PERIOD : u, Math.abs(y)];
  const r = Math.abs(u - PERIOD / 2) + v; // from the middle of the lozenge
  if (v === HALF) return 'B';
  if (v === HALF - 1) return x % 2 === 0 ? 'A' : '';
  if (rose(dx, y)) return 'A';
  if (r === 5 || r === 0) return 'B';
  if (r === 2 && (y === 0 || u === PERIOD / 2)) return 'A';
  // Small pyramids above and below the lozenge, hanging from the border.
  return Math.abs(u - PERIOD / 2) + (9 - v) <= 2 && v <= 9 ? 'B' : '';
}
function stitches(x0, x1, y0, y1, colours, cellAt = thread) { // one path per thread, 1 unit a cell
  const d = { A: '', B: '' };
  for (let y = y0; y <= y1; y++) {
    for (let x = x0; x <= x1; x++) {
      const t = cellAt(x, y);
      if (t) d[t] += `M${x - x0 + 0.14} ${y - y0 + 0.14}l.72 .72m0 -.72l-.72 .72`;
    }
  }
  const [w, h] = [x1 - x0 + 1, y1 - y0 + 1];
  return { width: w * 10, height: h * 10,
    markup: `<svg xmlns="http://www.w3.org/2000/svg" width="${w * 10}" height="${h * 10}" `
      + `viewBox="0 0 ${w} ${h}" fill="none" stroke-width=".4" stroke-linecap="round">`
      + `<path d="${d.A}" stroke="${palette[colours[0]]}"/>`
      + `<path d="${d.B}" stroke="${palette[colours[1]]}"/></svg>` };
}
const whole = (x, y) => (rose(x, y) ? 'A' : Math.abs(x) + Math.abs(y) === 0 ? 'B' : '');
const ART = {
  linen: stitches(-72, 72, -HALF, HALF, ['paper', 'paper']), // the width of the title page
  band: stitches(-60, 60, -HALF, HALF, ['cherry', 'ink']), // over a poem, at the measure
  star: stitches(-8, 8, -8, 8, ['paper', 'paper'], whole),
  redstar: stitches(-8, 8, -8, 8, ['cherry', 'ink'], whole),
};
// #endregion

// Running heads: the poet on the verso, the poem on the recto; folios in the display face.
const head = (parity, content) => ({ kind: 'text', id: `head-${parity}`, parity, content,
  pages: 'body', align: 'center', fontFamily: TEXT, italic: true, fontSize: pt(9),
  color: col('muted'), placement: at('page', 'top', parity === 'odd' ? SHIFT : -SHIFT, 12) });
const header = { elements: [head('even', '{author}'), head('odd', '{chapterTitle}')] };
const folio = (parity) => ({ kind: 'text', id: `folio-${parity}`, parity, content: '{pageNumber}',
  align: 'center', fontFamily: DISPLAY, fontSize: pt(9.5), color: col('cherry'),
  placement: at('page', 'bottom', parity === 'odd' ? SHIFT : -SHIFT, -10) });
const footer = { elements: [folio('even'), folio('odd')] };

const config = () => ({
  locale: LOCALE, // written out, never LANG: the poems are Ukrainian in every edition
  colorPalette, page, footnotes, header, footer,
  layout: { layoutType: 'single' }, // the default is two columns
  bodyText: { fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    firstLineIndent: em(1.5), minWordSpacing: 0.8, maxWordSpacing: 1.6, verse },
  headings: { fontFamily: DISPLAY, fontWeight: 400,
    levels: [{ level: 1, breakBefore: { enabled: true, parity: 'any' } }] },
  headingStyles: [titlePage, notePage, poem],
  paragraphStyles: [date,
    // The note is in the edition's language: :::paragraphs{lang=…} divides it by its patterns.
    { id: 'note', fontSize: pt(9.2), lineHeight: pt(13), color: col('ink'),
      italicColor: col('ink'), firstLineIndent: em(1.5) },
    { id: 'colophon', fontSize: pt(7.6), lineHeight: pt(10.4), color: col('muted'),
      textAlign: 'center', firstLineIndent: pt(0), marginTop: pt(LEAD),
      hyphenation: false },
  ],
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The title page and the note (content.<lang>.md), then the poems (content.text.<lang>.md).
const markdown = [String.raw`---
title: "Кобзар"
subtitle: "Вибрані поезії"
author: "Тарас Шевченко"
---

# Кобзар {style="title-page" place="Київ"}

# A note on the text {style="note-page"}

:::paragraphs{style="note" lang="en"}
Taras Shevchenko (1814–1861) wrote *Причинна* (*The Bewitched Girl*) in St Petersburg while still a serf, *Заповіт* (*Testament*) ill in Pereiaslav, and the cherry orchard in a cell of the Third Department, weeks before ten years of exile as a soldier. The opening of the ballad and the two poems, whole, follow the text of the academic edition (Kyiv, 2003), which keeps the poet’s *тілько*, *сем’я*, *отойді*. The notes were written for this edition.
:::

:::paragraphs{style="colophon"}
Set in Vollkorn and Yeseva One (SIL OFL) · Text: T. Shevchenko, public domain · Embroidery drawn in code
:::
`, String.raw`# Причинна {style="poem" kicker="Початок балади"}

:::verse
Реве та стогне Дніпр широкий,
Сердитий вітер завива,
Додолу верби гне високі,
Горами хвилю підійма.
І блідний місяць на ту пору
Із хмари де-де виглядав,
Неначе човен в синім морі
То виринав, то потопав.
Ще треті півні[^1] не співали,
Ніхто нігде не гомонів,
Сичі в гаю перекликались,
Та ясен раз у раз скрипів.

В таку добу під горою,
Біля того гаю,
Що чорніє над водою,
Щось біле блукає.
:::

:::paragraphs{style="date"}
1837, С.-Петербург
:::

[^1]: Третій спів півнів, удосвіта: тоді зникає нечиста сила.

# Заповіт {style="poem" kicker="Як умру, то поховайте"}

:::verse
Як умру, то поховайте
Мене на могилі[^2]
Серед степу широкого
На Вкраїні милій,
Щоб лани широкополі,
І Дніпро, і кручі
Було видно, було чути,
Як реве ревучий.

Як понесе з України
У синєє море
Кров ворожу… отойді я
І лани і гори —
Все покину, і полину
До самого Бога
Молитися… а до того
Я не знаю Бога.

Поховайте та вставайте,
Кайдани порвіте
І вражою злою кров’ю
Волю окропіте.
І мене в сем’ї великій,
В сем’ї вольній, новій,
Не забудьте пом’янути
Незлим тихим словом.
:::

:::paragraphs{style="date"}
25 грудня 1845, Переяслав
:::

[^2]: Тут: на кургані, степовому насипі над давнім похованням.

# Садок вишневий коло хати {style="poem" kicker="З циклу «В казематі»"}

:::verse
Садок вишневий коло хати,
Хрущі над вишнями гудуть.
Плугатарі з плугами йдуть,
Співають, ідучи, дівчата,
А матері вечерять ждуть.

Сем’я вечеря коло хати,
Вечірня зіронька встає.
Дочка вечерять подає,
А мати хоче научати,
Так соловейко не дає.

Поклала мати коло хати
Маленьких діточок своїх,
Сама заснула коло їх.
Затихло все, тілько дівчата
Та соловейко не затих.
:::

:::paragraphs{style="date"}
19–30 травня 1847, С.-Петербург
:::
`].join('\n\n');
const resources = Object.entries(ART).map(([id, { width, height }]) => ({ id, typeId: 'figure',
  kind: 'svg', createdAt: 0, updatedAt: 0, svg: { fileId: `${id}.svg`, width, height } }));

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { // every face the pages paint, loaded before the first build
  Vollkorn: ['400', '400i'], // TEXT: the poems, the notes, the note on the text, the heads
  'Yeseva One': ['400'], // DISPLAY: titles and folios
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
for (const [id, { markup }] of Object.entries(ART)) await loadSvg(`${id}.svg`, markup);
const doc = await buildDocumentWithFonts({ markdown, resources }, config(),
  kitCyrillicFonts(FONTS));
showPages(doc, { title: 'Кобзар' });
offerPdf(() => renderToPdf(doc, { fontProvider: cyrillicPdfProvider, 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 · 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 ───────────────────────────────────────────────────────────────────────
```

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

- **يرث نمط العنوان فاصل الصفحة من مستواه.** يأخذ مُدخل headingStyles كل حقل يتركه من مستوى عنوانه، بما فيه breakBefore. فصفحة المحتويات أو صفحة بيانات النشر المنسّقة على H1 بعد :::pagebreak ترث الزوجية 'odd' وتقع بعد صفحة فارغة. أعطِ هذا النمط breakBefore: { enabled: false }.

- اكتب الفاصلة العليا ’ (U+2019) في сем’ї وз’їли. أما ' المستقيمة فتُقرأ علامة قدم.
- يحدد نمط العنوان فاصله بنفسه: أعطِ `poem` قيمة `breakBefore` وإلا تبعت القصيدة سابقتها.
- قيمة `hyphenation` في نمط الفقرة منطقية. والنص بلغة أخرى يأخذ `:::paragraphs{lang="ar"}`، فتأتي معه أنماط تلك اللغة.
- تأكد من وجود ґ وє وі وї في خط العناوين قبل اختياره؛ كثير من الخطوط السيريلية يقف عند الروسية.

## الحقوق

- الوصفة: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- النص: Причинна (1837), lines 1–16, after the text of the Collected Works in six volumes, vol. 1 (Kyiv, 2003): Taras Shevchenko ([المصدر](http://litopys.org.ua/shevchenko/shev103.htm)), ملكية عامة
- النص: Заповіт (1845), whole, after the same edition, vol. 1: Taras Shevchenko ([المصدر](http://litopys.org.ua/shevchenko/shev146.htm)), ملكية عامة
- النص: Садок вишневий коло хати (1847), whole, after the same edition, vol. 2: Taras Shevchenko ([المصدر](http://litopys.org.ua/shevchenko/shev201.htm)), ملكية عامة
- النص: The note on the text, the footnotes and the colophon: Postext Cookbook, أصلي
- الخطوط: Vollkorn (OFL-1.1), Yeseva One (OFL-1.1)
- الشيفرة: MIT · محتوى المثال: MIT

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

- [رقم 015 · قصائد منضدة سطرًا سطرًا](https://postext.dev/ar/cookbook/poetry-collection.md): كل قصيدة كتلة :::verse مكتوبة كما تُطبع: إزاحات 1918 مسافات في أول السطر، وتتعلق التتمّات 2 em بعد سطرها، ويفصل سطر فارغ بين المقاطع. · المستوى 2 (متوسط) · الشعر
- [رقم 062 · شعر مُشكَّل: «Easter Wings» لهربرت، سطرًا سطرًا في الوسط](https://postext.dev/ar/cookbook/shaped-verse.md): قصيدتا Easter Wings وThe Altar لجورج هربرت منضّدتان نصَّ متن في الوسط، فقرة لكل بيت، فترسم أطوال الأسطر الشكلين. · المستوى 1 (أساسي) · الشعر
- [رقم 188 · رقائق ذهبية على غلاف أزرق داكن](https://postext.dev/ar/cookbook/gold-foil-poetry-cover.md): الرقائق الذهبية لون خاص له تشطيب: لوح خاص بها في PDF، ولمعان في Folio، وكرتون أزرق وورق كريمي لا يُطبع عليهما أي حبر. · المستوى 3 (متقدم) · الشعر
