# مربّعات نص الغلاف مثبّتة ومتسلسلة

> قصتان لبو في كتاب ذي غلاف ورقي، غلافه منضّد في ستة مربّعات نص معلّق بعضها ببعض: عنوان يطول مربّعه مع النص، وملخّص يكمل في مربّع ثانٍ.

- نسخة HTML: https://postext.dev/ar/cookbook/cover-text-boxes-anchored
- وصفة رقم 200 · الإخراج والدمج · المستوى 3 (متقدم) · المخرجات: Canvas, PDF
- الأنواع: الأدب القصصي والمسرح والنثر الأدبي
- تتطلب postext ≥ 1.93.0, postext-pdf ≥ 1.93.0 · اختُبرت مع 1.93.0, postext-pdf 1.93.0 بتاريخ 2026-11-23
- الصفحات: [1](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p01.webp?v=84557ea3), [3](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p03.webp?v=84557ea3), [4](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p04.webp?v=84557ea3), [5](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p05.webp?v=84557ea3), [6](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p06.webp?v=84557ea3), [15](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p15.webp?v=84557ea3), [21](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p21.webp?v=84557ea3), [1](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p22.webp?v=84557ea3)
- PDF: https://postext.dev/cookbook/cover-text-boxes-anchored/en/cover-text-boxes-anchored.pdf?v=84557ea3
- افتح في Sandbox: https://postext.dev/ar/sandbox#recipe=cover-text-boxes-anchored&lang=en (.postext: https://postext.dev/cookbook/cover-text-boxes-anchored/en/cover-text-boxes-anchored.postext)
- آخر تحديث: 2026-11-23
- لغات أخرى: [en](https://postext.dev/en/cookbook/cover-text-boxes-anchored.md), [es](https://postext.dev/es/cookbook/cover-text-boxes-anchored.md), [ca](https://postext.dev/ca/cookbook/cover-text-boxes-anchored.md), [de](https://postext.dev/de/cookbook/cover-text-boxes-anchored.md), [fr](https://postext.dev/fr/cookbook/cover-text-boxes-anchored.md), [it](https://postext.dev/it/cookbook/cover-text-boxes-anchored.md), [pt](https://postext.dev/pt/cookbook/cover-text-boxes-anchored.md), [zh](https://postext.dev/zh/cookbook/cover-text-boxes-anchored.md), [ja](https://postext.dev/ja/cookbook/cover-text-boxes-anchored.md)

## باختصار

كتاب صغير فيه قصتان لإدغار آلان بو، ومعه فرخ غلافه. كل نص على الغلاف يوضع تحت نص آخر أو فوقه أو بجانبه، فإذا طال العنوان نزل ما تحته، ويكمل نص الغلاف الخلفي تحت اقتباس.

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

قصتان لإدغار آلان بو، «قناع الموت الأحمر» و«الصورة البيضاوية» (الطبعة الإنجليزية بالنص الأصلي، والإسبانية بترجمة كارلوس أوليفيرا الصادرة عام 1884)، في كتاب ذي غلاف ورقي مقاسه 125 × 195 مم، ومعه فرخ غلافه. لا يحمل أي نص على الغلاف إحداثيات: كل نص مربّع معلّق بشيء آخر. على الغلاف الأمامي يتدلّى العنوان من أعلى اللوحة، ويتدلّى العنوان الفرعي من العنوان، ويقف اسم المؤلف على أسفلها. يحتاج العنوان إلى سطرين في الطبعتين، فيطول مربّعه وينزل العنوان الفرعي معه. وعلى الغلاف الخلفي يملأ الملخّص مربّعًا ارتفاعه 50 مم، وتكمل الأسطر التي لا تتسع لها في مربّع ثانٍ تحت اقتباس من القصة. وفوق الصفحات ترسم الوصفة الفرخ مرتين: كما يُطبع، ثم مع إطار حول كل مربّع وعلامة على التسلسل.

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

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

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

```js
// script.js, سطرًا 29–54
// A box anchored to a zone stands on that point of the zone's safe area; a box anchored to
// another box hangs below it, above it or beside it. With an anchor, `rect` gives only the
// size. The title may grow to 40 mm before its type shrinks, and the blurb sends the lines
// it cannot hold to the box under the quotation.
const size = (width, height) => ({ x: 0, y: 0, width, height });
const textBoxes = [
  // Front: the title from the top of the panel, the subtitle hung under it, the author
  // standing on the foot. Only the title's box grows; the subtitle follows it down.
  { name: 'title', rect: size(100, 14), anchor: { to: 'front', edge: 'top', y: 8 },
    maxHeight: 40 },
  { name: 'subtitle', rect: size(100, 9), anchor: { to: 'title', edge: 'below', y: 2 } },
  { name: 'author', rect: size(100, 8), anchor: { to: 'front', edge: 'bottom', y: -6 } },
  // Back: the blurb, a quotation under it, and the rest of the blurb under the quotation.
  // What the blurb's 50 mm cannot hold goes on in `blurb-end`, cut between lines.
  { name: 'blurb', rect: size(94, 50), anchor: { to: 'back', edge: 'top', y: 6 },
    next: 'blurb-end' },
  { name: 'quote', rect: size(94, 24), anchor: { to: 'blurb', edge: 'below', y: 5 },
    verticalAlign: 'middle' },
  { name: 'blurb-end', rect: size(94, 46), anchor: { to: 'quote', edge: 'below', y: 5 } },
];
const cover = {
  background: col('night'),
  elements: [{ id: 'art', kind: 'image', zone: 'front', x: 0, y: -3, width: 128, height: 201,
    resourceId: 'masque', fit: 'cover' }],
  textBoxes,
};
```

## المكونات

**تعلّم**

- [مربّعات نص الغلاف](https://postext.dev/ar/docs/print-covers.md#مربّعات-النص): تضيف cover.textBoxes إطارات نصية إلى فرخ الغلاف، يوضع كلٌّ منها بمستطيله rect أو يُثبَّت إلى المنطقة الآمنة للوحة أو إلى مربّع آخر (تحته أو فوقه أو بجانبه)؛ وتُكمل next نصّه في مربّع آخر، وتتيح maxHeight أن يطول مع نصّه، وتحدّد fit مقدار ما يصغر خطّه.
- [فرخ الغلاف](https://postext.dev/ar/docs/print-covers.md#الفرخ-ولوحاته): تُخرج buildCover فرخ نسخة مطبوعة: الغلاف الخلفي والكعب والغلاف الأمامي، مع الألسنة، أو غلاف التجليد المقوّى وسترته وأوراق البطانة، بالنزف وعلامات الطيّ. ويصمّمه إعداد cover ويملأ لوحاته مستند Markdown من الكتاب.

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

- [إطارات نص متسلسلة](https://postext.dev/ar/docs/composed-pages.md#ربط-الإطارات-بالتسلسل)
- [النسخ المطبوعة والردمك والكعب](https://postext.dev/ar/docs/print-covers.md#نسخ-الكتاب)
- [الأغلفة وصفحات العنوان وبيانات النشر](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين)
- [أنماط العناوين](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين)
- [صفحات افتتاح مصمَّمة](https://postext.dev/ar/docs/configuration-headings.md#الامتداد-والتصميم-المتقدم)
- [النصوص والخطوط والمربعات في تصاميم الصفحة](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات)
- [البيانات الوصفية للمستند](https://postext.dev/ar/docs/document-format.md#البيانات-التمهيدية-frontmatter)
- [أنماط الفقرات](https://postext.dev/ar/docs/configuration-styles.md#أنماط-الفقرات)
- [الترويسات وأرقام الصفحات](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات)
- [الأشكال والجداول بوصفها موارد](https://postext.dev/ar/docs/document-format-resources.md#الموارد)
- [لوحة ألوان دلالية](https://postext.dev/ar/docs/configuration-fonts-colors-viewers.md#لوحة-الألوان)
- [التصدير إلى PDF](https://postext.dev/ar/docs/configuration-pdf-output.md#توليد-ملفات-pdf)
- [صفحات على اللوحة (Canvas)](https://postext.dev/ar/docs/configuration-programmatic-usage.md#رسم-صفحة-في-صورة-نقطية)
- [الورق والتجليد والمكتب والإضاءة (Folio)](https://postext.dev/ar/docs/configuration-fonts-colors-viewers.md#عارض-folio-الإعدادات)
- [سمات العنوان](https://postext.dev/ar/docs/document-format.md#سمات-العناوين)
- [لون الورق](https://postext.dev/ar/docs/configuration-page-layout.md#الصفحة)
- [الترويسات بحسب دور الصفحة](https://postext.dev/ar/docs/configuration-headers-footers.md#عناصر-النص)
- [الخطوط المضمَّنة في PDF](https://postext.dev/ar/docs/configuration-pdf-output.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#لوحة-الألوان), [`cover`](https://postext.dev/ar/docs/print-covers.md#تصميم-الغلاف), [`folio`](https://postext.dev/ar/docs/configuration-html-folio-epub.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#أنماط-الفقرات), [`production`](https://postext.dev/ar/docs/print-covers.md#نسخ-الكتاب)

**واجهات API**

- [`buildCover`](https://postext.dev/ar/docs/print-covers.md#من-الشيفرة), [`buildDocumentWithFonts`](https://postext.dev/ar/docs/configuration-programmatic-usage.md#تحميل-الخطوط-قبل-الإخراج), [`decompressWoff2`](https://postext.dev/ar/docs/configuration-pdf-output.md#مزوّد-الخطوط-في-المتصفح-fontsource--woff2), [`inlineSvgFonts`](https://postext.dev/ar/docs/configuration-resources.md#الخطوط-في-نصوص-svg), [`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)

**الخطوط**

- EB Garamond (OFL-1.1), Cinzel (OFL-1.1)

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

### 1 · كل مربّع معلّق بلوحة أو بمربّع آخر

الشيفرة هي [الجواب المختصر](https://postext.dev/ar/cookbook/cover-text-boxes-anchored.md#الجواب-المختصر) أعلاه. يسمّي `anchor` لوحة من الفرخ أو مربّع نص آخر، ونقطة. على اللوحة تكون النقطة واحدة من النقاط التسع لمنطقتها الآمنة، ويضع المربّع نقطته المقابلة عليها: `edge: 'top'` يوسّط العنوان على الغلاف الأمامي ويضع حافته العليا على حافة المنطقة الآمنة العليا، و`edge: 'bottom'` يضع أسفل مربّع المؤلف على أسفل اللوحة. وعلى المربّع يمكن أن تكون النقطة أيضًا `below` أو `above` أو `right-of` أو `left-of`. و`x` و`y` يزيحان المربّع عن تلك النقطة بالمليمتر. ومع التثبيت لا يعطي `rect` إلا المقاس، فتبقى المربّعات في أماكنها إذا ثخن الكعب أو تغيّر قطع الكتاب.

### 2 · يطول العنوان فينزل العنوان الفرعي

```js
// script.js, سطرًا 68–84
const style = (id, fontFamily, size, lead, color, extra) => ({ id, fontFamily, fontSize: pt(size),
  lineHeight: pt(lead), color, italicColor: color, firstLineIndent: mm(0), textAlign: 'left',
  hyphenation: false, ...extra });
const mid = { textAlign: 'center' };
const caps = (tracking) => ({ fontWeight: 600, letterSpacing: pt(tracking) });
const coverStyles = [
  style('cover-title', 'Cinzel', 30, 33, col('bone'), { ...mid, fontWeight: 500 }),
  style('cover-subtitle', 'EB Garamond', 14, 18, col('gold'), { ...mid, italic: true }),
  style('cover-author', 'Cinzel', 10, 13, col('bone'), { ...mid, ...caps(2.2) }),
  style('cover-spine', 'Cinzel', 7, 8, col('bone'), { ...mid, ...caps(1.1) }),
  style('cover-blurb', 'EB Garamond', 10.5, 14.5, col('bone'), { textAlign: 'justify',
    hyphenation: true, firstLineIndent: mm(4) }),
  style('cover-blurb-first', 'EB Garamond', 10.5, 14.5, col('bone'), { textAlign: 'justify',
    hyphenation: true }),
  style('cover-quote', 'EB Garamond', 15, 19, col('gold'), { ...mid, italic: true }),
  style('cover-note', 'Cinzel', 7.5, 11, col('gold'), { ...caps(1.4), marginTop: pt(8) }),
];
```

العنوان منضّد بخط Cinzel بحجم 30 نقطة وتباعد أسطر 33. ارتفاع مربّعه 14 مم، أي سطر واحد. يحتاج «The Masque of the Red Death» و«La máscara de la muerte» إلى سطرين، فيطول المربّع مع النص حتى 40 مم هي `maxHeight`، ولا يصغر الحرف إلا بعد تجاوزها. والعنوان الفرعي مثبّت `below` العنوان على بعد 2 مم، فينزل بقدر السطر الثاني. أما المؤلف فمثبّت إلى أسفل اللوحة ولا يتحرك.

### 3 · يكمل الملخّص في مربّع آخر

يحمل مربّع الملخّص `next: 'blurb-end'`. ما لا يتسع له يُقطع بين سطرين ويكمل في ذلك المربّع، وليس له إطار خاص في ملف Markdown الخاص بالغلاف. يتدلّى الاقتباس من الملخّص، و`blurb-end` من الاقتباس، فتبقى المسافات بين الثلاثة كما هي إذا زاد ارتفاع المربّع الأول. ولا يصغر نص السلسلة، كله دفعة واحدة، إلا إذا ضاق المربّع الثاني أيضًا، وحدّه الافتراضي 90 % (`fit.minScale`). والسطر المنضّد بالحروف الكبيرة الصغيرة الذهبية هو آخر فقرة في إطار الملخّص، ولذلك يختم النص في المربّع الثاني:

```md
:::frame{slot="front"}
:::

:::frame{slot="blurb"}
:::paragraphs{style="cover-blurb-first"}
While a plague empties his country, Prince Prospero shuts himself up …
:::

:::paragraphs{style="cover-note"}
From the Raven Edition of Poe's works
:::
:::
```

الإطار `front` الفارغ يمنع `buildCover` من وضع العنوان والعنوان الفرعي واسم المؤلف من البيانات الوصفية للكتاب على الغلاف الأمامي: فالمربّعات هي التي تضعها هنا.

### 4 · كتاب ذو غلاف ورقي يُحسب كعبه من الصفحات

```js
// script.js, سطرًا 58–64
const production = {
  bindings: [{ id: 'pur', name: 'PUR perfect binding', style: 'perfect', signature: 16,
    measures: { bleed: 3, spineAllowance: 0.5 } }],
  versions: [{ id: 'paperback', name: t({ en: 'Paperback', es: 'Rústica' }), binding: 'pur',
    isbn: '978-84-0000-200-8', spineText: { minSpine: 4.5 } }],
};
const folio = { paper: { type: 'bookWove', grammage: 120, bulk: 2.2, shade: '#f8f3e8' } };
```

تجليد PUR بالغراء في ملازم من 16 صفحة، على ورق كتب وزنه 120 غ/م² وانتفاخه 2.2. في الكتاب 21 صفحة، تصير 32 بعد التجليد، فيبلغ الكعب نحو 4.7 مم، وهو دون الـ6 مم التي يُكتب على الكعب ابتداءً منها افتراضيًا؛ لذلك تضبط النسخة `spineText.minSpine` على 4.5، ويحمل الكعب العنوان واسم المؤلف. الردمك رقم للعرض لا يخص أي كتاب.

### 5 · متن الكتاب

```js
// script.js, سطرًا 88–128
const [W, H, TOP, FOOT, INNER, OUTER, LEAD] = [125, 195, 21, 23, 18, 16, 14.6]; // mm, pt
const at = (to, edge, x, y, box) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(box && { size: box }) });
const text = (id, content, look, place) => ({ kind: 'text', id, content, align: 'center',
  overflow: 'wrap', placement: place, ...look });
const face = (fontFamily, size, color, x) => ({ fontFamily, fontSize: pt(size), color, ...x });
const label = (size, color = col('muted')) => face('Cinzel', size, color, caps(size / 6));
const titling = (size, extra) => face('Cinzel', size, col('ink'), { fontWeight: 500, ...extra });
const none = { header: { elements: [] }, footer: { elements: [] }, numbered: false, toc: false };
const design = (minHeight, elements) => ({ enabled: true, minHeight: mm(minHeight),
  slot: { elements } });
const page = (parity) => ({ breakBefore: { enabled: true, parity } });
const rule = (id, y, to = 'page') => ({ kind: 'rule', id, direction: 'horizontal',
  thickness: pt(0.6), color: col('accent'), placement: at(to, 'top', 0, y, { width: mm(12) }) });
const wide = { width: mm(84) };
const headingStyles = [
  { ...none, id: 'half-title', advancedDesign: design(60, [
    text('t', '{title}', titling(12), at('page', 'top', 0, 62, wide))]) },
  // The title runs to two lines at 22 pt in both editions; the subtitle sits under them.
  { ...none, ...page('odd'), id: 'title-page', advancedDesign: design(H - TOP - FOOT, [
    text('t', '{title}', titling(22, { lineHeight: pt(27) }), at('page', 'top', 0, 44, wide)),
    text('s', '{subtitle}', face('EB Garamond', 13, col('ink'), { italic: true }),
      at('page', 'top', 0, 67)),
    rule('r', 77),
    text('a', '{author}', label(8.5, col('accent')), at('page', 'top', 0, 82)),
    text('c', '{attr.credit}', face('EB Garamond', 10, col('muted'), { italic: true }),
      at('page', 'top', 0, 118, { width: mm(76) })),
    text('i', '{attr.imprint}', label(7.5), at('page', 'bottom', 0, -26)),
  ]) },
  { ...none, ...page('even'), id: 'rights',
    advancedDesign: design(90, [rule('r', 84, 'container')]) },
  // Each tale opens on a recto, sunk 50 mm, its title on one line of Cinzel over a short rule.
  { ...page('odd'), id: 'tale', toc: false, header: { elements: [] }, advancedDesign: design(50, [
    text('t', '{titleText}', titling(13.5, { letterSpacing: pt(0.6) }),
      at('container', 'top', 0, 24, { width: mm(W - INNER - OUTER) })),
    rule('r', 40, 'container')]) },
  { ...none, ...page('odd'), id: 'colophon', advancedDesign: design(70, [
    rule('r', 62, 'container')]) },
];
const head = (id, content, parity) => text(id, content, { ...label(6.6), parity, pages: 'body' },
  at('page', 'top', 0, 11));
```

صفحة العنوان المختصر، فصفحة العنوان، فصفحة الحقوق، ثم تبدأ كل قصة على صفحة فردية منخفضة 50 مم، تحت عنوانها بخط Cinzel وخط أحمر قصير. تحمل الترويسات اسم المؤلف في الصفحة الزوجية وعنوان القصة في الفردية، وتختم صفحة البيانات الختامية الكتاب على آخر صفحة فردية.

### 6 · الفرخ يُبنى من الصفحات المنضدة

```js
// script.js, سطرًا 293–301
const built = buildCover({ config, version: 'paperback', pages: book.pages, markdown: coverText,
  metadata: book.metadata, resources });
if (!('config' in built)) throw new Error(built.issues.map((i) => i.kind).join(', '));
// The barcode's digits name OCR-B, which no font server has: the label face sets them.
for (const [id, bytes] of Object.entries(built.files)) {
  await loadSvg(id, new TextDecoder().decode(bytes)
    .replace(/font-family="[^"]*"/g, 'font-family="Cinzel"'));
}
const sheet = await buildDocumentWithFonts(built.content, built.config, kitFonts(FONTS));
```

تأخذ `buildCover` الصفحات والبيانات الوصفية وملف Markdown الخاص بالغلاف، وتعيد مستندًا من صفحة واحدة هي الفرخ. وتصير مربّعات النص إطارات في تلك الصفحة، تُنضّد كما تُنضّد إطارات الصفحة المركّبة. أرقام الرمز الشريطي تطلب خط OCR-B، ولا يوفره أي خادم خطوط، فتنضدها الوصفة بخط Cinzel.

### 7 · أين استقر كل مربّع

```js
// script.js, سطرًا 308–365
// Each text box comes back as a frame of the sheet's composed page, with the rect it was
// given after anchoring and growing, and `continuesTo` when its text goes on elsewhere.
const leaf = sheet.pages[0];
const scale = 1100 / leaf.width;
const names = new Set(textBoxes.map((b) => b.name));
const frames = (leaf.composed?.frames ?? []).filter((f) => names.has(f.name));
const views = document.createElement('section');
views.id = 'box-views';
views.style.cssText = 'display: grid; gap: 18px; '
  + 'grid-template-columns: repeat(auto-fit, minmax(300px, 600px)); justify-content: center; '
  + 'padding: 24px 16px; color: #ddd; font: 14px sans-serif';
for (const [mode, name] of [['flat', t({ en: 'As it prints', es: 'Como se imprime' })],
  ['boxes', t({ en: 'The text boxes', es: 'Las cajas de texto' })]]) {
  const [figure, canvas, caption] = ['figure', 'canvas', 'figcaption']
    .map((tag) => document.createElement(tag));
  figure.style.cssText = 'margin: 0; min-width: 0';
  canvas.setAttribute('role', 'img');
  canvas.setAttribute('aria-label', `${t({ en: 'The cover sheet', es: 'El pliego' })}: ${name}`);
  renderPageToCanvas(leaf, sheet, canvas, { scale });
  if (mode === 'boxes') {
    // Each box outlined and named; a chain drawn from the foot of a box to its next.
    const ctx = canvas.getContext('2d');
    ctx.setTransform(scale, 0, 0, scale, 0, 0);
    ctx.lineWidth = 2 / scale;
    ctx.font = `${13 / scale}px sans-serif`;
    for (const f of frames) {
      const { x, y, width, height } = f.rect;
      ctx.strokeStyle = ctx.fillStyle = '#f2c14e';
      ctx.setLineDash([8 / scale, 5 / scale]);
      ctx.strokeRect(x, y, width, height);
      ctx.setLineDash([]);
      // The name on a dark tab over the box's top-left corner, clear of the text.
      const tab = ctx.measureText(f.name).width + 10 / scale;
      ctx.fillStyle = '#141117';
      ctx.fillRect(x, y - 18 / scale, tab, 18 / scale);
      ctx.fillStyle = '#f2c14e';
      ctx.fillText(f.name, x + 5 / scale, y - 5 / scale);
      const next = frames.find((g) => g.id === f.continuesTo);
      if (next) {
        ctx.strokeStyle = '#ff7a59';
        // Out of the box's foot, down its right side, into the top of the next.
        const side = Math.max(x + width, next.rect.x + next.rect.width) + 14 / scale;
        ctx.beginPath();
        ctx.moveTo(x + width - 20 / scale, y + height);
        ctx.lineTo(side, y + height);
        ctx.lineTo(side, next.rect.y);
        ctx.lineTo(next.rect.x + next.rect.width - 20 / scale, next.rect.y);
        ctx.stroke();
      }
    }
  }
  // After the render, which sizes the canvas in CSS pixels: the column sets its width.
  canvas.style.cssText = 'display: block; width: 100%; height: auto';
  caption.textContent = name;
  figure.append(canvas, caption);
  views.append(figure);
}
document.getElementById('pages').before(views);
```

تعود صفحة الفرخ وإطاراتها في `page.composed.frames`، لكل منها المستطيل الذي أعطاه إياه التنضيد بعد التثبيت والإطالة، و`continuesTo` إذا كان نصه يكمل في إطار آخر. يحيط العرض الثاني المربّعات الستة بإطار فوق الفرخ، ويرسم التسلسل من أسفل الملخّص إلى أعلى `blurb-end`.

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

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

- مجلد الوصفة: https://github.com/drnachio/postext/tree/main/cookbook/cover-text-boxes-anchored

### script.js

```js
// ═══ Postext Cookbook · Nº 200 · Cover text boxes anchored, chained and grown ══════════════
// https://postext.dev/en/cookbook/cover-text-boxes-anchored
// Code: MIT · Text: E. A. Poe, tr. C. Olivera (public domain) · Art: diffusion models
// Fonts: EB Garamond, Cinzel (SIL OFL 1.1) · Needs postext ≥ 1.93.0
//
// Two of Poe's tales as a small paperback, and its cover sheet set from six text boxes.
// None of them has coordinates: each hangs from a panel of the sheet or from another box,
// so a title that runs to two lines takes the subtitle down with it, and the blurb on the
// back runs on under a quotation into a second box.
import { buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, inlineSvgFonts }
  from 'https://esm.sh/postext';
import { buildCover } from 'https://esm.sh/postext/production';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'cover-text-boxes-anchored';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// The pages' four colours, then the cover's: a night ground, bone type, a dull gold.
const palette = { ink: '#231f1c', accent: '#8e2219', muted: '#6a625a', paper: '#faf6ee',
  night: '#141117', bone: '#ece3cf', gold: '#c9a66b' };
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];

// #region answer: six text boxes placed against the panels and against each other
// A box anchored to a zone stands on that point of the zone's safe area; a box anchored to
// another box hangs below it, above it or beside it. With an anchor, `rect` gives only the
// size. The title may grow to 40 mm before its type shrinks, and the blurb sends the lines
// it cannot hold to the box under the quotation.
const size = (width, height) => ({ x: 0, y: 0, width, height });
const textBoxes = [
  // Front: the title from the top of the panel, the subtitle hung under it, the author
  // standing on the foot. Only the title's box grows; the subtitle follows it down.
  { name: 'title', rect: size(100, 14), anchor: { to: 'front', edge: 'top', y: 8 },
    maxHeight: 40 },
  { name: 'subtitle', rect: size(100, 9), anchor: { to: 'title', edge: 'below', y: 2 } },
  { name: 'author', rect: size(100, 8), anchor: { to: 'front', edge: 'bottom', y: -6 } },
  // Back: the blurb, a quotation under it, and the rest of the blurb under the quotation.
  // What the blurb's 50 mm cannot hold goes on in `blurb-end`, cut between lines.
  { name: 'blurb', rect: size(94, 50), anchor: { to: 'back', edge: 'top', y: 6 },
    next: 'blurb-end' },
  { name: 'quote', rect: size(94, 24), anchor: { to: 'blurb', edge: 'below', y: 5 },
    verticalAlign: 'middle' },
  { name: 'blurb-end', rect: size(94, 46), anchor: { to: 'quote', edge: 'below', y: 5 } },
];
const cover = {
  background: col('night'),
  elements: [{ id: 'art', kind: 'image', zone: 'front', x: 0, y: -3, width: 128, height: 201,
    resourceId: 'masque', fit: 'cover' }],
  textBoxes,
};
// #endregion

// #region binding: a slim paperback, its spine worked out from the pages
const production = {
  bindings: [{ id: 'pur', name: 'PUR perfect binding', style: 'perfect', signature: 16,
    measures: { bleed: 3, spineAllowance: 0.5 } }],
  versions: [{ id: 'paperback', name: t({ en: 'Paperback', es: 'Rústica' }), binding: 'pur',
    isbn: '978-84-0000-200-8', spineText: { minSpine: 4.5 } }],
};
const folio = { paper: { type: 'bookWove', grammage: 120, bulk: 2.2, shade: '#f8f3e8' } };
// #endregion

// #region cover-type: the paragraph styles the boxes are set in
const style = (id, fontFamily, size, lead, color, extra) => ({ id, fontFamily, fontSize: pt(size),
  lineHeight: pt(lead), color, italicColor: color, firstLineIndent: mm(0), textAlign: 'left',
  hyphenation: false, ...extra });
const mid = { textAlign: 'center' };
const caps = (tracking) => ({ fontWeight: 600, letterSpacing: pt(tracking) });
const coverStyles = [
  style('cover-title', 'Cinzel', 30, 33, col('bone'), { ...mid, fontWeight: 500 }),
  style('cover-subtitle', 'EB Garamond', 14, 18, col('gold'), { ...mid, italic: true }),
  style('cover-author', 'Cinzel', 10, 13, col('bone'), { ...mid, ...caps(2.2) }),
  style('cover-spine', 'Cinzel', 7, 8, col('bone'), { ...mid, ...caps(1.1) }),
  style('cover-blurb', 'EB Garamond', 10.5, 14.5, col('bone'), { textAlign: 'justify',
    hyphenation: true, firstLineIndent: mm(4) }),
  style('cover-blurb-first', 'EB Garamond', 10.5, 14.5, col('bone'), { textAlign: 'justify',
    hyphenation: true }),
  style('cover-quote', 'EB Garamond', 15, 19, col('gold'), { ...mid, italic: true }),
  style('cover-note', 'Cinzel', 7.5, 11, col('gold'), { ...caps(1.4), marginTop: pt(8) }),
];
// #endregion

// #region pages: the book block, two tales in a small paperback
const [W, H, TOP, FOOT, INNER, OUTER, LEAD] = [125, 195, 21, 23, 18, 16, 14.6]; // mm, pt
const at = (to, edge, x, y, box) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(box && { size: box }) });
const text = (id, content, look, place) => ({ kind: 'text', id, content, align: 'center',
  overflow: 'wrap', placement: place, ...look });
const face = (fontFamily, size, color, x) => ({ fontFamily, fontSize: pt(size), color, ...x });
const label = (size, color = col('muted')) => face('Cinzel', size, color, caps(size / 6));
const titling = (size, extra) => face('Cinzel', size, col('ink'), { fontWeight: 500, ...extra });
const none = { header: { elements: [] }, footer: { elements: [] }, numbered: false, toc: false };
const design = (minHeight, elements) => ({ enabled: true, minHeight: mm(minHeight),
  slot: { elements } });
const page = (parity) => ({ breakBefore: { enabled: true, parity } });
const rule = (id, y, to = 'page') => ({ kind: 'rule', id, direction: 'horizontal',
  thickness: pt(0.6), color: col('accent'), placement: at(to, 'top', 0, y, { width: mm(12) }) });
const wide = { width: mm(84) };
const headingStyles = [
  { ...none, id: 'half-title', advancedDesign: design(60, [
    text('t', '{title}', titling(12), at('page', 'top', 0, 62, wide))]) },
  // The title runs to two lines at 22 pt in both editions; the subtitle sits under them.
  { ...none, ...page('odd'), id: 'title-page', advancedDesign: design(H - TOP - FOOT, [
    text('t', '{title}', titling(22, { lineHeight: pt(27) }), at('page', 'top', 0, 44, wide)),
    text('s', '{subtitle}', face('EB Garamond', 13, col('ink'), { italic: true }),
      at('page', 'top', 0, 67)),
    rule('r', 77),
    text('a', '{author}', label(8.5, col('accent')), at('page', 'top', 0, 82)),
    text('c', '{attr.credit}', face('EB Garamond', 10, col('muted'), { italic: true }),
      at('page', 'top', 0, 118, { width: mm(76) })),
    text('i', '{attr.imprint}', label(7.5), at('page', 'bottom', 0, -26)),
  ]) },
  { ...none, ...page('even'), id: 'rights',
    advancedDesign: design(90, [rule('r', 84, 'container')]) },
  // Each tale opens on a recto, sunk 50 mm, its title on one line of Cinzel over a short rule.
  { ...page('odd'), id: 'tale', toc: false, header: { elements: [] }, advancedDesign: design(50, [
    text('t', '{titleText}', titling(13.5, { letterSpacing: pt(0.6) }),
      at('container', 'top', 0, 24, { width: mm(W - INNER - OUTER) })),
    rule('r', 40, 'container')]) },
  { ...none, ...page('odd'), id: 'colophon', advancedDesign: design(70, [
    rule('r', 62, 'container')]) },
];
const head = (id, content, parity) => text(id, content, { ...label(6.6), parity, pages: 'body' },
  at('page', 'top', 0, 11));
// #endregion

const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(W), height: mm(H), dpi: 300,
    backgroundColor: col('paper'),
    margins: { top: mm(TOP), bottom: mm(FOOT), left: mm(INNER), right: mm(OUTER), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'EB Garamond', fontSize: pt(11), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'justify', firstLineIndent: mm(4), indentAfterHeading: false, avoidWidows: true,
    hyphenation: { enabled: true }, optimalLineBreaking: true, avoidOrphans: true },
  headings: { fontFamily: 'Cinzel', color: col('ink'), textAlign: 'center' },
  headingStyles,
  paragraphStyles: [
    style('rights', 'EB Garamond', 8.5, 11.5, col('muted'), { marginBottom: pt(5) }),
    style('colophon', 'EB Garamond', 9.5, 13, col('muted'), { ...mid, italic: true }),
    ...coverStyles,
  ],
  header: { elements: [head('v', '{author}', 'even'), head('r', '{chapterTitle}', 'odd')] },
  footer: { elements: [text('f', '{pageNumber}', { ...face('EB Garamond', 9.5, col('ink')),
    pages: 'body' }, at('page', 'bottom', 0, -13))] },
  production, cover, folio,
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The book runs on through two files (each within the Cookbook's 2,500 words), cut between
// paragraphs. The cover's text is a third: a frame per text box.
const markdown = String.raw`---
title: "The Masque of the Red Death"
subtitle: "and The Oval Portrait"
author: "Edgar Allan Poe"
---

# The Masque of the Red Death {style="half-title"}

# The Masque of the Red Death {style="title-page" credit="Two tales, from the Raven Edition of his works" imprint="Taller de la Mar · Ocaña"}

# Rights {style="rights"}

:::paragraphs{style="rights"}
“The Masque of the Red Death” first appeared in *Graham’s Magazine* in May 1842 as “The Mask of the Red Death: A Fantasy”; “The Oval Portrait”, in the same magazine in April 1842 as “Life in Death”, and in the shorter form printed here in the *Broadway Journal* in 1845. The text follows the Raven Edition of *The Works of Edgar Allan Poe* (1903), Project Gutenberg eBooks 2147 and 2148, and is in the public domain.

Paperback · ISBN 978-84-0000-200-8 · a sample number, assigned to no book.

Cover: four colours on 300 g/m² board. Cover painting generated with diffusion models.

Set in EB Garamond and Cinzel (SIL OFL) on 120 g/m² cream book wove.
:::

# The Masque of the Red Death {style="tale"}

The “Red Death” had long devastated the country. No pestilence had ever been so fatal, or so hideous. Blood was its Avatar and its seal—the redness and the horror of blood. There were sharp pains, and sudden dizziness, and then profuse bleeding at the pores, with dissolution. The scarlet stains upon the body and especially upon the face of the victim, were the pest ban which shut him out from the aid and from the sympathy of his fellow-men. And the whole seizure, progress and termination of the disease, were the incidents of half an hour.

But the Prince Prospero was happy and dauntless and sagacious. When his dominions were half depopulated, he summoned to his presence a thousand hale and light-hearted friends from among the knights and dames of his court, and with these retired to the deep seclusion of one of his castellated abbeys. This was an extensive and magnificent structure, the creation of the prince’s own eccentric yet august taste. A strong and lofty wall girdled it in. This wall had gates of iron. The courtiers, having entered, brought furnaces and massy hammers and welded the bolts. They resolved to leave means neither of ingress or egress to the sudden impulses of despair or of frenzy from within. The abbey was amply provisioned. With such precautions the courtiers might bid defiance to contagion. The external world could take care of itself. In the meantime it was folly to grieve, or to think. The prince had provided all the appliances of pleasure. There were buffoons, there were improvisatori, there were ballet-dancers, there were musicians, there was Beauty, there was wine. All these and security were within. Without was the “Red Death.”

It was toward the close of the fifth or sixth month of his seclusion, and while the pestilence raged most furiously abroad, that the Prince Prospero entertained his thousand friends at a masked ball of the most unusual magnificence.

It was a voluptuous scene, that masquerade. But first let me tell of the rooms in which it was held. There were seven—an imperial suite. In many palaces, however, such suites form a long and straight vista, while the folding doors slide back nearly to the walls on either hand, so that the view of the whole extent is scarcely impeded. Here the case was very different; as might have been expected from the duke’s love of the bizarre. The apartments were so irregularly disposed that the vision embraced but little more than one at a time. There was a sharp turn at every twenty or thirty yards, and at each turn a novel effect. To the right and left, in the middle of each wall, a tall and narrow Gothic window looked out upon a closed corridor which pursued the windings of the suite. These windows were of stained glass whose color varied in accordance with the prevailing hue of the decorations of the chamber into which it opened. That at the eastern extremity was hung, for example, in blue—and vividly blue were its windows. The second chamber was purple in its ornaments and tapestries, and here the panes were purple. The third was green throughout, and so were the casements. The fourth was furnished and lighted with orange—the fifth with white—the sixth with violet. The seventh apartment was closely shrouded in black velvet tapestries that hung all over the ceiling and down the walls, falling in heavy folds upon a carpet of the same material and hue. But in this chamber only, the color of the windows failed to correspond with the decorations. The panes here were scarlet—a deep blood color. Now in no one of the seven apartments was there any lamp or candelabrum, amid the profusion of golden ornaments that lay scattered to and fro or depended from the roof. There was no light of any kind emanating from lamp or candle within the suite of chambers. But in the corridors that followed the suite, there stood, opposite to each window, a heavy tripod, bearing a brazier of fire that projected its rays through the tinted glass and so glaringly illumined the room. And thus were produced a multitude of gaudy and fantastic appearances. But in the western or black chamber the effect of the fire-light that streamed upon the dark hangings through the blood-tinted panes, was ghastly in the extreme, and produced so wild a look upon the countenances of those who entered, that there were few of the company bold enough to set foot within its precincts at all.

It was in this apartment, also, that there stood against the western wall, a gigantic clock of ebony. Its pendulum swung to and fro with a dull, heavy, monotonous clang; and when the minute-hand made the circuit of the face, and the hour was to be stricken, there came from the brazen lungs of the clock a sound which was clear and loud and deep and exceedingly musical, but of so peculiar a note and emphasis that, at each lapse of an hour, the musicians of the orchestra were constrained to pause, momentarily, in their performance, to hearken to the sound; and thus the waltzers perforce ceased their evolutions; and there was a brief disconcert of the whole gay company; and, while the chimes of the clock yet rang, it was observed that the giddiest grew pale, and the more aged and sedate passed their hands over their brows as if in confused reverie or meditation. But when the echoes had fully ceased, a light laughter at once pervaded the assembly; the musicians looked at each other and smiled as if at their own nervousness and folly, and made whispering vows, each to the other, that the next chiming of the clock should produce in them no similar emotion; and then, after the lapse of sixty minutes (which embrace three thousand and six hundred seconds of the Time that flies), there came yet another chiming of the clock, and then were the same disconcert and tremulousness and meditation as before.

But, in spite of these things, it was a gay and magnificent revel. The tastes of the duke were peculiar. He had a fine eye for colors and effects. He disregarded the decora of mere fashion. His plans were bold and fiery, and his conceptions glowed with barbaric lustre. There are some who would have thought him mad. His followers felt that he was not. It was necessary to hear and see and touch him to be sure that he was not.

He had directed, in great part, the moveable embellishments of the seven chambers, upon occasion of this great fête; and it was his own guiding taste which had given character to the masqueraders. Be sure they were grotesque. There were much glare and glitter and piquancy and phantasm—much of what has been since seen in “Hernani.” There were arabesque figures with unsuited limbs and appointments. There were delirious fancies such as the madman fashions. There was much of the beautiful, much of the wanton, much of the bizarre, something of the terrible, and not a little of that which might have excited disgust. To and fro in the seven chambers there stalked, in fact, a multitude of dreams. And these—the dreams—writhed in and about, taking hue from the rooms, and causing the wild music of the orchestra to seem as the echo of their steps. And, anon, there strikes the ebony clock which stands in the hall of the velvet. And then, for a moment, all is still, and all is silent save the voice of the clock. The dreams are stiff-frozen as they stand. But the echoes of the chime die away—they have endured but an instant—and a light, half-subdued laughter floats after them as they depart. And now again the music swells, and the dreams live, and writhe to and fro more merrily than ever, taking hue from the many-tinted windows through which stream the rays from the tripods. But to the chamber which lies most westwardly of the seven, there are now none of the maskers who venture; for the night is waning away; and there flows a ruddier light through the blood-colored panes; and the blackness of the sable drapery appals; and to him whose foot falls upon the sable carpet, there comes from the near clock of ebony a muffled peal more solemnly emphatic than any which reaches their ears who indulge in the more remote gaieties of the other apartments.
`;
const part2 = String.raw`But these other apartments were densely crowded, and in them beat feverishly the heart of life. And the revel went whirlingly on, until at length there commenced the sounding of midnight upon the clock. And then the music ceased, as I have told; and the evolutions of the waltzers were quieted; and there was an uneasy cessation of all things as before. But now there were twelve strokes to be sounded by the bell of the clock; and thus it happened, perhaps, that more of thought crept, with more of time, into the meditations of the thoughtful among those who revelled. And thus, too, it happened, perhaps, that before the last echoes of the last chime had utterly sunk into silence, there were many individuals in the crowd who had found leisure to become aware of the presence of a masked figure which had arrested the attention of no single individual before. And the rumor of this new presence having spread itself whisperingly around, there arose at length from the whole company a buzz, or murmur, expressive of disapprobation and surprise—then, finally, of terror, of horror, and of disgust.

In an assembly of phantasms such as I have painted, it may well be supposed that no ordinary appearance could have excited such sensation. In truth the masquerade license of the night was nearly unlimited; but the figure in question had out-Heroded Herod, and gone beyond the bounds of even the prince’s indefinite decorum. There are chords in the hearts of the most reckless which cannot be touched without emotion. Even with the utterly lost, to whom life and death are equally jests, there are matters of which no jest can be made. The whole company, indeed, seemed now deeply to feel that in the costume and bearing of the stranger neither wit nor propriety existed. The figure was tall and gaunt, and shrouded from head to foot in the habiliments of the grave. The mask which concealed the visage was made so nearly to resemble the countenance of a stiffened corpse that the closest scrutiny must have had difficulty in detecting the cheat. And yet all this might have been endured, if not approved, by the mad revellers around. But the mummer had gone so far as to assume the type of the Red Death. His vesture was dabbled in blood—and his broad brow, with all the features of the face, was besprinkled with the scarlet horror.

When the eyes of Prince Prospero fell upon this spectral image (which with a slow and solemn movement, as if more fully to sustain its role, stalked to and fro among the waltzers) he was seen to be convulsed, in the first moment with a strong shudder either of terror or distaste; but, in the next, his brow reddened with rage.

“Who dares?” he demanded hoarsely of the courtiers who stood near him—“who dares insult us with this blasphemous mockery? Seize him and unmask him—that we may know whom we have to hang at sunrise, from the battlements!”

It was in the eastern or blue chamber in which stood the Prince Prospero as he uttered these words. They rang throughout the seven rooms loudly and clearly—for the prince was a bold and robust man, and the music had become hushed at the waving of his hand.

It was in the blue room where stood the prince, with a group of pale courtiers by his side. At first, as he spoke, there was a slight rushing movement of this group in the direction of the intruder, who at the moment was also near at hand, and now, with deliberate and stately step, made closer approach to the speaker. But from a certain nameless awe with which the mad assumptions of the mummer had inspired the whole party, there were found none who put forth hand to seize him; so that, unimpeded, he passed within a yard of the prince’s person; and, while the vast assembly, as if with one impulse, shrank from the centres of the rooms to the walls, he made his way uninterruptedly, but with the same solemn and measured step which had distinguished him from the first, through the blue chamber to the purple—through the purple to the green—through the green to the orange—through this again to the white—and even thence to the violet, ere a decided movement had been made to arrest him. It was then, however, that the Prince Prospero, maddening with rage and the shame of his own momentary cowardice, rushed hurriedly through the six chambers, while none followed him on account of a deadly terror that had seized upon all. He bore aloft a drawn dagger, and had approached, in rapid impetuosity, to within three or four feet of the retreating figure, when the latter, having attained the extremity of the velvet apartment, turned suddenly and confronted his pursuer. There was a sharp cry—and the dagger dropped gleaming upon the sable carpet, upon which, instantly afterwards, fell prostrate in death the Prince Prospero. Then, summoning the wild courage of despair, a throng of the revellers at once threw themselves into the black apartment, and, seizing the mummer, whose tall figure stood erect and motionless within the shadow of the ebony clock, gasped in unutterable horror at finding the grave-cerements and corpse-like mask which they handled with so violent a rudeness, untenanted by any tangible form.

And now was acknowledged the presence of the Red Death. He had come like a thief in the night. And one by one dropped the revellers in the blood-bedewed halls of their revel, and died each in the despairing posture of his fall. And the life of the ebony clock went out with that of the last of the gay. And the flames of the tripods expired. And Darkness and Decay and the Red Death held illimitable dominion over all.

# The Oval Portrait {style="tale"}

The château into which my valet had ventured to make forcible entrance, rather than permit me, in my desperately wounded condition, to pass a night in the open air, was one of those piles of commingled gloom and grandeur which have so long frowned among the Appennines, not less in fact than in the fancy of Mrs. Radcliffe. To all appearance it had been temporarily and very lately abandoned. We established ourselves in one of the smallest and least sumptuously furnished apartments. It lay in a remote turret of the building. Its decorations were rich, yet tattered and antique. Its walls were hung with tapestry and bedecked with manifold and multiform armorial trophies, together with an unusually great number of very spirited modern paintings in frames of rich golden arabesque. In these paintings, which depended from the walls not only in their main surfaces, but in very many nooks which the bizarre architecture of the château rendered necessary—in these paintings my incipient delirium, perhaps, had caused me to take deep interest; so that I bade Pedro to close the heavy shutters of the room—since it was already night—to light the tongues of a tall candelabrum which stood by the head of my bed, and to throw open far and wide the fringed curtains of black velvet which enveloped the bed itself. I wished all this done that I might resign myself, if not to sleep, at least alternately to the contemplation of these pictures, and the perusal of a small volume which had been found upon the pillow, and which purported to criticise and describe them.

Long, long I read—and devoutly, devotedly I gazed. Rapidly and gloriously the hours flew by and the deep midnight came. The position of the candelabrum displeased me, and outreaching my hand with difficulty, rather than disturb my slumbering valet, I placed it so as to throw its rays more fully upon the book.

But the action produced an effect altogether unanticipated. The rays of the numerous candles (for there were many) now fell within a niche of the room which had hitherto been thrown into deep shade by one of the bed-posts. I thus saw in vivid light a picture all unnoticed before. It was the portrait of a young girl just ripening into womanhood. I glanced at the painting hurriedly, and then closed my eyes. Why I did this was not at first apparent even to my own perception. But while my lids remained thus shut, I ran over in my mind my reason for so shutting them. It was an impulsive movement to gain time for thought—to make sure that my vision had not deceived me—to calm and subdue my fancy for a more sober and more certain gaze. In a very few moments I again looked fixedly at the painting.

That I now saw aright I could not and would not doubt; for the first flashing of the candles upon that canvas had seemed to dissipate the dreamy stupor which was stealing over my senses, and to startle me at once into waking life.

The portrait, I have already said, was that of a young girl. It was a mere head and shoulders, done in what is technically termed a vignette manner; much in the style of the favorite heads of Sully. The arms, the bosom, and even the ends of the radiant hair melted imperceptibly into the vague yet deep shadow which formed the back-ground of the whole. The frame was oval, richly gilded and filigreed in Moresque. As a thing of art nothing could be more admirable than the painting itself. But it could have been neither the execution of the work, nor the immortal beauty of the countenance, which had so suddenly and so vehemently moved me. Least of all, could it have been that my fancy, shaken from its half slumber, had mistaken the head for that of a living person. I saw at once that the peculiarities of the design, of the vignetting, and of the frame, must have instantly dispelled such idea—must have prevented even its momentary entertainment. Thinking earnestly upon these points, I remained, for an hour perhaps, half sitting, half reclining, with my vision riveted upon the portrait. At length, satisfied with the true secret of its effect, I fell back within the bed. I had found the spell of the picture in an absolute life-likeliness of expression, which, at first startling, finally confounded, subdued, and appalled me. With deep and reverent awe I replaced the candelabrum in its former position. The cause of my deep agitation being thus shut from view, I sought eagerly the volume which discussed the paintings and their histories. Turning to the number which designated the oval portrait, I there read the vague and quaint words which follow:

“She was a maiden of rarest beauty, and not more lovely than full of glee. And evil was the hour when she saw, and loved, and wedded the painter. He, passionate, studious, austere, and having already a bride in his Art; she a maiden of rarest beauty, and not more lovely than full of glee; all light and smiles, and frolicsome as the young fawn; loving and cherishing all things; hating only the Art which was her rival; dreading only the pallet and brushes and other untoward instruments which deprived her of the countenance of her lover. It was thus a terrible thing for this lady to hear the painter speak of his desire to portray even his young bride. But she was humble and obedient, and sat meekly for many weeks in the dark, high turret-chamber where the light dripped upon the pale canvas only from overhead. But he, the painter, took glory in his work, which went on from hour to hour, and from day to day. And he was a passionate, and wild, and moody man, who became lost in reveries; so that he would not see that the light which fell so ghastly in that lone turret withered the health and the spirits of his bride, who pined visibly to all but him. Yet she smiled on and still on, uncomplainingly, because she saw that the painter (who had high renown) took a fervid and burning pleasure in his task, and wrought day and night to depict her who so loved him, yet who grew daily more dispirited and weak. And in sooth some who beheld the portrait spoke of its resemblance in low words, as of a mighty marvel, and a proof not less of the power of the painter than of his deep love for her whom he depicted so surpassingly well. But at length, as the labor drew nearer to its conclusion, there were admitted none into the turret; for the painter had grown wild with the ardor of his work, and turned his eyes from canvas merely, even to regard the countenance of his wife. And he would not see that the tints which he spread upon the canvas were drawn from the cheeks of her who sate beside him. And when many weeks had passed, and but little remained to do, save one brush upon the mouth and one tint upon the eye, the spirit of the lady again flickered up as the flame within the socket of the lamp. And then the brush was given, and then the tint was placed; and, for one moment, the painter stood entranced before the work which he had wrought; but in the next, while he yet gazed, he grew tremulous and very pallid, and aghast, and crying with a loud voice, ‘This is indeed Life itself!’ turned suddenly to regard his beloved:—She was dead!”

# Colophon {style="colophon"}

:::paragraphs{style="colophon"}
Taller de la Mar · Ocaña

Set in EB Garamond and Cinzel (SIL OFL) · Text in the public domain
:::
`;
const coverText = String.raw`:::frame{slot="front"}
:::

:::frame{slot="title"}
:::paragraphs{style="cover-title"}
The Masque of the Red Death
:::
:::

:::frame{slot="subtitle"}
:::paragraphs{style="cover-subtitle"}
and The Oval Portrait
:::
:::

:::frame{slot="author"}
:::paragraphs{style="cover-author"}
Edgar Allan Poe
:::
:::

:::frame{slot="blurb"}
:::paragraphs{style="cover-blurb-first"}
While a plague empties his country, Prince Prospero shuts himself up with a thousand of his courtiers in a fortified abbey, welds the gates behind them and gives a masked ball in a suite of seven rooms, each hung in one colour and lit through stained glass by a brazier. In the last room, black with windows the colour of blood, stands a clock of ebony that stops the music every hour.
:::

:::paragraphs{style="cover-blurb"}
Poe published the tale in *Graham’s Magazine* in May 1842, a month after “Life in Death”, the first version of “The Oval Portrait”. In that one a wounded traveller spends the night in an abandoned château in the Apennines and finds, by candlelight, the portrait of a young woman painted by her husband. The two tales run to some twenty pages together, and each takes place in a single night.
:::

:::paragraphs{style="cover-note"}
From the Raven Edition of Poe’s works
:::
:::

:::frame{slot="quote"}
:::paragraphs{style="cover-quote"}
And Darkness and Decay and the Red Death held illimitable dominion over all.
:::
:::
`;
const resources = [{ id: 'masque', typeId: 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: 'masque.jpg', format: 'jpeg', width: 1024, height: 1536 },
  altText: t({ en: 'A masked ball under a dark Gothic vault: a file of rooms lit blue, purple, '
    + 'green, orange, white and violet runs to a black room with blood-red windows; an ebony '
    + 'clock stands on the left, and a tall figure in a grave-shroud and a spattered mask '
    + 'stands still among the dancers.',
  es: 'Un baile de máscaras bajo una bóveda gótica en sombra: una hilera de salas iluminadas '
    + 'de azul, púrpura, verde, naranja, blanco y violeta termina en una sala negra de '
    + 'ventanas rojo sangre; a la izquierda, un reloj de ébano, y entre los danzantes, '
    + 'inmóvil, una figura alta con mortaja y una máscara salpicada.' }) }];
await loadImage('masque.jpg', asset('masque-1024.jpg'));

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { 'EB Garamond': ['400', '400i'], Cinzel: ['500', '600'] };

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const book = await buildDocumentWithFonts({ markdown: `${markdown}\n\n${part2}`, resources },
  config, kitFonts(FONTS));

// #region sheet: the cover sheet, built from the pages just laid out
const built = buildCover({ config, version: 'paperback', pages: book.pages, markdown: coverText,
  metadata: book.metadata, resources });
if (!('config' in built)) throw new Error(built.issues.map((i) => i.kind).join(', '));
// The barcode's digits name OCR-B, which no font server has: the label face sets them.
for (const [id, bytes] of Object.entries(built.files)) {
  await loadSvg(id, new TextDecoder().decode(bytes)
    .replace(/font-family="[^"]*"/g, 'font-family="Cinzel"'));
}
const sheet = await buildDocumentWithFonts(built.content, built.config, kitFonts(FONTS));
// #endregion

showPages(book, { title: t({ en: 'The Masque of the Red Death · a paperback and its cover',
  es: 'La máscara de la muerte · una rústica y su cubierta' }) });

// #region views: the sheet as it prints, then the boxes the layout placed
// Each text box comes back as a frame of the sheet's composed page, with the rect it was
// given after anchoring and growing, and `continuesTo` when its text goes on elsewhere.
const leaf = sheet.pages[0];
const scale = 1100 / leaf.width;
const names = new Set(textBoxes.map((b) => b.name));
const frames = (leaf.composed?.frames ?? []).filter((f) => names.has(f.name));
const views = document.createElement('section');
views.id = 'box-views';
views.style.cssText = 'display: grid; gap: 18px; '
  + 'grid-template-columns: repeat(auto-fit, minmax(300px, 600px)); justify-content: center; '
  + 'padding: 24px 16px; color: #ddd; font: 14px sans-serif';
for (const [mode, name] of [['flat', t({ en: 'As it prints', es: 'Como se imprime' })],
  ['boxes', t({ en: 'The text boxes', es: 'Las cajas de texto' })]]) {
  const [figure, canvas, caption] = ['figure', 'canvas', 'figcaption']
    .map((tag) => document.createElement(tag));
  figure.style.cssText = 'margin: 0; min-width: 0';
  canvas.setAttribute('role', 'img');
  canvas.setAttribute('aria-label', `${t({ en: 'The cover sheet', es: 'El pliego' })}: ${name}`);
  renderPageToCanvas(leaf, sheet, canvas, { scale });
  if (mode === 'boxes') {
    // Each box outlined and named; a chain drawn from the foot of a box to its next.
    const ctx = canvas.getContext('2d');
    ctx.setTransform(scale, 0, 0, scale, 0, 0);
    ctx.lineWidth = 2 / scale;
    ctx.font = `${13 / scale}px sans-serif`;
    for (const f of frames) {
      const { x, y, width, height } = f.rect;
      ctx.strokeStyle = ctx.fillStyle = '#f2c14e';
      ctx.setLineDash([8 / scale, 5 / scale]);
      ctx.strokeRect(x, y, width, height);
      ctx.setLineDash([]);
      // The name on a dark tab over the box's top-left corner, clear of the text.
      const tab = ctx.measureText(f.name).width + 10 / scale;
      ctx.fillStyle = '#141117';
      ctx.fillRect(x, y - 18 / scale, tab, 18 / scale);
      ctx.fillStyle = '#f2c14e';
      ctx.fillText(f.name, x + 5 / scale, y - 5 / scale);
      const next = frames.find((g) => g.id === f.continuesTo);
      if (next) {
        ctx.strokeStyle = '#ff7a59';
        // Out of the box's foot, down its right side, into the top of the next.
        const side = Math.max(x + width, next.rect.x + next.rect.width) + 14 / scale;
        ctx.beginPath();
        ctx.moveTo(x + width - 20 / scale, y + height);
        ctx.lineTo(side, y + height);
        ctx.lineTo(side, next.rect.y);
        ctx.lineTo(next.rect.x + next.rect.width - 20 / scale, next.rect.y);
        ctx.stroke();
      }
    }
  }
  // After the render, which sizes the canvas in CSS pixels: the column sets its width.
  canvas.style.cssText = 'display: block; width: 100%; height: auto';
  caption.textContent = name;
  figure.append(canvas, caption);
  views.append(figure);
}
document.getElementById('pages').before(views);
// #endregion

// One file for the printer: the pages, then the sheet at its own size.
offerPdf(() => renderToPdf([book, sheet], { fontProvider: fontsourceProvider,
  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 ───────────────────────────────────────────────────────────────────────
```

## تنويعات

### علّق اسم المؤلف تحت العنوان الفرعي

عندئذ يتبع المؤلفُ العنوانَ إلى الأسفل أيضًا، بدل أن يبقى على أسفل اللوحة.

```diff
-  { name: 'author', rect: size(100, 8), anchor: { to: 'front', edge: 'bottom', y: -6 } },
+  { name: 'author', rect: size(100, 8), anchor: { to: 'subtitle', edge: 'below', y: 6 } },
```

### صغّر العنوان الطويل إلى سطر واحد

من غير `maxHeight` يبقى مربّع العنوان على ارتفاعه 14 مم، ويصغّر التنضيد العنوان حتى يتسع له: هنا في سطر واحد، بنحو ثلثي حجمه.

```diff
   { name: 'title', rect: size(100, 14), anchor: { to: 'front', edge: 'top', y: 8 },
-    maxHeight: 40 },
+    fit: { minScale: 0.6 } },
```

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

- المربّع الذي يسمّيه `next` مربّع آخر يأخذ النص الذي يمرّره إليه ذلك المربّع. لا تعطه إطارًا خاصًا في ملف Markdown الخاص بالغلاف، واختم إطار المربّع الأول بما ينبغي أن يختم النص، كالملاحظة هنا.
- التثبيت الذي لا يسمّي شيئًا، أو يسمّي المربّع نفسه، أو يغلق حلقة، يُبلَّغ عنه، ويبقى المربّع على `rect` الخاص به. أعطِ كل مربّع مثبّت `rect` بمقاس حقيقي.
- لا تنطبق `maxHeight` على المربّع المدار (`rotate`)، فهو يحتفظ بمقاس `rect` الخاص به.

## الحقوق

- الوصفة: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- النص: The Masque of the Red Death and The Oval Portrait, from The Works of Edgar Allan Poe (Raven Edition, 1903), Project Gutenberg eBooks #2148 and #2147: Edgar Allan Poe ([المصدر](https://www.gutenberg.org/ebooks/2148)), ملكية عامة
- النص: La máscara de la muerte and El retrato oval, translated by Carlos Olivera, from Novelas y cuentos (Garnier Hermanos, Paris, 1884), as transcribed on Wikisource, spelling and punctuation modernised: Carlos Olivera ([المصدر](https://es.wikisource.org/wiki/Novelas_y_cuentos_(Poe))), ملكية عامة
- الصور: The cover painting: a masked ball in a file of coloured rooms under a Gothic vault, with an ebony clock and a figure in a grave-shroud, in oils: Generated With Diffusion Models, أصلي
- الخطوط: EB Garamond (OFL-1.1), Cinzel (OFL-1.1)
- الشيفرة: MIT · محتوى المثال: CC-BY-4.0

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

- [رقم 198 · مجلد من سلسلة، والسلسلة على أوراق بطانته](https://postext.dev/ar/cookbook/collection-volume-endpapers.md): المجلد الحادي عشر من سلسلة مجلدة في اثني عشر مجلدًا: رقما ردمك بجانب الشريط الرمزي، وغلاف مشترك بين المجلدات، والسلسلة كلها على أوراق البطانة. · المستوى 3 (متقدم) · الأدب القصصي والمسرح والنثر الأدبي
- [رقم 196 · غلاف كتاب ورقي بألسنة، وكعبه محسوب من الصفحات](https://postext.dev/ar/cookbook/paperback-cover-with-flaps.md): كتاب ورقي بقياس 120 × 190 مم وألسنة عرضها 60 مم: تُنضَّد الصفحات أولًا، ثم تصنع منها buildCover فرخ الغلاف، بكعب سمكه سمك ورقها. · المستوى 3 (متقدم) · الأدب القصصي والمسرح والنثر الأدبي
- [رقم 197 · الغلاف المقوّى والغلاف الواقي وأوراق البطانة](https://postext.dev/ar/cookbook/hardcover-jacket-and-endpapers.md): صفحات كتاب بغلاف ورقي تُجلَّد من جديد بالقماش: نسخة أخرى بردمكها، ويصنع buildCover الغلاف المقوّى والغلاف الواقي وورقتي البطانة. · المستوى 3 (متقدم) · الأدب القصصي والمسرح والنثر الأدبي
