# لوحات فنية داخل الهوامش وحتى حد القص وحتى النزف

> مقالة معرض عن أربع لوحات داخلية لفيرمير: كل لوحة في صفحة كاملة، داخل الهوامش أو حتى حد القص أو حتى النزف، وتفصيل بعرض 60 مم.

- نسخة HTML: https://postext.dev/ar/cookbook/art-plates-to-the-bleed
- وصفة رقم 183 · الأشكال والصور · المستوى 2 (متوسط) · المخرجات: Canvas, PDF
- الأنواع: الكتالوجات
- تتطلب postext ≥ 1.73.0, postext-pdf ≥ 1.73.0 · اختُبرت مع 1.73.0, postext-pdf 1.73.0 بتاريخ 2026-11-10
- الصفحات: [1](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p01.webp?v=98cf96f7), [2](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p02.webp?v=98cf96f7), [3](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p03.webp?v=98cf96f7), [4](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p04.webp?v=98cf96f7), [5](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p05.webp?v=98cf96f7), [6](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p06.webp?v=98cf96f7), [7](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p07.webp?v=98cf96f7)
- PDF: https://postext.dev/cookbook/art-plates-to-the-bleed/en/art-plates-to-the-bleed.pdf?v=98cf96f7
- افتح في Sandbox: https://postext.dev/ar/sandbox#recipe=art-plates-to-the-bleed&lang=en (.postext: https://postext.dev/cookbook/art-plates-to-the-bleed/en/art-plates-to-the-bleed.postext)
- آخر تحديث: 2026-11-10
- لغات أخرى: [en](https://postext.dev/en/cookbook/art-plates-to-the-bleed.md), [es](https://postext.dev/es/cookbook/art-plates-to-the-bleed.md), [ca](https://postext.dev/ca/cookbook/art-plates-to-the-bleed.md), [de](https://postext.dev/de/cookbook/art-plates-to-the-bleed.md), [fr](https://postext.dev/fr/cookbook/art-plates-to-the-bleed.md), [it](https://postext.dev/it/cookbook/art-plates-to-the-bleed.md), [pt](https://postext.dev/pt/cookbook/art-plates-to-the-bleed.md), [zh](https://postext.dev/zh/cookbook/art-plates-to-the-bleed.md), [ja](https://postext.dev/ja/cookbook/art-plates-to-the-bleed.md)

## باختصار

حدِّد إلى أين تمتد كل لوحة في صفحتها: داخل الهوامش، أو حتى حافة القص، أو أبعد منها، وأعطِ التفصيل عرضه بالمليمترات. وتتكوّن الصفحات من تلقاء نفسها.

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

سبع صفحات من كتالوج معرض صغير بمقاس 160 × 195 مم، عن أربع لوحات داخلية ليوهانس فيرمير من متحف رايكس ومتحف المتروبوليتان والمعرض الوطني للفنون. تبدأ المقالة في صفحة فردية بعنوان منخفض. وكل لوحة تذكرها تقف وحدها في الصفحة الكاملة التالية: «الخادمة التي تصب الحليب» في [الصفحة 2](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p02.webp?v=98cf96f7) داخل الهوامش وتحت ترويستها، و«امرأة شابة مع إبريق ماء» و«امرأة تقرأ رسالة» متقابلتان في [الصفحتين 4 و5](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p04.webp?v=98cf96f7)، الأولى عند حد القص والثانية ممتدة في النزف وراء علامات القص، وكلتاهما بلا ترويسة ولا رقم صفحة. ويُطبع تفصيل الميزان بعرض 60 مم في [الصفحة 7](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p07.webp?v=98cf96f7) وتعليقه بجانبه. ويحمل ملف PDF العلامات وTrimBox وBleedBox.

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

- كيف أطبع لوحة زيتية في صفحة كاملة، داخل الهوامش أو حتى حد القص أو حتى النزف؟
- كيف أصمم كتالوج فني: المدخل في الصفحة اليسرى، واللوحة في الصفحة اليمنى المقابلة؟
- كيف أُعدّ ملف PDF جاهزًا للطباعة فيه نزف وعلامات قص وإشارات مرجعية وتسميات صفحات وفضاء لوني؟

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

```js
// script.js, سطرًا 41–53
// Every plate stands alone on the first whole page after its citation, as large as the area
// allows. true (or 'content') keeps it inside the margins with its running heads; 'trim'
// covers the page to the cut, 'bleed' to the bleed. Those two crop the picture about its
// centre, put the caption on a band of paper at the foot, and drop the heads and the folio.
const plateType = { id: 'plate', name: t({ en: 'Plate', es: 'Lámina' }),
  shortLabel: t({ en: 'plate', es: 'lámina' }), captionPrefix: t({ en: 'Plate', es: 'Lámina' }),
  numberingTemplate: '{n}', resetOn: 'never', counterFormat: 'decimal',
  defaultPlacement: { plate: true, captionMeasure: 'body' } }; // the caption as wide as it
const REACH = { milkmaid: 'content', pitcher: 'trim', letter: 'bleed', balance: 'content' };
// A width as a length is measured against the slot, not shared out of it: the detail prints
// 60 mm wide in any layout, 1.25 times the 48 mm of canvas it shows. Its caption stands
// beside it in what is left of the column.
const DETAIL = { width: { value: 60, unit: 'mm' }, captionSide: 'inside', align: 'left' };
```

## المكونات

**تعلّم**

- [لوحات بصفحة كاملة](https://postext.dev/ar/docs/document-format-resources.md#الموضع): تضع الصورة وحدها في صفحة خاصة بها بأكبر حجم تتسع له منطقة المتن، أو على الصفحة كلها حتى حد القص أو حتى النزف، فتسقط عنها الترويسات ورقم الصفحة.
- [عرض الأشكال بالمليمترات](https://postext.dev/ar/docs/document-format-resources.md#الموضع): تعطي الشكل عرضه طولًا بالمليمتر أو السنتيمتر أو البوصة أو النقطة بدل نسبة من العمود، فيُطبع بالمقاس نفسه أيًّا كانت الخانة.

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

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

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

- [`bodyText`](https://postext.dev/ar/docs/configuration-text.md#نص-المتن), [`captionStyle`](https://postext.dev/ar/docs/configuration-resources.md#نمط-التعليقات), [`colorPalette`](https://postext.dev/ar/docs/configuration-fonts-colors-viewers.md#لوحة-الألوان), [`footer`](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات), [`header`](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات), [`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#أنماط-الفقرات), [`resourceTypes`](https://postext.dev/ar/docs/configuration-resources.md#أنواع-الموارد)

**واجهات API**

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

**الخطوط**

- Spectral (OFL-1.1), Cormorant Garamond (OFL-1.1), Jost (OFL-1.1)

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

### 1 · نوع واحد للوحات ومدى لكل لوحة

الشيفرة هي [الجواب المختصر](https://postext.dev/ar/cookbook/art-plates-to-the-bleed.md#الجواب-المختصر) أعلاه. يضع نوع اللوحات `plate: true` موضعًا افتراضيًا، فتنتقل اللوحة التي تذكرها المقالة إلى أول صفحة يمكن أن تشغلها كاملة، وتكبر حتى منطقة المتن وتعليقها تحتها. ويغيّر `REACH` ذلك لوحةً لوحة: `'trim'` و`'bleed'` تغطيان الصفحة وتقصّان الصورة حول مركزها، لذا يحسن اختيار لوحات قريبة من نسبة الصفحة (عرض هذه اللوحات من 0.85 إلى 0.89 لكل ارتفاع 1، والصفحة 0.82). ويجعل `captionMeasure: 'body'` تعليق اللوحة الداخلية بعرض الصورة.

### 2 · كل ملف على قدر المكان الذي يُطبع فيه

```js
// script.js, سطرًا 150–202
// JPEGs in assets/ at the pixels each needs for 300 ppi where it prints: 2,400 px high for
// the plates that cover the page (195 mm + 2 × 3 mm of bleed is 7.9 in), less for the rest.
const PAINTINGS = {
  milkmaid: [[1617, 1800], { en: 'Johannes Vermeer, *The Milkmaid*, c. 1660',
    es: 'Johannes Vermeer, *La lechera*, h. 1660' }, { en: 'Oil on canvas, 45.5 × 41 cm. '
    + 'Rijksmuseum, Amsterdam, SK-A-2344, purchased with the support of the Vereniging '
    + 'Rembrandt. Public domain.', es: 'Óleo sobre lienzo, 45,5 × 41 cm. Rijksmuseum, '
    + 'Ámsterdam, SK-A-2344, adquirido con el apoyo de la Vereniging Rembrandt. Dominio '
    + 'público.' }, { en: 'A kitchen maid in a yellow bodice and blue apron pours milk from '
    + 'a jug into a bowl beside a basket of bread, under a window on the left.', es: 'Una '
    + 'criada con corpiño amarillo y delantal azul vierte leche de una jarra en un cuenco, '
    + 'junto a un cesto de pan, bajo una ventana a la izquierda.' }],
  pitcher: [[2116, 2400], { en: 'Johannes Vermeer, *Young Woman with a Water Pitcher*, '
    + 'c. 1662', es: 'Johannes Vermeer, *Joven con una jarra de agua*, h. 1662' },
  { en: 'Oil on canvas, 45.7 × 40.6 cm. The Metropolitan Museum of Art, New York, 89.15.21, '
    + 'Marquand Collection, gift of Henry G. Marquand, 1889. Public domain.', es: 'Óleo sobre '
    + 'lienzo, 45,7 × 40,6 cm. The Metropolitan Museum of Art, Nueva York, 89.15.21, '
    + 'colección Marquand, donación de Henry G. Marquand, 1889. Dominio público.' },
  { en: 'A young woman in a white linen hood opens a window with one hand and holds a '
    + 'silver-gilt pitcher in a basin with the other; a map hangs behind her.', es: 'Una joven '
    + 'con toca de lino blanco abre una ventana con una mano y sujeta con la otra una jarra '
    + 'de plata dorada sobre una palangana; detrás cuelga un mapa.' }],
  letter: [[2039, 2400], { en: 'Johannes Vermeer, *Woman Reading a Letter*, c. 1663',
    es: 'Johannes Vermeer, *Mujer leyendo una carta*, h. 1663' }, { en: 'Oil on canvas, '
    + '46.5 × 39 cm. Rijksmuseum, Amsterdam, SK-C-251, on loan from the City of Amsterdam '
    + '(A. van der Hoop Bequest). Public domain.', es: 'Óleo sobre lienzo, 46,5 × 39 cm. '
    + 'Rijksmuseum, Ámsterdam, SK-C-251, en préstamo de la ciudad de Ámsterdam (legado '
    + 'A. van der Hoop). Dominio público.' }, { en: 'A woman in a blue jacket stands reading '
    + 'a letter in front of a map of Holland, between two chairs, lit from the left.',
  es: 'Una mujer con chaqueta azul lee una carta de pie ante un mapa de Holanda, entre dos '
    + 'sillas, con la luz a la izquierda.' }],
  balance: [[1502, 1700], { en: 'Johannes Vermeer, *Woman Holding a Balance*, c. 1664',
    es: 'Johannes Vermeer, *Mujer con una balanza*, h. 1664' }, { en: 'Oil on canvas, '
    + '39.7 × 35.5 cm. National Gallery of Art, Washington, 1942.9.97, Widener Collection. '
    + 'Public domain.', es: 'Óleo sobre lienzo, 39,7 × 35,5 cm. National Gallery of Art, '
    + 'Washington, 1942.9.97, colección Widener. Dominio público.' }, { en: 'A woman stands '
    + 'at a table spread with pearls and coins, holding up a small balance; a painting of the '
    + 'Last Judgment hangs behind her.', es: 'Una mujer, de pie ante una mesa con perlas y '
    + 'monedas, sostiene en alto una pequeña balanza; detrás cuelga un Juicio Final.' }],
  'balance-detail': [[800, 1051], { en: 'Detail of :ref{id="balance"}: the beam and its two '
    + 'empty pans. The 48 mm of canvas it shows print 60 mm wide, 1.25 times their size.',
  es: 'Detalle de la :ref{id="balance"}: el astil y sus dos platillos vacíos. Los 48 mm de '
    + 'lienzo que muestra se imprimen a 60 mm, 1,25 veces su tamaño.' }, { en: 'National '
    + 'Gallery of Art, Washington. Public domain.', es: 'National Gallery of Art, Washington. '
    + 'Dominio público.' }, { en: 'A hand holds a small balance by its loop between thumb '
    + 'and forefinger; both pans hang empty.', es: 'Una mano sostiene una pequeña balanza por '
    + 'el aro entre el pulgar y el índice; los dos platillos cuelgan vacíos.' }],
};
const resources = Object.entries(PAINTINGS).map(([id, [[w, h], caption, note, alt]]) => ({
  id, typeId: REACH[id] ? 'plate' : 'detail', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: `${id}-${h > w ? h : w}.jpg`, format: 'jpeg', width: w, height: h },
  caption: t(caption), note: t(note), altText: t(alt),
  ...(REACH[id] && { placement: { plate: REACH[id] } }) }));
```

يحسب فحص ما قبل الطباعة القصَّ: ارتفاع اللوحة الممتدة حتى النزف هنا 201 مم مع النزف، فيحتاج ملفها إلى 2400 بكسل ليبلغ 300 نقطة في البوصة، وتحتاج اللوحتان داخل الهوامش أقل من ذلك. وهي تُطبع بين 303 و348 نقطة في البوصة. ويمنح `page.cutLines` الورقة 3 مم من النزف، ومن دونه يتوقف `'bleed'` عند حد القص مثل `'trim'`.

### 3 · ترويسات تترك اللوحات الكاملة وشأنها

```js
// script.js, سطرًا 73–86
// pages: 'body' keeps them off the opener; a plate set to the trim or the bleed takes the
// 'plate' role, which no element here names, so its page prints bare.
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content,
  parity, pages: 'body', fontFamily: LABEL, fontSize: pt(7.5), color: col('muted'),
  placement: at('page', edge, x, 11), ...caps(7.5), ...extra });
const folio = { color: col('ink'), letterSpacing: pt(0.6) };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-title', '{title}', 'even', 'top-left', OUTER + 8),
  head('recto-title', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 8)),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };
const footer = { elements: [head('drop-folio', '{pageNumber}', 'all', 'top', 0,
  { ...folio, pages: 'opener', placement: at('container', 'top', 0, 8) })] };
```

اللوحة الممتدة حتى حد القص أو النزف تعطي صفحتها دور `'plate'`. وهذه الترويسات تطلب `pages: 'body'`، فتُطبع فوق اللوحات الداخلية وتسقط في الصفحتين 4 و5. والعنصر الذي ينبغي أن يظهر هناك مع ذلك، كإشارة صغيرة إلى المصدر في الزاوية، يذكر `'plate'` في `pages`.

### 4 · تفصيل بمقاس معلوم

يضع نوع التفصيل `width: { value: 60, unit: 'mm' }` مع `captionSide: 'inside'`. والطول يُقاس بالخانة بدل أن يأخذ نسبة منها، فالـ 48 مم من القماش التي يُظهرها القصّ تُطبع بعرض 60 مم، أي 1.25 ضعف مقاسها، في أي عمود وأي طبعة، ويستطيع التعليق أن يقول ذلك.

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

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

- مجلد الوصفة: https://github.com/drnachio/postext/tree/main/cookbook/art-plates-to-the-bleed

### script.js

```js
// ═══ Postext Cookbook · Nº 183 · Art plates to the margins, the trim and the bleed ═════
// https://postext.dev/en/cookbook/art-plates-to-the-bleed
// Code: MIT · Text: original (CC BY 4.0) · Paintings: Rijksmuseum, The Met, NGA (CC0)
// Fonts: Spectral, Cormorant Garamond, Jost (SIL OFL 1.1) · Needs postext ≥ 1.73.0
// An exhibition essay on four interiors by Vermeer. Each painting is a full-page plate: two
// inside the margins, one to the trimmed edge, one out to the bleed. A detail prints 60 mm wide.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'art-plates-to-the-bleed';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: a warm paper and ink, and the ultramarine of the Delft jackets
const palette = {
  ink: '#22201c', // text: a warm near-black
  accent: '#2c4a7c', // kicker, caption labels: the blue of the reading woman's jacket
  rule: '#c9bfae', // the opener's hairline
  muted: '#6b6359', // running heads, folios, credit lines
  paper: '#fbf9f4', // the page, and the band under a caption set over a plate
};
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' } })),
  // The engine's defaults link to 'main-color': pointed at the accent, no default blue shows.
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion
const [TEXT, DISPLAY, LABEL] = ['Spectral', 'Cormorant Garamond', 'Jost'];
const [PAGE_W, PAGE_H, TOP, BOTTOM, INNER, OUTER] = [160, 195, 20, 22, 18, 24]; // mm
const BLEED = 3; // mm of picture past the trim on the bleed plate, and the crop marks' offset
const LEAD = 13.5; // body leading in pt
const at = (to, edge, x, y, size) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(size && { size }) });
const caps = (size) => ({ fontWeight: 500, textTransform: 'uppercase',
  letterSpacing: pt(size * 0.2) });

// #region answer: a plate type, and how far each picture reaches
// Every plate stands alone on the first whole page after its citation, as large as the area
// allows. true (or 'content') keeps it inside the margins with its running heads; 'trim'
// covers the page to the cut, 'bleed' to the bleed. Those two crop the picture about its
// centre, put the caption on a band of paper at the foot, and drop the heads and the folio.
const plateType = { id: 'plate', name: t({ en: 'Plate', es: 'Lámina' }),
  shortLabel: t({ en: 'plate', es: 'lámina' }), captionPrefix: t({ en: 'Plate', es: 'Lámina' }),
  numberingTemplate: '{n}', resetOn: 'never', counterFormat: 'decimal',
  defaultPlacement: { plate: true, captionMeasure: 'body' } }; // the caption as wide as it
const REACH = { milkmaid: 'content', pitcher: 'trim', letter: 'bleed', balance: 'content' };
// A width as a length is measured against the slot, not shared out of it: the detail prints
// 60 mm wide in any layout, 1.25 times the 48 mm of canvas it shows. Its caption stands
// beside it in what is left of the column.
const DETAIL = { width: { value: 60, unit: 'mm' }, captionSide: 'inside', align: 'left' };
// #endregion

// #region opener: kicker, title, deck and a short rule, sunk into the first page
const opener = { enabled: true, minHeight: mm(74), slot: { elements: [
  { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: LABEL, fontSize: pt(7.8),
    color: col('accent'), align: 'left', placement: at('container', 'top-left', 0, 10),
    ...caps(7.8) },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: DISPLAY, fontWeight: 500,
    fontSize: pt(32), lineHeight: 1.02, color: col('ink'), align: 'left', overflow: 'wrap',
    placement: at('#kicker', 'below', 0, 3.5, { width: 'fill', height: 'auto' }) },
  { kind: 'text', id: 'deck', content: '{attr.deck}', fontFamily: DISPLAY, italic: true,
    fontWeight: 500, fontSize: pt(13), lineHeight: 1.2, color: col('ink'), align: 'left',
    overflow: 'wrap', placement: at('#title', 'below', 0, 3, { width: mm(96), height: 'auto' }) },
  { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(0.5), color: col('rule'),
    placement: at('#deck', 'below', 0, 6, { width: mm(22) }) },
] } };
// #endregion

// #region running-heads: the book on the verso, the essay on the recto, folios outside
// pages: 'body' keeps them off the opener; a plate set to the trim or the bleed takes the
// 'plate' role, which no element here names, so its page prints bare.
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content,
  parity, pages: 'body', fontFamily: LABEL, fontSize: pt(7.5), color: col('muted'),
  placement: at('page', edge, x, 11), ...caps(7.5), ...extra });
const folio = { color: col('ink'), letterSpacing: pt(0.6) };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-title', '{title}', 'even', 'top-left', OUTER + 8),
  head('recto-title', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 8)),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };
const footer = { elements: [head('drop-folio', '{pageNumber}', 'all', 'top', 0,
  { ...folio, pages: 'opener', placement: at('container', 'top', 0, 8) })] };
// #endregion

const config = {
  locale: t({ en: 'en-us', es: 'es' }), // the language the text is hyphenated in
  colorPalette,
  resourceTypes: [plateType, { ...plateType, id: 'detail', name: t({ en: 'Figure',
    es: 'Figura' }), shortLabel: t({ en: 'fig.', es: 'fig.' }), captionPrefix: t({ en: 'Fig.',
    es: 'Fig.' }), defaultPlacement: DETAIL }],
  page: { width: mm(PAGE_W), height: mm(PAGE_H), dpi: 150, backgroundColor: col('paper'),
    cutLines: { enabled: true, bleed: mm(BLEED) }, // without them 'bleed' stops at the trim
    margins: { top: mm(TOP), bottom: mm(BOTTOM), left: mm(INNER), right: mm(OUTER),
      mirror: true } },
  layout: { layoutType: 'single', gutterWidth: mm(5) }, // the gutter beside the detail
  bodyText: { fontFamily: TEXT, fontSize: pt(9.6), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    referenceBold: false, textAlign: 'justify', firstLineIndent: mm(4.5),
    indentAfterHeading: false, hyphenation: { enabled: true }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: DISPLAY, color: col('ink'), fontWeight: 500, levels: [
    { level: 1, fontSize: pt(32), breakBefore: { parity: 'odd' }, advancedDesign: opener },
    { level: 2, fontSize: pt(14), lineHeight: pt(LEAD), italic: true, marginTop: pt(LEAD),
      marginBottom: pt(LEAD / 3) },
  ] },
  paragraphStyles: [{ id: 'colophon', fontFamily: LABEL, fontSize: pt(7.2), lineHeight: pt(10),
    color: col('muted'), textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD) }],
  captionStyle: { fontFamily: LABEL, fontSize: pt(7.8), color: col('ink'), gap: pt(7),
    labelBold: true, labelColor: col('accent'), align: 'left',
    note: { fontSize: pt(6.8), color: col('muted') } },
  header,
  footer,
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "Vermeer: Four Rooms in Delft"
---

# A Window \\ on the Left {kicker="Exhibition essay" deck="Four interiors by Johannes Vermeer, painted between about 1660 and 1664"}

Johannes Vermeer spent his working life in Delft, and fewer than forty paintings by him survive. Most of them show the corner of a room, one woman busy with something small, and a window on the left through which the daylight comes. The four interiors brought together in this room were painted within some five years of one another. They now belong to three museums, in Amsterdam, New York and Washington, and in each of them the same kind of window is in a different state: shut, open, out of sight, curtained.

In *The Milkmaid* (:ref{id="milkmaid" style="full" case="lower"}) the window is shut. The maid stands side-on to it, pouring a thin stream of milk from an earthenware jug into a bowl, and the light reaches everything she is busy with: the jug, the bread, the blue cloth pushed back on the table, her yellow bodice and the sleeves rolled to the elbow. Vermeer painted the crust of the bread and the rim of the basket with small raised dots of pale paint, so that the highlights stand a little off the surface and catch the light of the gallery as well as the light of the kitchen. A wicker basket and a brass pail hang by the window. Low on the back wall runs a row of Delft tiles, and on the floor in front of them stands a foot warmer.

Kitchen pieces of the time were often crowded with game, fish and pans. Vermeer keeps a handful of objects and spends his care on the wall behind them, which is not white at all but a run of greys, ochres and faint blues, scored with nail holes and the marks of things that once hung there.

In *Young Woman with a Water Pitcher* (:ref{id="pitcher" style="full" case="lower"}) the window stands open. She holds the casement with one hand and rests the other on a silver-gilt pitcher standing in its basin. The linen over her head and shoulders reads as white, but almost none of it is: Vermeer painted it in the blues of the glass and the greys of the wall, keeping pure white for the few places where the light falls hardest. A map of the Low Countries hangs behind her, and a red carpet covers the table.

*Woman Reading a Letter* (:ref{id="letter" style="full" case="lower"}) takes the window out of the picture altogether. We know where it is only from the light on the letter and on her face, and from the shadows that the chairs throw on the wall. Her jacket is painted with natural ultramarine, a blue ground from lapis lazuli and dearer than any other pigment of the day, and the same blue runs through the shadows on the plaster and the cloth on the chairs. She has stopped in the middle of the room to read, with her lips slightly apart, in front of a map of Holland.

*Woman Holding a Balance* (:ref{id="balance" style="full" case="lower"}) is the darkest of the four. A curtain hangs over most of the window, and the little light it lets through falls on her fingers, on the pearls and coins spread over the table and on the gilt edge of the frame behind her, which holds a painting of the Last Judgment. She holds the balance by its loop between thumb and forefinger and waits for the beam to settle. Under the microscope its two pans are empty (:ref{id="balance-detail"}): she is weighing nothing.

Whether these rooms were the rooms of the house on the Oude Langendijk, where Vermeer lived with his wife’s family, cannot be known. The same chairs with lion-head finials, the same leaded window and the same tiled floor return from one picture to the next, rearranged each time, as a stage is set again for another scene.

## A note on the plates

None of the four canvases is taller than 47 centimetres, smaller than most visitors expect. Plates 1 and 4 are printed inside the margins of the page, as large as the text block allows, under the running heads. Plate 2 is printed to the trimmed edge of the page and plate 3 runs past it into the bleed, so that after trimming the picture fills the page; on those two pages the running head and the folio are left off, and the caption stands on a band of paper at the foot. Every plate is printed from a file of at least 300 pixels per inch at the size it takes on the page. Figure 1 is printed at a fixed width of 60 millimetres, whatever the page around it.

:::paragraphs{style="colophon"}
Set in Spectral, Cormorant Garamond and Jost (SIL Open Font License). Essay written for this catalogue under a CC BY 4.0 licence. Paintings reproduced from the open-access images of the Rijksmuseum, The Metropolitan Museum of Art and the National Gallery of Art, all in the public domain.
:::
`; // content.<lang>.md, inlined by the Cookbook

// #region paintings: four plates and a detail, with their tombstones and credit lines
// JPEGs in assets/ at the pixels each needs for 300 ppi where it prints: 2,400 px high for
// the plates that cover the page (195 mm + 2 × 3 mm of bleed is 7.9 in), less for the rest.
const PAINTINGS = {
  milkmaid: [[1617, 1800], { en: 'Johannes Vermeer, *The Milkmaid*, c. 1660',
    es: 'Johannes Vermeer, *La lechera*, h. 1660' }, { en: 'Oil on canvas, 45.5 × 41 cm. '
    + 'Rijksmuseum, Amsterdam, SK-A-2344, purchased with the support of the Vereniging '
    + 'Rembrandt. Public domain.', es: 'Óleo sobre lienzo, 45,5 × 41 cm. Rijksmuseum, '
    + 'Ámsterdam, SK-A-2344, adquirido con el apoyo de la Vereniging Rembrandt. Dominio '
    + 'público.' }, { en: 'A kitchen maid in a yellow bodice and blue apron pours milk from '
    + 'a jug into a bowl beside a basket of bread, under a window on the left.', es: 'Una '
    + 'criada con corpiño amarillo y delantal azul vierte leche de una jarra en un cuenco, '
    + 'junto a un cesto de pan, bajo una ventana a la izquierda.' }],
  pitcher: [[2116, 2400], { en: 'Johannes Vermeer, *Young Woman with a Water Pitcher*, '
    + 'c. 1662', es: 'Johannes Vermeer, *Joven con una jarra de agua*, h. 1662' },
  { en: 'Oil on canvas, 45.7 × 40.6 cm. The Metropolitan Museum of Art, New York, 89.15.21, '
    + 'Marquand Collection, gift of Henry G. Marquand, 1889. Public domain.', es: 'Óleo sobre '
    + 'lienzo, 45,7 × 40,6 cm. The Metropolitan Museum of Art, Nueva York, 89.15.21, '
    + 'colección Marquand, donación de Henry G. Marquand, 1889. Dominio público.' },
  { en: 'A young woman in a white linen hood opens a window with one hand and holds a '
    + 'silver-gilt pitcher in a basin with the other; a map hangs behind her.', es: 'Una joven '
    + 'con toca de lino blanco abre una ventana con una mano y sujeta con la otra una jarra '
    + 'de plata dorada sobre una palangana; detrás cuelga un mapa.' }],
  letter: [[2039, 2400], { en: 'Johannes Vermeer, *Woman Reading a Letter*, c. 1663',
    es: 'Johannes Vermeer, *Mujer leyendo una carta*, h. 1663' }, { en: 'Oil on canvas, '
    + '46.5 × 39 cm. Rijksmuseum, Amsterdam, SK-C-251, on loan from the City of Amsterdam '
    + '(A. van der Hoop Bequest). Public domain.', es: 'Óleo sobre lienzo, 46,5 × 39 cm. '
    + 'Rijksmuseum, Ámsterdam, SK-C-251, en préstamo de la ciudad de Ámsterdam (legado '
    + 'A. van der Hoop). Dominio público.' }, { en: 'A woman in a blue jacket stands reading '
    + 'a letter in front of a map of Holland, between two chairs, lit from the left.',
  es: 'Una mujer con chaqueta azul lee una carta de pie ante un mapa de Holanda, entre dos '
    + 'sillas, con la luz a la izquierda.' }],
  balance: [[1502, 1700], { en: 'Johannes Vermeer, *Woman Holding a Balance*, c. 1664',
    es: 'Johannes Vermeer, *Mujer con una balanza*, h. 1664' }, { en: 'Oil on canvas, '
    + '39.7 × 35.5 cm. National Gallery of Art, Washington, 1942.9.97, Widener Collection. '
    + 'Public domain.', es: 'Óleo sobre lienzo, 39,7 × 35,5 cm. National Gallery of Art, '
    + 'Washington, 1942.9.97, colección Widener. Dominio público.' }, { en: 'A woman stands '
    + 'at a table spread with pearls and coins, holding up a small balance; a painting of the '
    + 'Last Judgment hangs behind her.', es: 'Una mujer, de pie ante una mesa con perlas y '
    + 'monedas, sostiene en alto una pequeña balanza; detrás cuelga un Juicio Final.' }],
  'balance-detail': [[800, 1051], { en: 'Detail of :ref{id="balance"}: the beam and its two '
    + 'empty pans. The 48 mm of canvas it shows print 60 mm wide, 1.25 times their size.',
  es: 'Detalle de la :ref{id="balance"}: el astil y sus dos platillos vacíos. Los 48 mm de '
    + 'lienzo que muestra se imprimen a 60 mm, 1,25 veces su tamaño.' }, { en: 'National '
    + 'Gallery of Art, Washington. Public domain.', es: 'National Gallery of Art, Washington. '
    + 'Dominio público.' }, { en: 'A hand holds a small balance by its loop between thumb '
    + 'and forefinger; both pans hang empty.', es: 'Una mano sostiene una pequeña balanza por '
    + 'el aro entre el pulgar y el índice; los dos platillos cuelgan vacíos.' }],
};
const resources = Object.entries(PAINTINGS).map(([id, [[w, h], caption, note, alt]]) => ({
  id, typeId: REACH[id] ? 'plate' : 'detail', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: `${id}-${h > w ? h : w}.jpg`, format: 'jpeg', width: w, height: h },
  caption: t(caption), note: t(note), altText: t(alt),
  ...(REACH[id] && { placement: { plate: REACH[id] } }) }));
// #endregion

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { // text, display and label faces, loaded before the build
  Spectral: ['400', '400i'], 'Cormorant Garamond': ['500', '500i'], Jost: ['400', '500', '600'] };

// ─── 4 · Build & show ───────────────────────────────────────────────────────
await Promise.all(resources.map((r) => loadImage(r.bitmap.fileId, asset(r.bitmap.fileId))));
const doc = await buildDocumentWithFonts({ markdown, resources }, config, kitFonts(FONTS));
showPages(doc, { title: t({ en: 'Plates to the margins, the trim and the bleed',
  es: 'Láminas a los márgenes, al corte y a sangre' }) });
offerPdf(() => renderToPdf(doc, { fontProvider: fontsourceProvider, resourceBytes: imageBytes }),
  `${RECIPE}.pdf`); // with crop marks, a TrimBox and a BleedBox

// ─── 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
-const REACH = { milkmaid: 'content', pitcher: 'trim', letter: 'bleed', balance: 'content' };
+const REACH = { milkmaid: 'bleed', pitcher: 'bleed', letter: 'bleed', balance: 'bleed' };
```

### التفصيل بمقاسه الحقيقي

اقتطع 60 مم من القماش من ملف المتحف واترك العرض كما هو: يصبح التعليق 1:1. وفي الملف الأصلي لهذه اللوحة 1666 نقطة في البوصة، فحتى تفصيل من بضعة مليمترات يظل فوق 300.

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

- اللوحة المذكورة في الفقرة نفسها مع لوحة أخرى تنتظر الصفحة التي تليها، لأن الصفحة التي فيها عنصر عائم تُتخطى، ثلاث صفحات على الأكثر.
- العرض بـ `pt` و`mm` يعمل، أما `px` و`em` فلا يُقرآن طولًا، ويأخذ الشكل خانته كلها.
- اللوحة الأعرض كثيرًا من الصفحة تفقد جانبيها في لوحة حتى حد القص أو النزف. أبقِ اللوحات الأفقية داخل الهوامش حيث تظهر كاملة.

## الحقوق

- الوصفة: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- النص: The essay, the captions and the note on the plates: Postext Cookbook, CC-BY-4.0
- الصور: Plate 1, Johannes Vermeer, The Milkmaid, c. 1660, Rijksmuseum SK-A-2344; the museum’s image reduced to 1,800 px high: Rijksmuseum, Amsterdam ([المصدر](https://id.rijksmuseum.nl/200108369)), CC0-1.0
- الصور: Plate 2, Johannes Vermeer, Young Woman with a Water Pitcher, c. 1662, The Met 89.15.21; the museum’s image, its unpainted edges cut off, reduced to 2,400 px high: The Metropolitan Museum of Art, New York (Open Access) ([المصدر](https://www.metmuseum.org/art/collection/search/437881)), CC0-1.0
- الصور: Plate 3, Johannes Vermeer, Woman Reading a Letter, c. 1663, Rijksmuseum SK-C-251; the museum’s image reduced to 2,400 px high: Rijksmuseum, Amsterdam ([المصدر](https://id.rijksmuseum.nl/200108372)), CC0-1.0
- الصور: Plate 4, Johannes Vermeer, Woman Holding a Balance, c. 1664, National Gallery of Art 1942.9.97; the museum’s image reduced to 1,700 px high: National Gallery of Art, Washington (Open Access) ([المصدر](https://www.nga.gov/artworks/1236-woman-holding-balance)), CC0-1.0
- الصور: Figure 1, a 48 × 63 mm detail of plate 4 cut from the museum’s full-resolution image and reduced to 800 px wide: National Gallery of Art, Washington (Open Access) ([المصدر](https://www.nga.gov/artworks/1236-woman-holding-balance)), CC0-1.0
- الخطوط: Spectral (OFL-1.1), Cormorant Garamond (OFL-1.1), Jost (OFL-1.1)
- الشيفرة: MIT · محتوى المثال: CC-BY-4.0

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

- [رقم 034 · مداخل كتالوج تقابلها لوحاتها](https://postext.dev/ar/cookbook/catalogue-facing-plates.md): يبدأ كل مدخل صفحة زوجية ويستشهد بلوحته في أول جملة من التعليق؛ فتطفو اللوحة إلى الصفحة الفردية المقابلة، مصغَّرة بنسب المسح الضوئي حتى تملأ كتلة النص. · المستوى 3 (متقدم) · الكتالوجات
- [رقم 068 · مقالة مصوَّرة بلوحات تنزف حتى الحواف](https://postext.dev/ar/cookbook/photo-essay-full-bleed.md): لوحات هي أنماط عناوين مبنية من قائمة، تملأ كلٌّ منها صفحتها حتى حدّ القص؛ ولوحة العاصفة تعبر الفاصل الداخلي لصفحتين متقابلتين في نصفين. · المستوى 2 (متوسط) · كتب الصور
- [رقم 024 · PDF جاهز للطباعة: النزف وعلامات القص وPDF/X](https://postext.dev/ar/cookbook/print-ready-pdf.md): مطوية معرض بنزف 3 مم وعلامات قص، مصدَّرة إلى PDF/X-4 على FOGRA51 مع نُسخ طباعة أصلية، ويمر الفحص قبل الطباعة دون ملاحظات. · المستوى 3 (متقدم) · الأوراق المفردة والمطبوعات العابرة
