# غلاف كتاب ورقي بألسنة، وكعبه محسوب من الصفحات

> كتاب ورقي بقياس 120 × 190 مم وألسنة عرضها 60 مم: تُنضَّد الصفحات أولًا، ثم تصنع منها buildCover فرخ الغلاف، بكعب سمكه سمك ورقها.

- نسخة HTML: https://postext.dev/ar/cookbook/paperback-cover-with-flaps
- وصفة رقم 196 · الإخراج والدمج · المستوى 3 (متقدم) · المخرجات: Canvas, PDF
- الأنواع: الأدب القصصي والمسرح والنثر الأدبي
- تتطلب postext ≥ 1.93.0, postext-pdf ≥ 1.93.0 · اختُبرت مع 1.93.0, postext-pdf 1.93.0 بتاريخ 2026-11-23
- الصفحات: [3](https://postext.dev/cookbook/paperback-cover-with-flaps/en/p03.webp?v=9446d4a8), [4](https://postext.dev/cookbook/paperback-cover-with-flaps/en/p04.webp?v=9446d4a8), [5](https://postext.dev/cookbook/paperback-cover-with-flaps/en/p05.webp?v=9446d4a8), [7](https://postext.dev/cookbook/paperback-cover-with-flaps/en/p07.webp?v=9446d4a8), [9](https://postext.dev/cookbook/paperback-cover-with-flaps/en/p09.webp?v=9446d4a8), [10](https://postext.dev/cookbook/paperback-cover-with-flaps/en/p10.webp?v=9446d4a8), [20](https://postext.dev/cookbook/paperback-cover-with-flaps/en/p20.webp?v=9446d4a8), [21](https://postext.dev/cookbook/paperback-cover-with-flaps/en/p21.webp?v=9446d4a8), [23](https://postext.dev/cookbook/paperback-cover-with-flaps/en/p23.webp?v=9446d4a8), [25](https://postext.dev/cookbook/paperback-cover-with-flaps/en/p25.webp?v=9446d4a8), [37](https://postext.dev/cookbook/paperback-cover-with-flaps/en/p37.webp?v=9446d4a8), [1](https://postext.dev/cookbook/paperback-cover-with-flaps/en/p38.webp?v=9446d4a8)
- PDF: https://postext.dev/cookbook/paperback-cover-with-flaps/en/paperback-cover-with-flaps.pdf?v=9446d4a8
- افتح في Sandbox: https://postext.dev/ar/sandbox#recipe=paperback-cover-with-flaps&lang=en (.postext: https://postext.dev/cookbook/paperback-cover-with-flaps/en/paperback-cover-with-flaps.postext)
- آخر تحديث: 2026-11-23
- لغات أخرى: [en](https://postext.dev/en/cookbook/paperback-cover-with-flaps.md), [es](https://postext.dev/es/cookbook/paperback-cover-with-flaps.md), [ca](https://postext.dev/ca/cookbook/paperback-cover-with-flaps.md), [de](https://postext.dev/de/cookbook/paperback-cover-with-flaps.md), [fr](https://postext.dev/fr/cookbook/paperback-cover-with-flaps.md), [it](https://postext.dev/it/cookbook/paperback-cover-with-flaps.md), [pt](https://postext.dev/pt/cookbook/paperback-cover-with-flaps.md), [zh](https://postext.dev/zh/cookbook/paperback-cover-with-flaps.md), [ja](https://postext.dev/ja/cookbook/paperback-cover-with-flaps.md)

## باختصار

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

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

أسطورتان لبيكر، «The Spirits’ Mountain» و«The Emerald Eyes» (وعنوانهما بالإسبانية «El monte de las ánimas» و«Los ojos verdes»)، في كتاب جيب ورقي بقياس 120 × 190 مم وألسنة عرضها 60 مم، ومعه الفرخ الذي يُطبع عليه غلافه. ينضّد Postext أولًا الصفحات السبع والثلاثين: صفحة نصف العنوان، وصفحة العنوان، والحقوق، والفهرس، وورقة عنوان لكل أسطورة، ثم المتن بخط Crimson Pro بقياس 11/15.2. بعدها تأخذ `buildCover` هذه الصفحات وتركّب الفرخ: اللسان الخلفي، والغلاف الخلفي بنبذته ورمزه الشريطي، والكعب، والغلاف الأمامي بلوحة لكنيسة مهدمة عند سفح جبل مونكايو، واللسان الأمامي. ويأتي العنوان والعنوان الفرعي واسم المؤلف من بيانات الكتاب الوصفية، ونص الألسنة من ملف Markdown مستقل.

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

- كيف أصنع فرخ غلاف كتاب ورقي بألسنة، والكعب محسوب من عدد الصفحات؟

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

```js
// script.js, سطرًا 28–47
// The book's own binding profile: PUR perfect binding in 16-page signatures, flaps of
// 60 mm whatever the trim. The spine is written nowhere: buildCover works it out from the
// laid-out pages, rounded up to whole signatures, on the paper of `folio.paper`.
const production = {
  bindings: [{ id: 'pur-flaps', name: 'PUR perfect binding, 60 mm flaps', style: 'perfect',
    signature: 16, measures: { flapWidth: 60, bleed: 3, spineAllowance: 0.5 } }],
  versions: [{ id: 'paperback', name: t({ en: 'Paperback', es: 'Rústica' }), binding: 'pur-flaps',
    flaps: true, isbn: '978-84-0000-196-4', isbnAddOn: '90000' }],
};
// 100 g/m² bulky cream wove at a bulk of 2.4: each leaf is 100 × 2.4 = 240 µm thick.
const folio = { paper: { type: 'bookWove', grammage: 100, bulk: 2.4, shade: '#f7f1e3' } };
// The design: a night ground over the whole sheet and the painting on the front, into the
// bleed at head and foot and up to the flap's fold. The texts come from the cover Markdown,
// the title, subtitle and author from the book's metadata.
const cover = {
  background: col('night'),
  elements: [{ id: 'art', kind: 'image', zone: 'front', x: 0, y: -3, width: 118, height: 196,
    resourceId: 'moncayo', fit: 'cover' }],
  verticalAlign: { back: 'middle' },
};
```

## المكونات

**تعلّم**

- [فرخ الغلاف](https://postext.dev/ar/docs/print-covers.md#الفرخ-ولوحاته): تُخرج buildCover فرخ نسخة مطبوعة: الغلاف الخلفي والكعب والغلاف الأمامي، مع الألسنة، أو غلاف التجليد المقوّى وسترته وأوراق البطانة، بالنزف وعلامات الطيّ. ويصمّمه إعداد cover ويملأ لوحاته مستند Markdown من الكتاب.
- [النسخ المطبوعة والردمك والكعب](https://postext.dev/ar/docs/print-covers.md#نسخ-الكتاب): تعطي production.versions كل تجليد للكتاب ملف تجليده وردمكه، ويُطبع الردمك رمزًا شريطيًا EAN-13؛ ويُحسب الكعب من عدد الصفحات والورق. وتضيف production.collection ردمك العمل الكامل وفهرسًا بعناوينه.

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

- [الأغلفة وصفحات العنوان وبيانات النشر](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين)
- [أنماط العناوين](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين)
- [صفحات افتتاح مصمَّمة](https://postext.dev/ar/docs/configuration-headings.md#الامتداد-والتصميم-المتقدم)
- [النصوص والخطوط والمربعات في تصاميم الصفحة](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات)
- [البيانات الوصفية للمستند](https://postext.dev/ar/docs/document-format.md#البيانات-التمهيدية-frontmatter)
- [أنماط الفقرات](https://postext.dev/ar/docs/configuration-styles.md#أنماط-الفقرات)
- [جدول المحتويات](https://postext.dev/ar/docs/configuration-notes-references.md#جدول-المحتويات)
- [الترويسات وأرقام الصفحات](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات)
- [الأشكال والجداول بوصفها موارد](https://postext.dev/ar/docs/document-format-resources.md#الموارد)
- [لوحة ألوان دلالية](https://postext.dev/ar/docs/configuration-fonts-colors-viewers.md#لوحة-الألوان)
- [التصدير إلى PDF](https://postext.dev/ar/docs/configuration-pdf-output.md#توليد-ملفات-pdf)
- [صفحات على اللوحة (Canvas)](https://postext.dev/ar/docs/configuration-programmatic-usage.md#رسم-صفحة-في-صورة-نقطية)
- [الورق والتجليد والمكتب والإضاءة (Folio)](https://postext.dev/ar/docs/configuration-fonts-colors-viewers.md#عارض-folio-الإعدادات)
- [سمات العنوان](https://postext.dev/ar/docs/document-format.md#سمات-العناوين)
- [لون الورق](https://postext.dev/ar/docs/configuration-page-layout.md#الصفحة)
- [الترويسات بحسب دور الصفحة](https://postext.dev/ar/docs/configuration-headers-footers.md#عناصر-النص)
- [الخطوط المضمَّنة في PDF](https://postext.dev/ar/docs/configuration-pdf-output.md#لماذا-مزوّد-الخطوط)
- [ترويسات لكل قسم](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين)
- [فصول بلا أرقام](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين)

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

- [`bodyText`](https://postext.dev/ar/docs/configuration-text.md#نص-المتن), [`colorPalette`](https://postext.dev/ar/docs/configuration-fonts-colors-viewers.md#لوحة-الألوان), [`cover`](https://postext.dev/ar/docs/print-covers.md#تصميم-الغلاف), [`folio`](https://postext.dev/ar/docs/configuration-html-folio-epub.md#المظهر), [`footer`](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات), [`header`](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات), [`headingStyles`](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين), [`headings`](https://postext.dev/ar/docs/configuration-headings.md#العناوين), [`layout`](https://postext.dev/ar/docs/configuration-page-layout.md#التخطيط), [`locale`](https://postext.dev/ar/docs/configuration-language.md#تقسيم-الكلمات-بالواصلة), [`page`](https://postext.dev/ar/docs/configuration-page-layout.md#الصفحة), [`paragraphStyles`](https://postext.dev/ar/docs/configuration-styles.md#أنماط-الفقرات), [`production`](https://postext.dev/ar/docs/print-covers.md#نسخ-الكتاب), [`toc`](https://postext.dev/ar/docs/configuration-notes-references.md#جدول-المحتويات)

**واجهات API**

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

**الخطوط**

- Crimson Pro (OFL-1.1), Cormorant Garamond (OFL-1.1), Josefin Sans (OFL-1.1)

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

### 1 · التجليد يحدد الألسنة، والورق يحدد الكعب

الشيفرة هي [الجواب المختصر](https://postext.dev/ar/cookbook/paperback-cover-with-flaps.md#الجواب-المختصر) أعلاه. يصف ملف التجليد طريقة عمل المجلّد: تجليد حراري بغراء PUR في ملازم من 16 صفحة، وألسنة عرضها 60 مم، ونزف 3 مم، ونصف مليمتر يُضاف إلى الكعب للغراء. وتحمل النسخة الردمك ورقمه الإضافي ذا الخانات الخمس؛ والردمك رقم للتمثيل لا يخص أي كتاب. ولا يُكتب عرض الكعب في أي موضع. تُقرَّب الصفحات السبع والثلاثون صعودًا إلى ثلاث ملازم، أي 48 صفحة أو 24 ورقة، وكل ورقة من ورق وزنه 100 غ/م² وانتفاخه 2.4 سمكها 240 ميكرومترًا: 24 × 0.24 + 0.5 تعطي كعبًا عرضه 6.3 مم. والكعب الذي يقل عن 6 مم لا يُكتب عليه شيء افتراضيًا (`spineText.minSpine`)، ولذلك طُبع الكتاب على ورق منتفخ.

### 2 · الصفحات أولًا

```js
// script.js, سطرًا 72–124
const [W, H, TOP, FOOT, INNER, OUTER, LEAD] = [120, 190, 20, 22, 18, 15.5, 15.2]; // mm, pt
const at = (to, edge, x, y, size) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(size && { size }) });
const text = (id, content, look, place) => ({ kind: 'text', id, content, align: 'center',
  overflow: 'wrap', placement: place, ...look });
const face = (fontFamily, size, color, extra) => ({ fontFamily, fontSize: pt(size), color,
  ...extra });
const label = (size, color = col('muted')) => face('Josefin Sans', size, color, caps(size / 5));
const none = { header: { elements: [] }, footer: { elements: [] }, numbered: false, toc: false };
const design = (minHeight, elements) => ({ enabled: true, minHeight: mm(minHeight),
  slot: { elements } });
const page = (parity) => ({ breakBefore: { enabled: true, parity } });
const rule = (id, y, to = 'page') => ({ kind: 'rule', id, direction: 'horizontal',
  thickness: pt(0.6), color: col('accent'), placement: at(to, 'top', 0, y, { width: mm(10) }) });
const folioAt = (y, pages) => ({ elements: [text('f', '{pageNumber}',
  { ...face('Crimson Pro', 9, col('ink')), pages }, at('page', 'bottom', 0, y))] });
const serif = (size, extra) => face('Cormorant Garamond', size, col('ink'), extra);
const headingStyles = [
  { ...none, id: 'half-title', advancedDesign: design(60, [
    text('t', '{title}', serif(17, { fontWeight: 500 }), at('page', 'top', 0, 62))]) },
  { ...none, ...page('odd'), id: 'title-page', advancedDesign: design(H - TOP - FOOT, [
    text('t', '{title}', serif(27, { fontWeight: 600 }), at('page', 'top', 0, 46)),
    text('s', '{subtitle}', serif(13, { italic: true }), at('page', 'top', 0, 58)),
    rule('r', 67),
    text('a', '{author}', label(8, col('accent')), at('page', 'top', 0, 72)),
    text('tr', '{attr.translators}', face('Crimson Pro', 9.5, col('muted'), { italic: true }),
      at('page', 'top', 0, 118, { width: mm(70) })),
    text('i', '{attr.imprint}', label(7), at('page', 'bottom', 0, -26)),
  ]) },
  // The rights at the foot of the verso, under a short rule.
  { ...none, ...page('even'), id: 'rights',
    advancedDesign: design(92, [rule('r', 86, 'container')]) },
  { ...none, ...page('odd'), id: 'contents', advancedDesign: design(34, [
    text('t', '{titleText}', label(8, col('accent')), at('container', 'top', 0, 14)),
    rule('r', 21, 'container')]) },
  // Each legend has a title leaf of its own (the contents point to it), then opens on the
  // next recto, sunk 40 mm.
  { ...none, ...page('odd'), id: 'tale-title', toc: true, advancedDesign: design(90, [
    text('k', '{attr.kicker}', serif(15, { fontWeight: 600, color: col('accent') }),
      at('page', 'top', 0, 58)),
    text('t', '{titleText}', serif(23, { fontWeight: 500 }), at('page', 'top', 0, 67)),
    text('p', '{attr.place}', face('Crimson Pro', 10.5, col('muted'), { italic: true }),
      at('page', 'top', 0, 79)),
    rule('r', 88)]) },
  { ...page('odd'), id: 'tale', toc: false, advancedDesign: design(40, [
    text('t', '{titleText}', serif(15, { fontWeight: 500, italic: true }),
      at('container', 'top', 0, 16)),
    rule('r', 25, 'container')]) },
  { ...none, ...page('any'), id: 'colophon', advancedDesign: design(70, [
    rule('r', 60, 'container')]) },
];
const head = (id, content, parity) => text(id, content, { ...label(6.8), parity, pages: 'body' },
  at('page', 'top', 0, 11));
```

متن الكتاب مستند Postext عادي، وكل صفحة فيه تُحسب في الكعب. وتستعمل الصفحات التمهيدية أنماط عناوين تضع تصاميمُها العنوانَ والخطَّ واسمَ الناشر على ارتفاعات ثابتة من الصفحة. ولكل أسطورة ورقة عنوان خاصة بها (وهي التي يشير إليها الفهرس)، ثم يبدأ نصها من جديد في الصفحة الفردية التالية، على بعد 40 مم من أعلاها. غيّر حجم الخط أو الهوامش فيتغير عدد الصفحات، ويتبعه الكعب في التنضيد التالي.

### 3 · أنماط الغلاف تقيم مع أنماط الكتاب

```js
// script.js, سطرًا 51–68
const style = (id, fontFamily, size, lead, color, extra) => ({ id, fontFamily, fontSize: pt(size),
  lineHeight: pt(lead), color, italicColor: color, firstLineIndent: mm(0), textAlign: 'left',
  hyphenation: false, ...extra });
const caps = (tracking) => ({ fontWeight: 600, textTransform: 'uppercase',
  letterSpacing: pt(tracking) });
const coverStyles = [
  style('cover-title', 'Cormorant Garamond', 40, 40, col('bone'), { fontWeight: 600,
    textAlign: 'center', marginTop: mm(12) }),
  style('cover-subtitle', 'Cormorant Garamond', 15, 19, col('bone'), { italic: true,
    textAlign: 'center' }),
  style('cover-author', 'Josefin Sans', 8.5, 11, col('gold'), { ...caps(1.8),
    textAlign: 'center', marginTop: pt(16) }),
  style('cover-spine', 'Josefin Sans', 7.5, 9, col('bone'), { ...caps(1.2), textAlign: 'center' }),
  style('cover-blurb', 'Crimson Pro', 10.5, 14.5, col('bone'), { marginBottom: pt(7) }),
  style('cover-note', 'Crimson Pro', 10.5, 14.5, col('gold'), { italic: true }),
  style('flap-head', 'Josefin Sans', 7.5, 10, col('gold'), caps(1.4)),
  style('flap-text', 'Crimson Pro', 9.6, 13.2, col('bone'), { marginTop: pt(5) }),
];
```

يُنضَّد الفرخ بإعدادات الكتاب، فأنماط فقراته في القائمة نفسها التي فيها أنماط الحقوق وخاتمة الطبع. و`cover-title` و`cover-subtitle` و`cover-author` و`cover-spine` هي الأسماء التي تعطيها `buildCover` للبيانات الوصفية التي تضعها؛ أما `cover-blurb` و`cover-note` و`flap-head` و`flap-text` فيسمّيها ملف Markdown الخاص بالغلاف. وعلى الأرضية الليلية يُصفّ النص غير مضبوط الحافة، بلا تقطيع للكلمات، بلون العاج والذهب من لوحة الألوان.

### 4 · الفرخ يُصنع من الصفحات المنضدة

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

تتلقى `buildCover` الصفحات والبيانات الوصفية وملف Markdown الخاص بالغلاف، وفيه `:::frame` للغلاف الخلفي وآخر لكل لسان. وتُرجع مستندًا تنضّده `buildDocumentWithFonts` كأي مستند آخر، ومعه الرمز الشريطي في ملف SVG. تطلب أرقام الرمز خط OCR-B، ولا يقدّمه أي خادم خطوط، فيصفّها المثال بخط Josefin Sans الذي يضمّنه ملف PDF أصلًا. ويحمل ملف PDF الصفحات السبع والثلاثين ثم الفرخ بقياسه الخاص، وهو الملف الذي تنتظره المطبعة.

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

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

- مجلد الوصفة: https://github.com/drnachio/postext/tree/main/cookbook/paperback-cover-with-flaps

### script.js

```js
// ═══ Postext Cookbook · Nº 196 · A paperback cover with flaps, spine from the pages ═══
// https://postext.dev/en/cookbook/paperback-cover-with-flaps
// Code: MIT · Text: Bécquer, tr. C. F. & K. L. Bates (public domain) · Art: diffusion models
// Fonts: Crimson Pro, Cormorant Garamond, Josefin Sans (SIL OFL 1.1) · Needs postext ≥ 1.93.0
//
// Two of Bécquer's legends as a 120 × 190 mm paperback with 60 mm flaps. Postext lays the
// pages out first; buildCover then makes the cover sheet from them, its spine as thick as
// the pages on their paper.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, inlineSvgFonts,
} from 'https://esm.sh/postext';
import { buildCover } from 'https://esm.sh/postext/production';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'paperback-cover-with-flaps';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { ink: '#25221e', accent: '#86472a', muted: '#6b645a', paper: '#fbf7ee',
  night: '#16242a', gold: '#c99b4e', bone: '#eee5d1' }; // the last three: the cover's
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];

// #region answer: the paperback: a printer's binding with 60 mm flaps, its ISBN, its paper
// The book's own binding profile: PUR perfect binding in 16-page signatures, flaps of
// 60 mm whatever the trim. The spine is written nowhere: buildCover works it out from the
// laid-out pages, rounded up to whole signatures, on the paper of `folio.paper`.
const production = {
  bindings: [{ id: 'pur-flaps', name: 'PUR perfect binding, 60 mm flaps', style: 'perfect',
    signature: 16, measures: { flapWidth: 60, bleed: 3, spineAllowance: 0.5 } }],
  versions: [{ id: 'paperback', name: t({ en: 'Paperback', es: 'Rústica' }), binding: 'pur-flaps',
    flaps: true, isbn: '978-84-0000-196-4', isbnAddOn: '90000' }],
};
// 100 g/m² bulky cream wove at a bulk of 2.4: each leaf is 100 × 2.4 = 240 µm thick.
const folio = { paper: { type: 'bookWove', grammage: 100, bulk: 2.4, shade: '#f7f1e3' } };
// The design: a night ground over the whole sheet and the painting on the front, into the
// bleed at head and foot and up to the flap's fold. The texts come from the cover Markdown,
// the title, subtitle and author from the book's metadata.
const cover = {
  background: col('night'),
  elements: [{ id: 'art', kind: 'image', zone: 'front', x: 0, y: -3, width: 118, height: 196,
    resourceId: 'moncayo', fit: 'cover' }],
  verticalAlign: { back: 'middle' },
};
// #endregion

// #region cover-type: the paragraph styles the cover's text is set in
const style = (id, fontFamily, size, lead, color, extra) => ({ id, fontFamily, fontSize: pt(size),
  lineHeight: pt(lead), color, italicColor: color, firstLineIndent: mm(0), textAlign: 'left',
  hyphenation: false, ...extra });
const caps = (tracking) => ({ fontWeight: 600, textTransform: 'uppercase',
  letterSpacing: pt(tracking) });
const coverStyles = [
  style('cover-title', 'Cormorant Garamond', 40, 40, col('bone'), { fontWeight: 600,
    textAlign: 'center', marginTop: mm(12) }),
  style('cover-subtitle', 'Cormorant Garamond', 15, 19, col('bone'), { italic: true,
    textAlign: 'center' }),
  style('cover-author', 'Josefin Sans', 8.5, 11, col('gold'), { ...caps(1.8),
    textAlign: 'center', marginTop: pt(16) }),
  style('cover-spine', 'Josefin Sans', 7.5, 9, col('bone'), { ...caps(1.2), textAlign: 'center' }),
  style('cover-blurb', 'Crimson Pro', 10.5, 14.5, col('bone'), { marginBottom: pt(7) }),
  style('cover-note', 'Crimson Pro', 10.5, 14.5, col('gold'), { italic: true }),
  style('flap-head', 'Josefin Sans', 7.5, 10, col('gold'), caps(1.4)),
  style('flap-text', 'Crimson Pro', 9.6, 13.2, col('bone'), { marginTop: pt(5) }),
];
// #endregion

// #region pages: the book block, a small literary paperback
const [W, H, TOP, FOOT, INNER, OUTER, LEAD] = [120, 190, 20, 22, 18, 15.5, 15.2]; // mm, pt
const at = (to, edge, x, y, size) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(size && { size }) });
const text = (id, content, look, place) => ({ kind: 'text', id, content, align: 'center',
  overflow: 'wrap', placement: place, ...look });
const face = (fontFamily, size, color, extra) => ({ fontFamily, fontSize: pt(size), color,
  ...extra });
const label = (size, color = col('muted')) => face('Josefin Sans', size, color, caps(size / 5));
const none = { header: { elements: [] }, footer: { elements: [] }, numbered: false, toc: false };
const design = (minHeight, elements) => ({ enabled: true, minHeight: mm(minHeight),
  slot: { elements } });
const page = (parity) => ({ breakBefore: { enabled: true, parity } });
const rule = (id, y, to = 'page') => ({ kind: 'rule', id, direction: 'horizontal',
  thickness: pt(0.6), color: col('accent'), placement: at(to, 'top', 0, y, { width: mm(10) }) });
const folioAt = (y, pages) => ({ elements: [text('f', '{pageNumber}',
  { ...face('Crimson Pro', 9, col('ink')), pages }, at('page', 'bottom', 0, y))] });
const serif = (size, extra) => face('Cormorant Garamond', size, col('ink'), extra);
const headingStyles = [
  { ...none, id: 'half-title', advancedDesign: design(60, [
    text('t', '{title}', serif(17, { fontWeight: 500 }), at('page', 'top', 0, 62))]) },
  { ...none, ...page('odd'), id: 'title-page', advancedDesign: design(H - TOP - FOOT, [
    text('t', '{title}', serif(27, { fontWeight: 600 }), at('page', 'top', 0, 46)),
    text('s', '{subtitle}', serif(13, { italic: true }), at('page', 'top', 0, 58)),
    rule('r', 67),
    text('a', '{author}', label(8, col('accent')), at('page', 'top', 0, 72)),
    text('tr', '{attr.translators}', face('Crimson Pro', 9.5, col('muted'), { italic: true }),
      at('page', 'top', 0, 118, { width: mm(70) })),
    text('i', '{attr.imprint}', label(7), at('page', 'bottom', 0, -26)),
  ]) },
  // The rights at the foot of the verso, under a short rule.
  { ...none, ...page('even'), id: 'rights',
    advancedDesign: design(92, [rule('r', 86, 'container')]) },
  { ...none, ...page('odd'), id: 'contents', advancedDesign: design(34, [
    text('t', '{titleText}', label(8, col('accent')), at('container', 'top', 0, 14)),
    rule('r', 21, 'container')]) },
  // Each legend has a title leaf of its own (the contents point to it), then opens on the
  // next recto, sunk 40 mm.
  { ...none, ...page('odd'), id: 'tale-title', toc: true, advancedDesign: design(90, [
    text('k', '{attr.kicker}', serif(15, { fontWeight: 600, color: col('accent') }),
      at('page', 'top', 0, 58)),
    text('t', '{titleText}', serif(23, { fontWeight: 500 }), at('page', 'top', 0, 67)),
    text('p', '{attr.place}', face('Crimson Pro', 10.5, col('muted'), { italic: true }),
      at('page', 'top', 0, 79)),
    rule('r', 88)]) },
  { ...page('odd'), id: 'tale', toc: false, advancedDesign: design(40, [
    text('t', '{titleText}', serif(15, { fontWeight: 500, italic: true }),
      at('container', 'top', 0, 16)),
    rule('r', 25, 'container')]) },
  { ...none, ...page('any'), id: 'colophon', advancedDesign: design(70, [
    rule('r', 60, 'container')]) },
];
const head = (id, content, parity) => text(id, content, { ...label(6.8), parity, pages: 'body' },
  at('page', 'top', 0, 11));
// #endregion

const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(W), height: mm(H), dpi: 300,
    backgroundColor: col('paper'),
    margins: { top: mm(TOP), bottom: mm(FOOT), left: mm(INNER), right: mm(OUTER), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Crimson Pro', fontSize: pt(11), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'justify',
    firstLineIndent: mm(4), indentAfterHeading: false, hyphenation: { enabled: true },
    optimalLineBreaking: true, avoidWidows: true, avoidOrphans: true },
  headings: { fontFamily: 'Cormorant Garamond', color: col('ink'), textAlign: 'center', levels: [
    { level: 2, fontSize: pt(12.5), lineHeight: pt(LEAD), fontWeight: 600, color: col('accent'),
      marginTop: pt(LEAD), marginBottom: pt(LEAD / 2) }] },
  headingStyles,
  paragraphStyles: [
    style('rights', 'Crimson Pro', 8, 11, col('muted'), { marginBottom: pt(5) }),
    style('colophon', 'Crimson Pro', 9.5, 13, col('muted'), { italic: true, textAlign: 'center' }),
    ...coverStyles,
  ],
  toc: { levels: [{ level: 1, fontFamily: 'Crimson Pro', fontSize: pt(11), color: col('ink'),
    marginBottom: pt(LEAD / 2) }], pageNumber: { fontFamily: 'Crimson Pro', fontSize: pt(11),
    color: col('ink'), width: mm(8) }, leader: { char: ' ', gap: mm(2) } },
  header: { elements: [head('v', '{author}', 'even'), head('r', '{chapterTitle}', 'odd')] },
  footer: folioAt(-12, 'body'),
  production, cover, folio,
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The book runs on through three files (each within the Cookbook's 2,500 words), cut
// between paragraphs. The cover's text is a fifth: a frame per panel.
const markdown = String.raw`---
title: "The Spirits’ Mountain"
subtitle: "and The Emerald Eyes"
author: "Gustavo Adolfo Bécquer"
---

# The Spirits’ Mountain {style="half-title"}

# The Spirits’ Mountain {style="title-page" translators="Translated from the Spanish by Cornelia Frances Bates and Katharine Lee Bates" imprint="Moncayo Press · Soria"}

# Rights {style="rights"}

:::paragraphs{style="rights"}
The two legends appeared in the Madrid newspaper *El Contemporáneo* in 1861 and were gathered in Bécquer’s *Obras* in 1871. The translation by Cornelia Frances Bates and Katharine Lee Bates was published in *Romantic Legends of Spain* (New York, 1909) and is in the public domain; the text follows Project Gutenberg eBook 50044.

Paperback with flaps · ISBN 978-84-0000-196-4 · a sample number, assigned to no book.

Cover painting generated with diffusion models.

Set in Crimson Pro, Cormorant Garamond and Josefin Sans (SIL OFL) on 100 g/m² cream bulky book wove, bulk 2.4.
:::

# Contents {style="contents"}

:::toc

# The Spirits’ Mountain {style="tale-title" kicker="I" place="A Legend of Soria"}

# The Spirits’ Mountain {style="tale"}

On All Souls’ Night I was awakened, I knew not at what hour, by the tolling of bells; their monotonous, unceasing sound brought to mind this tradition which I heard a short time ago in Soria.

I tried to sleep again. Impossible! The imagination, once roused, is a horse that runs wild and cannot be reined in. To pass the time, I decided to write the story out, and so in fact I did.

I had heard it in the very place where it originated and, as I wrote, I sometimes glanced behind me with sudden fear, when, smitten by the cold night air, the glass of my balcony crackled.

Make of it what you will—here it goes loose, like the mounted horseman in a Spanish pack of cards.

## I

“Leash the dogs! Blow the horns to call the hunters together, and let us return to the city. Night is at hand—the Night of All Souls, and we are on the Spirits’ Mountain.”

“So soon!”

“Were it any day but this, I would not give up till I had made an end of that pack of wolves which the snows of the Moncayo have driven from their dens; but to-day it is impossible. Very soon the Angelus will sound in the monastery of the Knights Templars, and the souls of the dead will commence to toll their bell in the chapel on the mountain.”

“In that ruined chapel! Bah! Would you frighten me?”

“No, fair cousin; but you are not aware of all that happens hereabout, for it is not yet a year since you came hither from a distant part of Spain. Rein in your mare; I will keep mine at the same pace and tell you this story on the way.”

The pages gathered together in merry, boisterous groups; the Counts of Bórges and Alcudiel mounted their noble steeds, and the whole company followed after the son and daughter of those great houses, Alonso and Beatriz, who rode at some little distance in advance of the company.

As they went, Alonso related in these words the promised tradition:

“This mountain, which is now called the Spirits’ Mountain, belonged to the Knights Templars, whose monastery you see yonder on the river bank. The Templars were both monks and warriors. After Soria had been wrested from the Moors, the King summoned the Templars here from foreign lands to defend the city on the side next to the bridge, thus giving deep offense to his Castilian nobles, who, as they had won Soria alone, would alone have been able to defend it.

“Between the knights of the new and powerful Order and the nobles of the city there fermented for some years an animosity which finally developed into a deadly hatred. The Templars claimed for their own this mountain, where they reserved an abundance of game to satisfy their needs and contribute to their pleasures; the nobles determined to organize a great hunt within the bounds notwithstanding the rigorous prohibitions of the *clergy with spurs*, as their enemies called them.

“The news of the projected invasion spread fast, and nothing availed to check the rage for the hunt on the one side, and the determination to break it up on the other. The proposed expedition came off. The wild beasts did not remember it; but it was never to be forgotten by the many mothers mourning for their sons. That was not a hunting-trip, but a frightful battle; the mountain was strewn with corpses, and the wolves, whose extermination was the end in view, had a bloody feast. Finally the authority of the King was brought to bear; the mountain, the accursed cause of so many bereavements, was declared abandoned, and the chapel of the Templars, situated on this same wild steep, friends and enemies buried together in its cloister, began to fall into ruins.

“They say that ever since, on All Souls’ Night, the chapel bell is heard tolling all alone, and the spirits of the dead, wrapt in the tatters of their shrouds, run as in a fantastic chase through the bushes and brambles. The deer trumpet in terror, wolves howl, snakes hiss horribly, and on the following morning there have been seen clearly marked in the snow the prints of the fleshless feet of the skeletons. This is why we call it in Soria the Spirits’ Mountain, and this is why I wished to leave it before nightfall.”

Alonso’s story was finished just as the two young people arrived at the end of the bridge which admits to the city from that side. There they waited for the rest of the company to join them, and then the whole cavalcade was lost to sight in the dim and narrow streets of Soria.

## II

The servants had just cleared the tables; the high Gothic fireplace of the palace of the Counts of Alcudiel was shedding a vivid glow over the groups of lords and ladies who were chatting in friendly fashion, gathered about the blaze; and the wind shook the leaded glass of the ogive windows.

Two persons only seemed to hold aloof from the general conversation—Beatriz and Alonso. Beatriz, absorbed in a vague revery, followed with her eyes the capricious dance of the flames. Alonso watched the reflection of the fire sparkling in the blue eyes of Beatriz.

Both maintained for some time an unbroken silence.

The duennas were telling gruesome stories, appropriate to the Night of All Souls—stories in which ghosts and spectres played the principal rôles, and the church bells of Soria were tolling in the distance with a monotonous and mournful sound.

“Fair cousin,” finally exclaimed Alonso, breaking the long silence between them. “Soon we are to separate, perhaps forever. I know you do not like the arid plains of Castile, its rough, soldier customs, its simple, patriarchal ways. At various times I have heard you sigh, perhaps for some lover in your far-away demesne.”

Beatriz made a gesture of cold indifference; the whole character of the woman was revealed in that disdainful contraction of her delicate lips.

“Or perhaps for the grandeur and gaiety of the French capital, where you have lived hitherto,” the young man hastened to add. “In one way or another, I foresee that I shall lose you before long. When we part, I would like to have you carry hence a remembrance of me. Do you recollect the time when we went to church to give thanks to God for having granted you that restoration to health which was your object in coming to this region? The jewel that fastened the plume of my cap attracted your attention. How well it would look clasping a veil over your dark hair! It has already been the adornment of a bride. My father gave it to my mother, and she wore it to the altar. Would you like it?”

“I do not know how it may be in your part of the country,” replied the beauty, “but in mine to accept a gift is to incur an obligation. Only on a holy day may one receive a present

from a kinsman—though he may go to Rome without returning empty-handed.”

The frigid tone in which Beatriz spoke these words troubled the youth for a moment, but, clearing his brow, he replied sadly:

“I know it, cousin, but to-day is the festival of All Saints, and yours among them—a holiday on which gifts are fitting. Will you accept mine?”

Beatriz slightly bit her lip and put out her hand for the jewel, without a word.

The two again fell silent and again heard the quavering voices of the old women telling of witches and hobgoblins, the whistling wind which shook the ogive windows, and the mournful, monotonous tolling of the bells.

After the lapse of some little time, the interrupted dialogue was thus renewed:

“And before All Saints’ Day ends, which is holy to my saint as well as to yours, so that you can, without compromising yourself, give me a keepsake, will you not do so?” pleaded Alonso, fixing his eyes on his cousin’s, which flashed like lightning, gleaming with a diabolical thought.

“Why not?” she exclaimed, raising her hand to her right shoulder as though seeking for something amid the folds of her wide velvet sleeve embroidered with gold. Then, with an innocent air of disappointment, she added:

“Do you recollect the blue scarf I wore to-day to the hunt—the scarf which you said, because of something about the meaning of its color, was the emblem of your soul?”

“Yes.”

“Well! it is lost! it is lost, and I was thinking of letting you have it for a souvenir.”

“Lost! where?” asked Alonso, rising from his seat with an indescribable expression of mingled fear and hope.

“I do not know—perhaps on the mountain.”

“On the Spirits’ Mountain!” he murmured, paling and sinking back into his seat. “On the Spirits’ Mountain!”

Then he went on in a voice choked and broken:

“You know, for you have heard it a thousand times, that I am called in the city, in all Castile, the king of the hunters. Not having yet had a chance to try, like my ancestors, my strength in battle, I have brought to bear on this pastime, the image of war, all the energy of my youth, all the hereditary ardor of my race. The rugs your feet tread on are the spoils of the chase, the hides of the wild beasts I have killed with my own hand. I know their haunts and their habits; I have fought them by day and by night, on foot and on horseback, alone and with hunting-parties, and there is not a man will say that he has ever seen me shrink from danger. On any other night I would fly for that scarf—fly as joyously as to a festival; but to-night, this one night—why disguise it?—I am afraid. Do you hear? The bells are tolling, the Angelus has sounded in San Juan del Duero, the ghosts of the mountain are now beginning to lift their yellowing skulls from amid the brambles that cover their graves—the ghosts! the mere sight of them is enough to curdle with horror the blood of the bravest, turn his hair white, or sweep him away in the stormy whirl of their fantastic chase as a leaf, unwitting whither, is carried by the wind.”

While the young man was speaking, an almost imperceptible smile curled the lips of Beatriz, who, when he had ceased, exclaimed in an indifferent tone, while she was stirring the fire on the hearth, where the wood blazed and snapped, throwing off sparks of a thousand colors:

“Oh, by no means! What folly! To go to the mountain at this hour for such a trifle! On so dark a night, too, with ghosts abroad, and the road beset by wolves!”

As she spoke this closing phrase, she emphasized it with so peculiar an intonation that Alonso could not fail to understand all her bitter irony. As moved by a spring, he leapt to his feet, passed his hand over his brow as if to dispel the fear which was in his brain, not in his breast, and with firm voice he said, addressing his beautiful cousin, who was still leaning over the hearth, amusing herself by stirring the fire:

“Farewell, Beatriz, farewell. If I return, it will be soon.”

“Alonso, Alonso!” she called, turning quickly, but now that she wished—or made show of wishing—to detain him, the youth had gone.

In a few moments she heard the beat of a horse’s hoofs departing at a gallop. The beauty, with a radiant expression of satisfied pride flushing her cheeks, listened attentively to the sound which grew fainter and fainter until it died away.

The old dames, meanwhile, were continuing their tales of ghostly apparitions; the wind was shrilling against the balcony glass, and far away the bells of the city tolled on.

## III

An hour had passed, two, three; midnight would soon be striking, and Beatriz withdrew to her chamber. Alonso had not returned; he had not returned, though less than an hour would have sufficed for his errand.

“He must have been afraid!” exclaimed the girl, closing her prayer-book and turning toward her bed after a vain attempt to murmur some of the prayers that the church offers for the dead on the Day of All Souls.

After putting out her light and drawing the double silken curtains, she fell asleep; but her sleep was restless, light, uneasy.

The Postigo clock struck midnight. Beatriz heard through her dreams the slow, dull, melancholy strokes, and half opened her eyes. She thought she had heard, at the same time, her name spoken, but far, far away, and in a faint, suffering voice. The wind groaned outside her window.

“It must have been the wind,” she said, and pressing her hand above her heart, she strove to calm herself. But her heart beat ever more wildly. The larchwood doors of the chamber grated on their hinges with a sharp creak, prolonged and strident.
`;
const part2 = String.raw`First these doors, then the more distant ones—all the doors which led to her room opened, one after another, some with a heavy, groaning sound, some with a long wail that set the nerves on edge. Then silence, a silence full of strange noises, the silence of midnight, with a monotonous murmur of far-off water, the distant barking of dogs, confused voices, unintelligible words, echoes of footsteps going and coming, the rustle of trailing garments, half-suppressed sighs, labored breathing almost felt upon the face, involuntary shudders that announce the presence of something not seen, though its approach is felt in the darkness.

Beatriz, stiffening with fear, yet trembling, thrust her head out from the bed-curtains and listened a moment. She heard a thousand diverse noises; she passed her hand across her brow and listened again; nothing, silence.

She saw, with that dilation of the pupils common in nervous crises, dim shapes moving hither and thither all about the room, but when she fixed her gaze on any one point, there was nothing but darkness and impenetrable shadows.

“Bah!” she exclaimed, again resting her beautiful head upon her blue satin pillow, “am I as timid as these poor kinsfolk of mine, whose hearts thump with terror under their armor when they hear a ghost-story?”

And closing her eyes she tried to sleep—but her effort to compose herself was in vain. Soon she started up again, paler, more uneasy, more terrified. This time it was no illusion; the brocade hangings of the door had rustled as they were pushed to either side, and slow footsteps were heard upon the carpet; the sound of those footsteps was muffled, almost imperceptible, but continuous, and she heard, keeping measure with them, a creaking as of dry wood or bones. And the footfalls came nearer, nearer; the prayer-stool by the side of her bed moved. Beatriz uttered a sharp cry, and burying herself under the bedclothes, hid her head and held her breath.

The wind beat against the balcony glass; the water of the far-off fountain was falling, falling, with a monotonous, unceasing sound; the barking of the dogs was borne upon the gusts, and the church bells in the city of Soria, some near, some remote, tolled sadly for the souls of the dead.

So passed an hour, two, the night, a century, for that night seemed to Beatrix eternal. At last the day began to break; putting fear from her, she half opened her eyes to the first silver rays. How beautiful, after a night of wakefulness and terrors, is the clear white light of dawn! She parted the silken curtains of her bed and was ready to laugh at her past alarms, when suddenly a cold sweat covered her body, her eyes seemed starting from their sockets, and a deadly pallor overspread her cheeks; for on her prayer-stool she had seen, torn and blood-stained, the blue scarf she lost on the mountain, the blue scarf Alonso went to seek.

When her attendants rushed in, aghast, to tell her of the death of the heir of Alcudiel, whose body, partly devoured by wolves, had been found that morning among the brambles on the Spirits’ Mountain, they discovered her motionless, convulsed, clinging with both hands to one of the ebony bedposts, her eyes staring, her mouth open, the lips white, her limbs rigid—dead, dead of fright!

## IV

They say that, some time after this event, a hunter who, having lost his way, had been obliged to pass the Night of the Dead on the Spirits’ Mountain, and who in the morning, before he died, was able to relate what he had seen, told a tale of horror. Among other awful sights, he avowed he beheld the skeletons of the ancient Knights Templars and of the nobles of Soria, buried in the cloister of the chapel, rise at the hour of the Angelus with a horrible rattle and, mounted on their bony steeds, chase, as a wild beast, a beautiful woman, pallid, with streaming hair, who, uttering cries of terror and anguish, had been wandering, with bare and bloody feet, about the tomb of Alonso.

# The Emerald Eyes {style="tale-title" kicker="II" place="A Legend of the Moncayo"}

# The Emerald Eyes {style="tale"}

For a long time I have desired to write something with this title. Now that the opportunity has come, I have inscribed it in capital letters at the top of the page and have let my pen run at will.

I believe that I have seen eyes like those I have painted in this legend. It may have been in my dreams, but I have seen them. Too true it is that I shall not be able to describe them as they were, luminous, transparent as drops of rain slipping over the leaves of the trees after a summer shower. At all events, I count upon the imagination of my readers to understand me in what we might call a sketch for a picture which I will paint some day.

## I

“The stag is wounded—he is wounded; no doubt of it. There are traces of his blood on the mountain shrubs, and in trying to leap one of those mastic trees his legs failed him. Our young lord begins where others end. In my forty years as huntsman I have not seen a better shot. But by Saint Saturio, patron of Soria, cut him off at these hollies, urge on the dogs, blow the horns till your lungs are empty, and bury your spurs in the flanks of the horses. Do you not see that he is going toward the fountain of the Poplars, and if he lives to reach it we must give him up for lost?”

The glens of the Moncayo flung from echo to echo the braying of the horns and barking of the unleashed pack of hounds; the shouts of the pages resounded with new vigor, while the confused throng of men, dogs and horses rushed toward the point which Iñigo, the head huntsman of the Marquises of Almenar, indicated as the one most favorable for intercepting the quarry.

But all was of no avail. When the fleetest of the greyhounds reached the hollies, panting, its jaws covered with foam, already the deer, swift as an arrow, had cleared them at a single bound, disappearing among the thickets of a narrow path which led to the fountain.

“Draw rein! draw rein, every man!” then cried Iñigo. “It was the will of God that he should escape.”

And the troop halted, the horns fell silent and the hounds, at the call of the hunters, abandoned, snarling, the trail.

At that moment, the lord of the festival, Fernando de Argensola, the heir of Almenar, came up with the company.

“What are you doing?” he exclaimed, addressing his huntsman, astonishment depicted on his features, anger burning in his eyes. “What are you doing, idiot? Do you see that the creature is wounded, that it is the first to fall by my hand, and yet you abandon the pursuit and let it give you the slip to die in the depths of the forest? Do you think perchance that I have come to kill deer for the banquets of wolves?”

“*Señor*,” murmured Iñigo between his teeth, “it is impossible to pass this point.”

“Impossible! And why?”

“Because this path,” continued the huntsman, “leads to the fountain of the Poplars, the fountain of the Poplars in whose waters dwells an evil spirit. He who dares trouble its flow pays dear for his rashness. Already the deer will have reached its borders; how will you take it without drawing on your head some fearful calamity? We hunters are kings of the Moncayo, but kings that pay a tribute. A quarry which takes refuge at this mysterious fountain is a quarry lost.”

“Lost! Sooner will I lose the seigniory of my fathers, sooner will I lose my soul into the hands of Satan than permit this stag to escape me, the only one my spear has wounded, the first fruits of my hunting. Do you see him? Do you see him? He can still at intervals be made out from here. His legs falter, his speed slackens; let me go, let me go! Drop this bridle or I roll you in the dust! Who knows if I will not run him down before he reaches the fountain? And if he should reach it, to the devil with it, its untroubled waters and its inhabitants! On, Lightning! on, my steed! If you overtake him, I will have the diamonds of my coronet set in a headstall all of gold for you.”

Horse and rider departed like a hurricane.

Iñigo followed them with his eyes till they disappeared in the brush. Then he looked about him: all like himself remained motionless, in consternation.

The huntsman exclaimed at last:

“*Señores*, you are my witnesses. I exposed myself to death under his horse’s hoofs to hold him back. I have fulfilled my duty. Against the devil heroism does not avail. To this point comes the huntsman with his crossbow; beyond this, it is for the chaplain with his holy water to attempt to pass.”

## II

“You are pale; you go about sad and gloomy. What afflicts you? From the day, which I shall ever hold in hate, on which you went to the fountain of the Poplars in chase of the wounded deer, I should say an evil sorceress had bewitched you with her enchantments.

“You do not go to the mountains now preceded by the clamorous pack of hounds, nor does the blare of your horns awake the echoes. Alone with these brooding fancies which beset you, every morning you take your crossbow only to plunge into the thickets and remain there until the sun goes down. And when night darkens and you return to the castle, white and weary, in vain I seek in the game-bag the spoils of the chase. What detains you so long far from those who love you most?”

While Iñigo was speaking, Fernando, absorbed in his thoughts, mechanically cut splinters from the ebony bench with his hunting knife.

After a long silence, which was interrupted only by the click of the blade as it slipped over the polished wood, the young man, addressing his servant as if he had not heard a single word, exclaimed:

“Iñigo, you who are an old man, you who know all the haunts of the Moncayo, who have lived on its slopes pursuing wild beasts and in your wandering hunting trips have more than once stood on its summit, tell me, have you ever by chance met a woman who dwells among its rocks?”

“A woman!” exclaimed the huntsman with astonishment, looking closely at him.

“Yes,” said the youth. “It is a strange thing that has happened to me, very strange. I thought I could keep this secret always; but it is no longer possible. It overflows my heart and begins to reveal itself in my face. Therefore I am going to tell it to you. You will help me solve the mystery which enfolds this being who seems to exist only for me, since no one knows her or has seen her, or can give me any account of her.”

The huntsman, without opening his lips, drew forward his stool to place it near the ebony bench of his lord from whom he did not once remove his affrighted eyes. The youth, after arranging his thoughts, continued thus:

“From the day on which, notwithstanding your gloomy predictions, I went to the fountain of the Poplars, and crossing its waters recovered the stag which your superstition would have let escape, my soul has been filled with a desire for solitude.

“You do not know that place. See, the fountain springs from a hidden source in the cavity of a rock, and falls in trickling drops through the green, floating leaves of the plants that grow on the border of its cradle. These drops, which on falling glisten like points of gold and sound like the notes of a musical instrument, unite on the turf and murmuring, murmuring with a sound like that of bees humming about the flowers, glide on through the gravel, and form a rill and contend with the obstacles in their way, and gather volume and leap and flee and run, sometimes with a laugh, sometimes with sighs, until they fall into a lake. Into the lake they fall with an indescribable sound. Laments, words, names, songs, I know not what I have heard in that sound when I have sat, alone and fevered, upon the huge rock at whose feet the waters of that mysterious fountain leap to bury themselves in a deep pool whose still surface is scarcely rippled by the evening wind.

“Everything there is grand. Solitude with its thousand vague murmurs dwells in those places and transports the mind with a profound melancholy. In the silvered leaves of the poplars, in the hollows of the rocks, in the waves of the water it seems that the invisible spirits of nature talk with us, that they recognize a brother in the immortal soul of man.

“When at break of dawn you would see me take my crossbow and go toward the mountain, it was never to lose myself among the thickets in pursuit of game. No, I went to sit on the rim of the fountain, to seek in its waves—I know not what—an absurdity! The day I leaped over it on my Lightning, I believed I saw glittering in its depths a marvel—truly a marvel—the eyes of a woman!

“Perhaps it may have been a fugitive ray of sunshine that wound, serpent like, through the foam; perhaps one of those flowers which float among the weeds of its bosom, flowers whose calyxes seem to be emeralds—I do not know. I thought I saw a gaze which fixed itself on mine, a look which kindled in my breast a desire absurd, impossible of realization, that of meeting a person with eyes like those.

“In my search, I went to that place day after day.
`;
const part3 = String.raw`“At last, one afternoon—I thought myself the plaything of a dream—but no, it is the truth; I have spoken with her many times as I am now speaking with you—one afternoon I found, sitting where I had sat, clothed in a robe which reached to the waters and floated on their surface, a woman beautiful beyond all exaggeration. Her hair was like gold; her eyelashes shone like threads of light, and between the lashes flashed the restless eyes that I had seen—yes; for the eyes of that woman were the eyes which I bore stamped upon my mind, eyes of an impossible color, the color——”

“Green!” exclaimed Iñigo, in accents of profound terror, starting with a bound from his seat.

Fernando, in turn, looked at him as if astonished that Iñigo should supply what he was about to say, and asked him with mingled anxiety and joy:

“Do you know her?”

“Oh, no!” said the huntsman. “God save me from knowing her! But my parents, on forbidding me to go toward those places, told me a thousand times that the spirit, goblin, demon or woman, who dwells in those waters, has eyes of that color. I conjure you by that which you love most on earth not to return to the fountain of the Poplars. One day or another her vengeance will overtake you, and you will expiate in death the crime of having stained her waters.”

“By what I love most!” murmured the young man with a sad smile.

“Yes,” continued the elder. “By your parents, by your kindred, by the tears of her whom heaven destines for your wife, by those of a servant who watched beside your cradle.”

“Do you know what I love most in this world? Do you know for what I would give the love of my father, the kisses of her who gave me life, and all the affection which all the women on earth can hold in store? For one look, for only one look of those eyes! How can I leave off seeking them?”

Fernando said these words in such a tone that the tear which trembled on the eyelids of Iñigo fell silently down his cheek, while he exclaimed with a mournful accent: “The will of Heaven be done!”

## III

“Who art thou? What is thy fatherland? Where dost thou dwell? Day after day I come seeking thee, and see neither the palfrey that brings thee hither, nor the servants who bear thy litter. Rend once for all the veil of mystery in which thou dost enfold thyself as in the heart of night. I love thee and, highborn or lowly, I will be thine, thine forever.”

The sun had crossed the crest of the mountain. The shadows were descending its slope with giant strides. The breeze sighed amid the poplars of the fountain. The mist, rising little by little from the surface of the lake, began to envelop the rocks of its margin.

Upon one of these rocks, on one which seemed ready to topple over into the depths of the waters on whose surface was pictured its wavering image, the heir of Almenar, on his knees at the feet of his mysterious beloved, sought in vain to draw from her the secret of her existence.

She was beautiful, beautiful and pallid as an alabaster statue. One of her tresses fell over her shoulders, entangling itself in the folds of her veil like a ray of sunlight passing through clouds; and her eyes, within the circle of her amber-colored lashes, gleamed like emeralds set in fretted gold.

When the youth ceased speaking, her lips moved as for utterance, but only exhaled a sigh, a sigh soft and sorrowful like that of the gentle wave which a dying breeze drives among the rushes.

“Thou answerest not,” exclaimed Fernando, seeing his hope mocked. “Wouldst thou have me credit what they have told me of thee? Oh, no! Speak to me. I long to know if thou lovest me; I long to know if I may love thee, if thou art a woman——”

—“Or a demon. And if I were?”

The youth hesitated a moment; a cold sweat ran through his limbs; the pupils of his eyes dilated, fixing themselves with more intensity upon those of that woman and, fascinated by their phosphoric brilliance, as though demented he exclaimed in a burst of passion:

“If thou wert, I should love thee. I should love thee as I love thee now, as it is my destiny to love thee even beyond this life, if there be any life beyond.”

“Fernando,” said the beautiful being then, in a voice like music: “I love thee even more than thou lovest me; in that I, who am pure spirit, stoop to a mortal. I am not a woman like those that live on earth. I am a woman worthy of thee who art superior to the rest of humankind. I dwell in the depths of these waters, incorporeal like them, fugitive and transparent; I speak with their murmurs and move with their undulations. I do not punish him who dares disturb the fountain where I live; rather I reward him with my love, as a mortal superior to the superstitions of the common herd, as a lover capable of responding to my strange and mysterious embrace.”

While she was speaking, the youth, absorbed in the contemplation of her fantastic beauty, drawn on as by an unknown force, approached nearer and nearer the edge of the rock. The woman of the emerald eyes continued thus:

“Dost thou behold, behold the limpid depths of this lake, behold these plants with large, green leaves which wave in its bosom? They will give us a couch of emeralds and corals and I—I will give thee a bliss unnamable, that bliss which thou hast dreamed of in thine hours of delirium, and which no other can bestow.—Come! the mists of the lake float over our brows like a pavilion of lawn, the waves call us with their incomprehensible voices, the wind sings among the poplars hymns of love; come—come!”

Night began to cast her shadows, the moon shimmered on the surface of the pool, the mist was driven before the rising breeze, the green eyes glittered in the dusk like the will-o’-the-wisps that run over the surface of impure waters. “Come, come!” these words were murmuring in the ears of Fernando like an incantation—“Come!” and the mysterious woman called him to the brink of the abyss where she was poised, and seemed to offer him a kiss—a kiss——

Fernando took one step toward her—another—and felt arms slender and flexible twining about his neck and a cold sensation on his burning lips, a kiss of snow—wavered, lost his footing and fell, striking the water with a dull and mournful sound.

The waves leaped in sparks of light, and closed over his body, and their silvery circles went widening, widening until they died away on the banks.

# Colophon {style="colophon"}

:::paragraphs{style="colophon"}
This book was set in November 2026, on the eve of All Souls’ Night.
:::
`;
const coverText = String.raw`:::frame{slot="back"}
:::paragraphs{style="cover-blurb"}
On All Souls’ Night the bell of a ruined Templar chapel rings by itself above Soria, and a young noble rides out to fetch a blue sash his cousin says she lost on the mountain. A hunter follows a woman with green eyes to a spring on the slopes of the Moncayo.
:::

:::paragraphs{style="cover-blurb"}
Bécquer wrote these two legends in his twenties, for the Madrid newspaper *El Contemporáneo*, from stories he heard in the towns where they happen.
:::

:::paragraphs{style="cover-note"}
Translated by Cornelia Frances Bates and Katharine Lee Bates
:::
:::

:::frame{slot="flapFront"}
:::paragraphs{style="flap-head"}
Gustavo Adolfo Bécquer
:::

:::paragraphs{style="flap-text"}
was born in Seville in 1836 and went to Madrid at eighteen to make a living as a writer. He wrote for newspapers, translated plays and worked as a government censor of novels. In 1864 he spent months in the monastery of Veruela, at the foot of the Moncayo, and sent from there the letters *Desde mi celda*. He died in Madrid in 1870, at thirty-four. His *Rimas* and *Leyendas* were collected by his friends and published the following year.
:::
:::

:::frame{slot="flapBack"}
:::paragraphs{style="flap-head"}
The translators
:::

:::paragraphs{style="flap-text"}
Cornelia Frances Bates (1826–1908) began to study Spanish at seventy-one and read Bécquer in two small green volumes with a red dictionary beside them. Her daughter Katharine Lee Bates (1859–1929), professor of English at Wellesley College, finished the translation they had planned together and published it in New York in 1909 as *Romantic Legends of Spain*.
:::
:::
`;
const resources = [{ id: 'moncayo', typeId: 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: 'moncayo.jpg', format: 'jpeg', width: 1100, height: 1771 },
  altText: t({ en: 'A ruined chapel with a lit window on a rocky hill at night, a snowy '
    + 'ridge behind it and a rider in a red cloak on the path below.',
  es: 'Una capilla en ruinas con una ventana encendida en un cerro de noche, una sierra '
    + 'nevada detrás y un jinete de capa roja en el camino.' }) }];
await loadImage('moncayo.jpg', asset('moncayo-1100.jpg'));

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

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const book = await buildDocumentWithFonts({ markdown: [markdown, part2, part3]
  .join('\n\n'), resources }, config, kitFonts(FONTS));

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

showPages(book, { title: t({ en: 'The Spirits’ Mountain · paperback with flaps',
  es: 'El monte de las ánimas · rústica con solapas' }) });
// The sheet above the pages, with the measures buildCover worked out.
const { spine, width, height } = built.sheet;
const canvas = document.createElement('canvas');
canvas.style.cssText = 'display: block; width: min(1200px, 94vw); margin: 32px auto 8px';
canvas.title = `${book.pages.length} pp. · spine ${spine.toFixed(1)} mm · sheet `
  + `${width.toFixed(1)} × ${height.toFixed(1)} mm`;
document.getElementById('pages').before(canvas, canvas.title);
renderPageToCanvas(sheet.pages[0], sheet, canvas, { scale: 2400 / sheet.pages[0].width });

// One file for the printer: the pages, then the sheet at its own size.
offerPdf(() => renderToPdf([book, sheet], { fontProvider: fontsourceProvider,
  resourceBytes: imageBytes }), `${RECIPE}.pdf`);

// ─── Kit ── helpers shared by every Cookbook recipe · postext.dev/cookbook ─────

// ─── Kit · core v1 ── the same in every recipe · postext.dev/cookbook
function mm(value) { return { value, unit: 'mm' }; }
function pt(value) { return { value, unit: 'pt' }; }
function em(value) { return { value, unit: 'em' }; }
/** The sample language's string: t({ en: 'Figure', es: 'Figura' }). */
function t(strings) { return strings[LANG] ?? Object.values(strings)[0]; }
/** A file in this recipe's assets folder, served from the Postext repo by jsDelivr. */
function asset(file) { return `https://cdn.jsdelivr.net/gh/drnachio/postext@main/cookbook/${RECIPE}/assets/${file}`; }

// ─── Kit · fonts v3 ── the same in every recipe · postext.dev/cookbook
// Postext loads the faces a config asks for before layout and asks the kit
// for Fontsource's files, the ones the PDF embeds too.

/** buildDocumentWithFonts' options: the resolver, and FONTS' faces loaded
 *  with the config's. FONTS = { 'Family Name': ['400', '400i', '700'] }. */
function kitFonts(FONTS = {}) {
  const faces = Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) =>
    ({ family, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' })));
  return { resolve: fontsourceResolver, faces };
}

/** A face's files with their ranges: latin, then latin-ext and greek when
 *  `text` needs them (kitSubsetsFor). Null for a face Fontsource lacks. */
async function fontsourceResolver(family, weight, style, { text = '' } = {}) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  if (meta && !(await fontsourceWeights(family, style)).includes(weight)) return null;
  kitStatus('Loading fonts…');
  const at = await fontsourceAt(id);
  return ['latin', ...kitSubsetsFor(text, meta)].map((subset) => ({
    source: `${at}files/${id}-${subset}-${weight}-${style}.woff2`,
    unicodeRange: kitRanges()[subset],
  }));
}

/** Each file's unicode-range (a function: the kit runs after the pen's code). */
function kitRanges() {
  return {
    latin: 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,'
      + 'U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD',
    'latin-ext': 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,'
      + 'U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF',
    greek: 'U+0370-03FF',
  };
}

/** For the cjk, arabic and comics blocks: loads `faces` (as FONTS) for the
 *  sample `text`; `optional` skips a face Fontsource lacks. Files are added in
 *  the order asked, the last winning a shared character. Resolves to the count. */
async function loadFonts(faces, text = '', { optional = false } = {}) {
  kitStatus('Loading fonts…');
  const ranges = kitRanges();
  const jobs = [];
  for (const [family, specs] of Object.entries(faces)) {
    const id = fontsourceId(family);
    const todo = [...new Set(specs)].map((spec) => [parseInt(spec, 10), spec.endsWith('i') ? 'italic' : 'normal'])
      .filter(([weight, style]) => !hasFace(family, weight, style)); // before any await
    const at = fontsourceAt(id);
    const meta = optional || /[^\0-ÿ]/u.test(text) ? await fontsourceMeta(family) : null;
    const subsets = ['latin', ...kitSubsetsFor(text, meta)];
    for (const [weight, style] of todo) {
      if (optional && !(meta && (await fontsourceWeights(family, style)).includes(weight))) continue;
      for (const subset of subsets) {
        const url = `${await at}files/${id}-${subset}-${weight}-${style}.woff2`;
        const face = new FontFace(family, `url(${url}) format('woff2')`,
          { weight: String(weight), style, unicodeRange: ranges[subset] });
        jobs.push(face.load().catch(() => {
          if (subset === 'latin' && !optional) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
        }));
      }
    }
  }
  const ready = await Promise.all(jobs).catch((error) => { kitFail(error); throw error; });
  return ready.filter((face) => face && document.fonts.add(face)).length;
}

/** A loaded FontFace covers this face (fonts.check() says yes to any family). */
function hasFace(family, weight, style) {
  for (const face of document.fonts) {
    if (face.status !== 'loaded' || face.style !== style) continue;
    if (face.family.replace(/^["']|["']$/g, '') !== family) continue;
    const [low, high = low] = face.weight.split(' ').map(Number);
    if (weight >= low && weight <= high) return true;
  }
  return false;
}

/** The files beyond latin `text` needs that `meta`'s family ships. */
function kitSubsetsFor(text, meta) {
  return [[/[Ā-˿ᴀ-ᶿḀ-ỿ†ℓⱠ-Ɀ꜠-ꟿ]/u, 'latin-ext'], [/[Ͱ-Ͽ]/u, 'greek']]
    .filter(([re, x]) => re.test(text) && meta?.subsets?.includes(x)).map(([, x]) => x);
}

/** Fontsource's id for a family: 'Source Serif 4' → 'source-serif-4'. */
function fontsourceId(family) { return family.toLowerCase().replace(/\s+/g, '-'); }

/** A package's folder at the one version @5 names now (#766). */
function fontsourceAt(id, u = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@`) {
  return (fontsourceAt.c ??= {})[id] ??= fetch(u + '5/package.json').then((r) => r.json())
    .then((p) => p.version || 5, () => 5).then((v) => `${u}${v}/`);
}

/** The family's Fontsource metadata (weights, styles, subsets), or null. */
function fontsourceMeta(family, id = fontsourceId(family)) {
  return (fontsourceMeta.c ??= {})[id] ??= fetch(`https://api.fontsource.org/v1/fonts/${id}`)
    .then((res) => (res.ok ? res.json() : null), () => null);
}

/** The weights the package ships in `style`: the API pairs none (no Libre
 *  Caslon 700 italic file), so italics are read from latin-italic.css. */
function fontsourceWeights(family, style, id = fontsourceId(family)) {
  return (fontsourceWeights.c ??= {})[id + style] ??= fontsourceMeta(family).then(async (m) => {
    if (!m?.styles.includes(style)) return m ? [] : [400, 700];
    const css = style === 'italic' ? await fetch(`${await fontsourceAt(id)}latin-italic.css`).then((r) => (r.ok ? r.text() : ''), () => '') : '';
    const w = [...css.matchAll(/weight: (\d+)/g)].map((x) => +x[1]);
    return w.length ? w : m.weights;
  });
}

// ─── Kit · viewer v2 ── the same in every recipe · postext.dev/cookbook
/** The pages as spreads on a dark desk, page 1 alone, then verso | recto,
 *  each painted when it scrolls near. Other options go to renderPageToCanvas. */
function showPages(docs, { title, width = 460, ...render } = {}) {
  const root = viewer(title);
  const pages = [docs].flat().flatMap((doc) =>
    doc.pages.map((page) => ({ doc, page, n: (doc.pageIndexOffset ?? 0) + page.index })));
  const spreads = [];
  let verso = null;
  for (const p of pages) {
    if (p.n % 2 === 1) { if (verso) spreads.push([verso, null]); verso = p; }
    else { spreads.push([verso, p]); verso = null; }
  }
  if (verso) spreads.push([verso, null]);
  const density = Math.min(window.devicePixelRatio || 1, 2);
  showPages.painter?.disconnect();
  const painter = new IntersectionObserver((entries) => {
    for (const { isIntersecting, target } of entries) {
      if (!isIntersecting) continue;
      painter.unobserve(target);
      const { doc, page } = target.postext;
      renderPageToCanvas(page, doc, target, { ...render, scale: (width * density) / page.width });
    }
  }, { rootMargin: '800px' });
  showPages.painter = painter;
  root.replaceChildren(...spreads.map((pair) => {
    const spread = document.createElement('div');
    spread.className = 'pt-spread';
    for (const p of pair) {
      const figure = document.createElement('figure');
      if (p) {
        const label = p.page.pageLabel || String(p.n + 1);
        const canvas = document.createElement('canvas');
        canvas.postext = p;
        canvas.style.aspectRatio = `${p.page.width} / ${p.page.height}`;
        canvas.setAttribute('role', 'img');
        canvas.setAttribute('aria-label', `Page ${label}`);
        const folio = document.createElement('figcaption');
        folio.textContent = label;
        figure.append(canvas, folio);
        painter.observe(canvas);
      } else figure.className = 'pt-blank';
      spread.append(figure);
    }
    return spread;
  }));
  kitStatus(`${pages.length} ${pages.length === 1 ? 'page' : 'pages'}`);
  document.documentElement.dataset.postext = 'ready';
  return pages.length;
}

/** The desk, the bar and the error reporting, created once. */
function viewer(title) {
  if (!document.getElementById('pt-kit')) {
    document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit">
      :root { color-scheme: dark; }
      body { margin: 0; background: #0e1014; color: #b9bcc4; font: 13px/1.45 system-ui, sans-serif; }
      #pt-bar { position: sticky; top: 0; z-index: 1; display: flex; flex-wrap: wrap; align-items: center;
        gap: 6px 16px; padding: 10px 16px; background: rgb(14 16 20 / .92); backdrop-filter: blur(6px);
        border-bottom: 1px solid #23262d; }
      #pt-bar strong { color: #f4f1ea; font-weight: 600; }
      #pt-actions { display: flex; gap: 12px; margin-left: auto; }
      #pt-actions a, #pt-actions button { color: #d8a21a; font: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
      #pages { display: grid; justify-items: center; gap: 48px; padding: 32px 16px 72px; }
      .pt-spread { display: flex; }
      .pt-spread figure { margin: 0; width: min(460px, 44vw); }
      .pt-spread canvas { display: block; width: 100%; background: #fff;
        box-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figure:first-child canvas { box-shadow: inset -14px 0 14px -14px rgb(0 0 0 / .18), 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figcaption { margin-top: 10px; text-align: center; font: 600 10px/1 system-ui, sans-serif;
        letter-spacing: .18em; text-transform: uppercase; color: #6c7079; }
      .pt-blank { visibility: hidden; }
      @media (max-width: 760px) {
        .pt-spread { flex-direction: column; gap: 32px; }
        .pt-spread figure { width: min(460px, 92vw); }
        .pt-blank { display: none; }
      }
    </style>`);
    document.body.insertAdjacentHTML('afterbegin',
      '<header id="pt-bar"><strong id="pt-title"></strong><span id="pt-status" role="status"></span><span id="pt-actions"></span></header>');
    document.getElementById('pt-title').textContent = document.title || 'Postext';
    addEventListener('error', (event) => kitFail(event.error ?? event.message));
    addEventListener('unhandledrejection', (event) => kitFail(event.reason));
  }
  if (title) document.getElementById('pt-title').textContent = title;
  return document.getElementById('pages')
    ?? document.body.appendChild(Object.assign(document.createElement('main'), { id: 'pages' }));
}

function kitStatus(text) {
  viewer();
  document.getElementById('pt-status').textContent = text;
}

function kitFail(error) {
  document.documentElement.dataset.postext = 'error';
  kitStatus(`Error: ${error?.message ?? error}`);
}

// ─── Kit · pdf v3 ── the same in every recipe that exports a PDF
/** The Fontsource files the screen used, as TrueType, with their range and
 *  place: the nearest weight the family ships in that style, upright with no italic;
 *  latin, then what its letters need (kitSubsetsFor). */
async function fontsourceProvider(family, weight, style, request) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  const s = style === 'italic' && meta && !meta.styles.includes('italic') ? 'normal' : style;
  const shipped = meta ? await fontsourceWeights(family, s) : [];
  const weights = shipped.length ? shipped : [400, 700];
  const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const text = String.fromCodePoint(...(request?.codePoints ?? []));
  const files = await Promise.all(['latin', ...kitSubsetsFor(text, meta)].map(async (subset, order) => {
    const res = await fetch(`${await fontsourceAt(id)}files/${id}-${subset}-${w}-${s}.woff2`);
    if (!res.ok) throw new Error(`Fontsource has no ${family} ${w} ${s} ${subset}`);
    return Object.assign(await decompressWoff2(new Uint8Array(await res.arrayBuffer())),
      { unicodeRange: kitRanges()[subset], order });
  }));
  return files.length === 1 ? files[0] : files;
}

/** A "Build the PDF" button; then "Open the PDF" (a new tab: CodePen's frame
 *  shows no PDFs) and a download link. */
function offerPdf(makePdf, filename) {
  viewer();
  const button = Object.assign(document.createElement('button'), { type: 'button', textContent: 'Build the PDF' });
  button.dataset.postextPdf = filename;
  button.addEventListener('click', async () => {
    button.disabled = true;
    button.textContent = 'Building the PDF…';
    try {
      const bytes = await makePdf();
      const url = URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }));
      const size = `${Math.max(1, Math.round(bytes.length / 1024))} KB`;
      button.replaceWith(
        Object.assign(document.createElement('a'), { href: url, target: '_blank', rel: 'noopener', textContent: 'Open the PDF ↗' }),
        Object.assign(document.createElement('a'), { href: url, download: filename, textContent: `Download ${filename} · ${size}` }));
    } catch (error) {
      button.disabled = false;
      button.textContent = 'Build the PDF';
      kitFail(error);
    }
  });
  document.getElementById('pt-actions').append(button);
}

// ─── Kit · images v3 ── recipes with pictures · postext.dev/cookbook
/** Registers a photo or PNG for the canvas and keeps its bytes for the PDF.
 *  fetch → ImageBitmap never taints the canvas (a plain cross-origin <img> would). */
async function loadImage(fileId, url) {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`Image not found (${res.status}): ${url}`);
  const bytes = new Uint8Array(await res.arrayBuffer());
  registerResourceImage(fileId, await createImageBitmap(new Blob([bytes])));
  (loadImage.bytes ??= new Map()).set(fileId, bytes);
}

/** Registers SVG markup as a vector image, its fonts inside (inlineSvgFonts, ≥ 1.25).
 *  `options` go to registerResourceImage: { singleInk: true } tints it on the canvas. */
async function loadSvg(fileId, svg, options) {
  if (typeof inlineSvgFonts === 'function') svg = await inlineSvgFonts(svg, svgFaces);
  const img = new Image();
  img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
  await img.decode();
  registerResourceImage(fileId, img, options);
  (loadImage.bytes ??= new Map()).set(fileId, new TextEncoder().encode(svg));
}

/** A face's Fontsource files: nearest weight; latin + what the SVG sets. */
async function svgFaces(family, weight, style, { codePoints = [] } = {}) {
  const [id, m] = [fontsourceId(family), await fontsourceMeta(family)];
  const w = m?.weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a)) ?? weight;
  const s = m?.styles.includes(style) === false ? 'normal' : style;
  return Promise.all(['latin', ...kitSubsetsFor(String.fromCodePoint(...codePoints), m)].map(async (x) => new Uint8Array(
    await (await fetch(`${await fontsourceAt(id)}files/${id}-${x}-${w}-${s}.woff2`)).arrayBuffer())));
}

/** renderToPdf({ resourceBytes: imageBytes }) */
function imageBytes(fileId) { return loadImage.bytes?.get(fileId); }

/** renderToHtml({ resourceImageUrl: imageUrl }) */
function imageUrl(fileId) {
  const bytes = imageBytes(fileId);
  if (!bytes) return undefined;
  imageUrl.urls ??= new Map();
  if (!imageUrl.urls.has(fileId)) {
    const type = /\.svg$/i.test(fileId) ? 'image/svg+xml' : /\.png$/i.test(fileId) ? 'image/png' : 'image/jpeg';
    imageUrl.urls.set(fileId, URL.createObjectURL(new Blob([bytes], { type })));
  }
  return imageUrl.urls.get(fileId);
}

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

## تنويعات

### اكتب الكعب من الأسفل إلى الأعلى

يُكتب الكعب افتراضيًا من الأعلى إلى الأسفل، كما تنص المواصفة ISO 6357 وكما تفعل الكتب الإنجليزية، فيُقرأ مستقيمًا والكتاب مستلقٍ على وجهه الأمامي. أما العادة الأقدم في إسبانيا وأوروبا القارية فتكتبه من الأسفل إلى الأعلى.

```diff
   versions: [{ id: 'paperback', name: t({ en: 'Paperback', es: 'Rústica' }), binding: 'pur-flaps',
-    flaps: true, isbn: '978-84-0000-196-4', isbnAddOn: '90000' }],
+    flaps: true, isbn: '978-84-0000-196-4', isbnAddOn: '90000',
+    spineText: { direction: 'bottomToTop' } }],
```

### اطبع على ورق أرق

بوزن 80 غ/م² وانتفاخ 2.2 يصير سمك الورقة 176 ميكرومترًا، وينزل الكعب إلى 4.7 مم ويفقد كتابته التي تحتاج إلى 6 مم.

```diff
-const folio = { paper: { type: 'bookWove', grammage: 100, bulk: 2.4, shade: '#f7f1e3' } };
+const folio = { paper: { type: 'bookWove', grammage: 80, bulk: 2.2, shade: '#f7f1e3' } };
```

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

- في قائمة الصفحات الملتقطة يأتي الفرخ بعد صفحات الكتاب، فرقمه هو عدد صفحات الكتاب زائد واحد. وإذا زادت صفحات الكتاب صفحة تغيّر الرقم.
- إذا طلبت أرقام الرمز الشريطي خطًا لا يجده ملف PDF فشل التصدير. حمّل ملف SVG الخاص به مع `font-family` لخط حمّله المثال من قبل.

## الحقوق

- الوصفة: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- النص: The Spirits’ Mountain and The Emerald Eyes, translated by Cornelia Frances Bates and Katharine Lee Bates, from Romantic Legends of Spain (1909), Project Gutenberg eBook #50044: Gustavo Adolfo Bécquer ([المصدر](https://www.gutenberg.org/ebooks/50044)), ملكية عامة
- النص: El monte de las ánimas and Los ojos verdes, from the Obras (Madrid, Fernando Fe, 1885) as transcribed on Wikisource, accents modernised: Gustavo Adolfo Bécquer ([المصدر](https://es.wikisource.org/wiki/El_monte_de_las_%C3%A1nimas)), ملكية عامة
- الصور: The front cover: a ruined chapel under the Moncayo on All Souls’ Night, in oils: Generated With Diffusion Models, أصلي
- الخطوط: Crimson Pro (OFL-1.1), Cormorant Garamond (OFL-1.1), Josefin Sans (OFL-1.1)
- الشيفرة: MIT · محتوى المثال: CC-BY-4.0

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

- [رقم 198 · مجلد من سلسلة، والسلسلة على أوراق بطانته](https://postext.dev/ar/cookbook/collection-volume-endpapers.md): المجلد الحادي عشر من سلسلة مجلدة في اثني عشر مجلدًا: رقما ردمك بجانب الشريط الرمزي، وغلاف مشترك بين المجلدات، والسلسلة كلها على أوراق البطانة. · المستوى 3 (متقدم) · الأدب القصصي والمسرح والنثر الأدبي
- [رقم 200 · مربّعات نص الغلاف مثبّتة ومتسلسلة](https://postext.dev/ar/cookbook/cover-text-boxes-anchored.md): قصتان لبو في كتاب ذي غلاف ورقي، غلافه منضّد في ستة مربّعات نص معلّق بعضها ببعض: عنوان يطول مربّعه مع النص، وملخّص يكمل في مربّع ثانٍ. · المستوى 3 (متقدم) · الأدب القصصي والمسرح والنثر الأدبي
- [رقم 194 · غلاف بنافذة تؤطّر صفحة العنوان](https://postext.dev/ar/cookbook/die-cut-window-cover.md): نافذة بيضاوية مقصوصة في الغلاف بـ dieCuts، مقيسة على لوحة صفحة العنوان كي تقع حافتها على الإطار المذهّب، وخط القص على لوح خاص. · المستوى 2 (متوسط) · الأدب القصصي والمسرح والنثر الأدبي
