# غلاف بنافذة تؤطّر صفحة العنوان

> نافذة بيضاوية مقصوصة في الغلاف بـ dieCuts، مقيسة على لوحة صفحة العنوان كي تقع حافتها على الإطار المذهّب، وخط القص على لوح خاص.

- نسخة HTML: https://postext.dev/ar/cookbook/die-cut-window-cover
- وصفة رقم 194 · الإخراج والدمج · المستوى 2 (متوسط) · المخرجات: Canvas, PDF, عناصر تحكم حية
- الأنواع: الأدب القصصي والمسرح والنثر الأدبي
- تتطلب postext ≥ 1.84.0, postext-pdf ≥ 1.84.0 · اختُبرت مع 1.84.0, postext-pdf 1.84.0 بتاريخ 2026-11-13
- الصفحات: [1](https://postext.dev/cookbook/die-cut-window-cover/en/p01.webp?v=6d3b96ec), [2](https://postext.dev/cookbook/die-cut-window-cover/en/p02.webp?v=6d3b96ec), [3](https://postext.dev/cookbook/die-cut-window-cover/en/p03.webp?v=6d3b96ec), [4](https://postext.dev/cookbook/die-cut-window-cover/en/p04.webp?v=6d3b96ec), [5](https://postext.dev/cookbook/die-cut-window-cover/en/p05.webp?v=6d3b96ec), [7](https://postext.dev/cookbook/die-cut-window-cover/en/p07.webp?v=6d3b96ec), [8](https://postext.dev/cookbook/die-cut-window-cover/en/p08.webp?v=6d3b96ec), [9](https://postext.dev/cookbook/die-cut-window-cover/en/p09.webp?v=6d3b96ec), [10](https://postext.dev/cookbook/die-cut-window-cover/en/p10.webp?v=6d3b96ec)
- PDF: https://postext.dev/cookbook/die-cut-window-cover/en/die-cut-window-cover.pdf?v=6d3b96ec
- افتح في Sandbox: https://postext.dev/ar/sandbox#recipe=die-cut-window-cover&lang=en (.postext: https://postext.dev/cookbook/die-cut-window-cover/en/die-cut-window-cover.postext)
- آخر تحديث: 2026-11-13
- لغات أخرى: [en](https://postext.dev/en/cookbook/die-cut-window-cover.md), [es](https://postext.dev/es/cookbook/die-cut-window-cover.md), [ca](https://postext.dev/ca/cookbook/die-cut-window-cover.md), [de](https://postext.dev/de/cookbook/die-cut-window-cover.md), [fr](https://postext.dev/fr/cookbook/die-cut-window-cover.md), [it](https://postext.dev/it/cookbook/die-cut-window-cover.md), [pt](https://postext.dev/pt/cookbook/die-cut-window-cover.md), [zh](https://postext.dev/zh/cookbook/die-cut-window-cover.md), [ja](https://postext.dev/ja/cookbook/die-cut-window-cover.md)

## باختصار

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

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

*The Oval Portrait* (وبالإسبانية *El retrato oval*)، قصة إدغار آلن بو المنشورة عام 1842 بنصّها الأقصر الذي طبعه عام 1845، في كتاب صغير مجلّد من عشر صفحات بقياس 130 × 195 مم. الغلاف دمقس قديم قُصّت فيه نافذة بيضاوية. وتحته صفحة العنوان، وهي اللوحة نفسها في إطارها المذهّب على الطراز المغربي، والنافذة موضوعة بحيث تقع حافتها على الذهب: والكتاب مغلق يظهر الوجه المرسوم مؤطّرًا مرتين، بالذهب وبالقص. وتلي القصة على ورق كريمي بحرف استهلالي كبير، ويعيد الغلاف الخلفي الدمقس مع التعريف في إطار داكن. ويحمل ملف المطبعة محيط النافذة على لوح خاص به.

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

- كيف أقصّ نافذة في غلاف كتاب بحيث تؤطّر صورة في الصفحة التي تحته؟
- كيف أسلّم صانع القالب خط القص على لوح خاص به في ملف PDF؟

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

```js
// script.js, سطرًا 41–48
// The window is cut through the first leaf, so the closed book shows page 3 through it.
// Its size is measured on the title-page painting: a little wider than the frame's opening,
// so the cut edge falls on the gilt and the face sits in the middle of the hole.
const dieCuts = {
  shapes: [{ id: 'window', name: t({ en: 'Oval window', es: 'Ventana oval' }),
    shape: 'ellipse', x: mm(26), y: mm(15.7), width: mm(78), height: mm(102) }],
  pages: [{ pages: '1', die: 'window' }], // page 1, the front board
};
```

## المكونات

**تعلّم**

- [فتحات مقصوصة بالقالب](https://postext.dev/ar/docs/special-inks-die-cuts.md#القص-بالقالب): تقصّ dieCuts.shapes وdieCuts.pages (أو حاوية :::diecut) فتحة في الصفحة وورقتها، ويلتفّ النص حولها على الوجهين.
- [خط القص في PDF](https://postext.dev/ar/docs/special-inks-die-cuts.md#خط-القص-في-ملف-pdf): ترسم print.dieLine كل فتحة وكل حافة مقصوصة على لوح Separation خاص بها، بطباعة فوقية ولا يُحبَّر أبدًا، لصانع القالب.

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

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

**واجهات API**

- [`buildDocumentWithFonts`](https://postext.dev/ar/docs/configuration-programmatic-usage.md#تحميل-الخطوط-قبل-الإخراج), [`createFolioFromDocument`](https://postext.dev/ar/docs/configuration-html-folio-epub.md#كتاب-ثلاثي-الأبعاد-postext-folio), [`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)

**الخطوط**

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

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

### 1 · نافذة مطابقة للإطار

الشيفرة هي [الجواب المختصر](https://postext.dev/ar/cookbook/die-cut-window-cover.md#الجواب-المختصر) أعلاه. النافذة `ellipse` في الصفحة 1، توضع من الزاوية العليا اليسرى لحدّ القص. الثقب في الصفحة 1 يطلّ على الصفحة 3، لذا يُقاس على لوحة صفحة العنوان: هنا قُرئت فتحة الإطار وحافته الخارجية بالبكسل على الصورة ثم حُوّلت إلى مليمترات، ووُضعت النافذة على ثلث عرض الشريط المذهّب، فتبقى داخل القص حلقة رفيعة من الذهب.

### 2 · لوحات معلّقة من حدّ القص

```js
// script.js, سطرًا 52–93
// Both paintings are placed in trim millimetres, the same frame the die is measured in. The
// portrait is set a little larger than the page so the frame is centred on it (and on the
// window); the cover type sits on a dark cartouche below the window.
const bleed = (x, y, width, height) => ({ kind: 'image', id: 'painting',
  resourceId: '{attr.picture}', fit: 'cover', placement: at('page', 'top-left', x, y,
    { width: mm(width), height: mm(height) }) });
const sheet = bleed(-BLEED, -BLEED, WIDTH + 2 * BLEED, HEIGHT + 2 * BLEED);
const portrait = bleed(-3.6, -BLEED, 140, 210); // its oval centred at x = WIDTH / 2
const box = (id, y, h) => ({ kind: 'box', id, placement: at('page', 'top-left', 17, y,
  { width: mm(WIDTH - 34), height: mm(h) }), style: { backgroundColor: col('plate'),
  borderColor: col('gold'), borderWidth: pt(0.75) } });
const type = (id, content, y, size, extra = {}) => ({ kind: 'text', id, content,
  fontFamily: DISPLAY, fontSize: pt(size), lineHeight: 1.1, color: col('gold'),
  align: 'center', placement: at('page', 'top-left', 17, y, { width: mm(WIDTH - 34) }),
  ...extra });
const caps = { fontWeight: 600, textTransform: 'uppercase', letterSpacing: pt(2.2) };
const full = (elements) => ({ enabled: true, minHeight: mm(HEIGHT - TOP),
  slot: { elements } });
const bare = { numbered: false, toc: false, header: { elements: [] },
  footer: { elements: [] } };
// A plate's section drops the foot margin, so its design reaches the foot of the page.
const flush = (top = TOP, side = 0) => ({ margins: { top: mm(top), bottom: mm(0),
  left: mm(INNER + side), right: mm(OUTER + side) } });
const dark = { palette: { paper: palette.velvet }, marginTop: pt(0), marginBottom: pt(0) };
const behind = (el) => ({ ...el, reserve: false }); // painted under the section's text
const headingStyles = [
  { id: 'cover', ...bare, ...dark, ...flush(), advancedDesign: full([sheet,
    box('plate', 130, 44), type('title', '{title}', 138, 27, { italic: true, fontWeight: 500 }),
    type('author', '{author}', 159, 9.5, caps)]) },
  { id: 'titlepage', ...bare, ...dark, ...flush(), breakBefore: { enabled: true, parity: 'odd' },
    advancedDesign: full([portrait, type('title', '{title}', 146, 30,
      { italic: true, fontWeight: 500 }), type('author', '{author}', 166, 10, caps)]) },
  { id: 'colophon', ...bare, hidden: true, ...flush(132), breakBefore: { parity: 'any' },
    bodyStyle: { fontSize: pt(9), lineHeight: pt(12.5), color: col('muted'), textAlign: 'left' } },
  { id: 'tale', numbered: false, toc: true, breakBefore: { enabled: true, parity: 'odd' },
    marginTop: mm(30), marginBottom: pt(28),
    dropCap: { lines: 3, fontFamily: DISPLAY, color: col('ink'), gap: mm(1.2) } },
  // The back: the damask again, and the copy set in gold on a cartouche.
  { id: 'back', ...bare, ...dark, ...flush(74, 10), breakBefore: { enabled: true,
    parity: 'even' }, advancedDesign: { enabled: true, slot: { elements: [behind(sheet),
      behind(box('plate', 62, 78))] } } },
];
```

يُقاس القالب بالمليمترات من حدّ القص، وكذلك اللوحات. يتجاوز الدمقس حدّ القص بمقدار الهامش الزائد من كل جهة؛ وتوضع اللوحة أعرض ببضعة مليمترات كي يقع الإطار في وسط الصفحة والنافذة. ويحذف الغلاف وصفحة العنوان الهامش السفلي، ويطبع كلٌّ منهما العنوان واسم المؤلف من frontmatter.

### 3 · خط القص على لوحه

```js
// script.js, سطرًا 105–106
  print: { standard: 'pdfx4', outputProfile: 'fogra51', convertImages: false,
    dieLine: { output: 'page', ink: 'Die', width: pt(0.5) } },
```

يطبع ملف PDF الغلاف كاملًا ويرسم محيط النافذة على فصل لوني `Die` بطباعة فوقية لا يُحبَّر أبدًا: يقرأ منه صانع القالب الشكل وتتخطاه المطبعة. ويُبقي `convertImages: false` اللوحات صور JPEG بألوان sRGB، وهو ما يسمح به PDF/X-4، فيبقى الملف دون الميغابايت.

### 4 · الكتاب المغلق على المكتب

```js
// script.js, سطرًا 128–134
  folio: {
    tilt: 34, yaw: 0,
    paper: { type: 'bookWove', shade: '#f6efe2' },
    binding: { type: 'hardcover', cover: 'pages', coverMaterial: 'paper' },
    surface: { type: 'walnut' },
    lighting: { environment: 'lamp', intensity: 1.15 },
  },
```

مع `binding.cover: 'pages'` تكون الصفحة الأولى هي الغلاف الأمامي، فيعرض Folio الكتاب مغلقًا والوجه في النافذة وجدران القص تلتقط ضوء المصباح. اقلب الغلاف لترى صفحة العنوان كاملة.

### 5 · غلاف مسطح يكشف ما تحته

```js
// script.js, سطرًا 211–219
const under = new Map();
const beneath = (i) => {
  if (!under.has(i) && doc.pages[i]) {
    const canvas = document.createElement('canvas');
    under.set(i, canvas);
    renderPageToCanvas(doc.pages[i], doc, canvas, { scale: 1, beneath });
  }
  return under.get(i);
};
```

على canvas تعطي `beneath` العارضَ الصفحة 3 لنافذة الغلاف، فيُظهر الغلاف المسطح الوجه أيضًا. ولا شيء تحت باطن الغلاف، فيُظهر ثقبه الخلفية.

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

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

- مجلد الوصفة: https://github.com/drnachio/postext/tree/main/cookbook/die-cut-window-cover

### script.js

```js
// ═══ Postext Cookbook · Nº 194 · A window cover that frames the title page ═══════════════
// https://postext.dev/en/cookbook/die-cut-window-cover
// Code: MIT · Text: Poe (PD) · Translation: CC BY 4.0 · Paintings: diffusion models
// Fonts: EB Garamond, Cormorant Garamond (SIL OFL 1.1) · Needs postext ≥ 1.84.0
//
// Poe's tale of a portrait in an oval frame, as a small hardback whose damask cover has an
// oval window cut through it. Closed, the book shows the face of the portrait on the title
// page through the window; the window's edge falls on the gilt of the painted frame.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
import { createFolioFromDocument } from 'https://esm.sh/postext-folio';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'die-cut-window-cover';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: ink on cream inside; gold on a near-black for the cover and its plates
const palette = {
  ink: '#2b2320', // the text
  paper: '#f6efe2', // a cream book wove
  velvet: '#2a0d10', // the wall behind the portrait, and the endpapers
  plate: '#160c0b', // the cartouches on the damask
  gold: '#d9b36c', // the title type, the colour of the painted frame
  muted: '#6f6158', // the note on the text
};
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: 'gold (defaults)', value: { hex: palette.gold, model: 'hex' } },
];
// #endregion
const [WIDTH, HEIGHT, BLEED] = [130, 195, 3]; // mm: a small hardback, and its bleed
const [TOP, FOOT, INNER, OUTER] = [18, 24, 16, 19];
const [TEXT, DISPLAY] = ['EB Garamond', 'Cormorant Garamond'];
const at = (to, edge, x = 0, y = 0, size) => ({ anchor: { to, edge },
  offset: { x: mm(x), y: mm(y) }, ...(size && { size }) });

// #region answer: one oval die through the cover, in register with the frame beneath
// The window is cut through the first leaf, so the closed book shows page 3 through it.
// Its size is measured on the title-page painting: a little wider than the frame's opening,
// so the cut edge falls on the gilt and the face sits in the middle of the hole.
const dieCuts = {
  shapes: [{ id: 'window', name: t({ en: 'Oval window', es: 'Ventana oval' }),
    shape: 'ellipse', x: mm(26), y: mm(15.7), width: mm(78), height: mm(102) }],
  pages: [{ pages: '1', die: 'window' }], // page 1, the front board
};
// #endregion

// #region plates: the paintings hung from the trim, and the type set on them
// Both paintings are placed in trim millimetres, the same frame the die is measured in. The
// portrait is set a little larger than the page so the frame is centred on it (and on the
// window); the cover type sits on a dark cartouche below the window.
const bleed = (x, y, width, height) => ({ kind: 'image', id: 'painting',
  resourceId: '{attr.picture}', fit: 'cover', placement: at('page', 'top-left', x, y,
    { width: mm(width), height: mm(height) }) });
const sheet = bleed(-BLEED, -BLEED, WIDTH + 2 * BLEED, HEIGHT + 2 * BLEED);
const portrait = bleed(-3.6, -BLEED, 140, 210); // its oval centred at x = WIDTH / 2
const box = (id, y, h) => ({ kind: 'box', id, placement: at('page', 'top-left', 17, y,
  { width: mm(WIDTH - 34), height: mm(h) }), style: { backgroundColor: col('plate'),
  borderColor: col('gold'), borderWidth: pt(0.75) } });
const type = (id, content, y, size, extra = {}) => ({ kind: 'text', id, content,
  fontFamily: DISPLAY, fontSize: pt(size), lineHeight: 1.1, color: col('gold'),
  align: 'center', placement: at('page', 'top-left', 17, y, { width: mm(WIDTH - 34) }),
  ...extra });
const caps = { fontWeight: 600, textTransform: 'uppercase', letterSpacing: pt(2.2) };
const full = (elements) => ({ enabled: true, minHeight: mm(HEIGHT - TOP),
  slot: { elements } });
const bare = { numbered: false, toc: false, header: { elements: [] },
  footer: { elements: [] } };
// A plate's section drops the foot margin, so its design reaches the foot of the page.
const flush = (top = TOP, side = 0) => ({ margins: { top: mm(top), bottom: mm(0),
  left: mm(INNER + side), right: mm(OUTER + side) } });
const dark = { palette: { paper: palette.velvet }, marginTop: pt(0), marginBottom: pt(0) };
const behind = (el) => ({ ...el, reserve: false }); // painted under the section's text
const headingStyles = [
  { id: 'cover', ...bare, ...dark, ...flush(), advancedDesign: full([sheet,
    box('plate', 130, 44), type('title', '{title}', 138, 27, { italic: true, fontWeight: 500 }),
    type('author', '{author}', 159, 9.5, caps)]) },
  { id: 'titlepage', ...bare, ...dark, ...flush(), breakBefore: { enabled: true, parity: 'odd' },
    advancedDesign: full([portrait, type('title', '{title}', 146, 30,
      { italic: true, fontWeight: 500 }), type('author', '{author}', 166, 10, caps)]) },
  { id: 'colophon', ...bare, hidden: true, ...flush(132), breakBefore: { parity: 'any' },
    bodyStyle: { fontSize: pt(9), lineHeight: pt(12.5), color: col('muted'), textAlign: 'left' } },
  { id: 'tale', numbered: false, toc: true, breakBefore: { enabled: true, parity: 'odd' },
    marginTop: mm(30), marginBottom: pt(28),
    dropCap: { lines: 3, fontFamily: DISPLAY, color: col('ink'), gap: mm(1.2) } },
  // The back: the damask again, and the copy set in gold on a cartouche.
  { id: 'back', ...bare, ...dark, ...flush(74, 10), breakBefore: { enabled: true,
    parity: 'even' }, advancedDesign: { enabled: true, slot: { elements: [behind(sheet),
      behind(box('plate', 62, 78))] } } },
];
// #endregion

const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(WIDTH), height: mm(HEIGHT), dpi: 150,
    backgroundColor: col('paper'), cutLines: { enabled: false, bleed: mm(BLEED) },
    margins: { top: mm(TOP), bottom: mm(FOOT), left: mm(INNER), right: mm(OUTER), mirror: true } },
  layout: { layoutType: 'single' },
  dieCuts,
  // #region die-line: the die line on its own plate, in a PDF/X-4 for the printer
  print: { standard: 'pdfx4', outputProfile: 'fogra51', convertImages: false,
    dieLine: { output: 'page', ink: 'Die', width: pt(0.5) } },
  // #endregion
  bodyText: { fontFamily: TEXT, fontSize: pt(10.5), lineHeight: pt(14), color: col('ink'),
    italicColor: col('ink'), boldColor: col('ink'), textAlign: 'justify',
    firstLineIndent: pt(12), paragraphSpacing: pt(0),
    hyphenation: { enabled: true }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: DISPLAY, color: col('ink'), textAlign: 'center', levels: [
    { level: 1, fontSize: pt(20), lineHeight: pt(24), italic: true, fontWeight: 500,
      marginTop: pt(0), marginBottom: pt(14) },
  ] },
  headingStyles,
  paragraphStyles: [{ id: 'blurb', fontFamily: DISPLAY, fontSize: pt(13), lineHeight: pt(17),
    color: col('gold'), textAlign: 'center', firstLineIndent: pt(0), hyphenation: false }],
  header: { elements: [['verso', 'even', '{author}'], ['recto', 'odd', '{title}']].map(
    ([id, parity, content]) => ({ kind: 'text', id, parity, content, fontFamily: TEXT,
      fontSize: pt(9), italic: true, color: col('muted'), align: 'center', pages: 'body',
      placement: at('page', 'top', 0, 10, { width: mm(80) }) })) },
  footer: { elements: [{ kind: 'text', id: 'folio', content: '{pageNumber}',
    fontFamily: TEXT, fontSize: pt(9), color: col('muted'), align: 'center',
    placement: at('page', 'bottom', 0, -12, { width: mm(20) }) }] },
  // #region folio: a small hardback with a printed cover, seen low across the window
  folio: {
    tilt: 34, yaw: 0,
    paper: { type: 'bookWove', shade: '#f6efe2' },
    binding: { type: 'hardcover', cover: 'pages', coverMaterial: 'paper' },
    surface: { type: 'walnut' },
    lighting: { environment: 'lamp', intensity: 1.15 },
  },
  // #endregion
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
// Cover, title page, note, the tale and the back: each a heading with a style. The cover
// and the title page print their title and author from the frontmatter.
const markdown = String.raw`---
title: "The Oval Portrait"
author: "Edgar Allan Poe"
---

# The Oval Portrait {style="cover" picture="damask"}

# The Oval Portrait {style="titlepage" picture="portrait"}

# Note on the text {style="colophon"}

Edgar Allan Poe’s tale first appeared as “Life in Death” in *Graham’s Magazine* in April 1842. This shorter text is the one he printed in the *Broadway Journal* in 1845, under the title it has kept since.

The cover is a damask with an oval window cut through it, and the window is the frame of the portrait beneath.

# 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 rarely, 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!”

# About the tale {style="back" picture="damask"}

:::paragraphs{style="blurb"}
A wounded traveller spends the night in a turret room hung with paintings. By candlelight he finds one he had not seen, the portrait of a young woman so alive that he shuts his eyes, and in the catalogue on his pillow he reads how it was painted.
:::
`; // content.<lang>.md, inlined by the Cookbook

const PICTURES = {
  damask: [t({ en: 'An old damask: gold pomegranates, lions and griffins on oxblood.',
    es: 'Un damasco antiguo: granadas, leones y grifos dorados sobre rojo sangre.' }), 1024, 1536],
  portrait: [t({ en: 'A young woman with dark curls, painted head and shoulders, in a gilded '
    + 'oval frame on a velvet wall.', es: 'Una muchacha de rizos oscuros, pintada de busto, en '
    + 'un marco oval dorado sobre una pared de terciopelo.' }), 1024, 1536],
};
const resources = Object.entries(PICTURES).map(([id, [alt, w, h]]) => ({ id,
  typeId: 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0, altText: alt,
  bitmap: { fileId: `${id}.jpg`, format: 'jpeg', width: w, height: h } }));
const FILES = { damask: asset('damask.jpg'), portrait: asset('portrait.jpg') };

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

// ─── 4 · Build & show ───────────────────────────────────────────────────────
await Promise.all(Object.entries(FILES).map(([id, url]) => loadImage(`${id}.jpg`, url)));
// The press file first, with bleed and marks; the screen's trimmed pages last.
const cut = { ...config.page.cutLines, enabled: true };
const pressConfig = { ...config, page: { ...config.page, cutLines: cut } };
const press = await buildDocumentWithFonts({ markdown, resources }, pressConfig, kitFonts(FONTS));
const doc = await buildDocumentWithFonts({ markdown, resources }, config, kitFonts(FONTS));

// #region folio-stage: the book closed on the desk, the face in the window
const stage = document.createElement('section');
stage.id = 'folio';
stage.ariaLabel = t({ en: 'The book in 3D', es: 'El libro en 3D' });
stage.style.cssText = 'height: min(78vh, 720px); margin: 0 auto; max-width: 1280px';
document.body.append(stage);
createFolioFromDocument(stage, doc, { at: 0,
  appearance: { textureBaseUrl: 'https://postext.dev/folio/textures' } });
// #endregion

// #region see-through: the flat cover shows the title page through its window
const under = new Map();
const beneath = (i) => {
  if (!under.has(i) && doc.pages[i]) {
    const canvas = document.createElement('canvas');
    under.set(i, canvas);
    renderPageToCanvas(doc.pages[i], doc, canvas, { scale: 1, beneath });
  }
  return under.get(i);
};
// #endregion
showPages(doc, { title: t({ en: 'The Oval Portrait · a window cover',
  es: 'El retrato oval · una cubierta con ventana' }), beneath });
document.getElementById('pages').before(stage);
offerPdf(() => renderToPdf(press, { fontProvider: fontsourceProvider, resourceBytes: imageBytes,
  profileBaseUrl: 'https://postext.dev/icc/' }), `${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 ───────────────────────────────────────────────────────────────────────
```

## تنويعات

### سمِّ اللوح كما تنتظره آلة القص

تبحث طاولات القص الرقمية عن لون خاص اسمه CutContour، أرجواني في الغالب، وعن خط رفيع جدًا.

```diff
-    dieLine: { output: 'page', ink: 'Die', width: pt(0.5) } },
+    dieLine: { output: 'page', ink: 'CutContour', cmyk: { c: 0, m: 100, y: 0, k: 0 },
+      width: pt(0.25) } },
```

### نافذة مستديرة

الدائرة تُظهر الوجه وحده، ويبقى الإطار مخفيًا تحت الغلاف حتى يُقلب.

```diff
-    shape: 'ellipse', x: mm(26), y: mm(15.7), width: mm(78), height: mm(102) }],
+    shape: 'circle', x: mm(32), y: mm(24), width: mm(66), height: mm(66) }],
```

## الحقوق

- الوصفة: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- النص: The Oval Portrait, in the text of the Broadway Journal (1845), from Project Gutenberg eBook 2147, with Poe’s “rarely” for the eBook’s “merely”: Edgar Allan Poe ([المصدر](https://www.gutenberg.org/ebooks/2147)), ملكية عامة
- النص: The Spanish translation, the note on the text and the back-cover copy: Postext Cookbook, CC-BY-4.0
- الصور: Cover and back: a pomegranate damask: Generated With Diffusion Models, أصلي
- الصور: Title page: the oval portrait on a velvet wall: Generated With Diffusion Models, أصلي
- الخطوط: EB Garamond (OFL-1.1), Cormorant Garamond (OFL-1.1)
- الشيفرة: MIT · محتوى المثال: CC-BY-4.0

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

- [رقم 024 · PDF جاهز للطباعة: النزف وعلامات القص وPDF/X](https://postext.dev/ar/cookbook/print-ready-pdf.md): مطوية معرض بنزف 3 مم وعلامات قص، مصدَّرة إلى PDF/X-4 على FOGRA51 مع نُسخ طباعة أصلية، ويمر الفحص قبل الطباعة دون ملاحظات. · المستوى 3 (متقدم) · الأوراق المفردة والمطبوعات العابرة
- [رقم 100 · كتاب مُخرَج على المكتب، بالأبعاد الثلاثة](https://postext.dev/ar/cookbook/folio-book-on-a-desk.md): تفتح الدالة createFolioFromDocument من الحزمة postext-folio فصلًا مُخرَجًا ككتاب مجلَّد بالقماش على مكتب من خشب الجوز، بمظهر يحدده config.folio. · المستوى 2 (متوسط) · الأدب القصصي والمسرح والنثر الأدبي
- [رقم 056 · محرّر حيّ يجري الإخراج في Web Worker](https://postext.dev/ar/cookbook/web-worker-live-editor.md): نص Markdown بجانب صفحة جيب: عامل Web Worker ينضّد الفصل بخطوطه الخاصة، وكل ضغطة مفتاح تلغي البناء الجاري. · المستوى 3 (متقدم) · الأدب القصصي والمسرح والنثر الأدبي
