# Caselle di testo di copertina ancorate e concatenate

> Due racconti di Poe in brossura, con la copertina in sei caselle di testo appese l’una all’altra, un titolo che cresce e una quarta che prosegue altrove.

- Versione HTML: https://postext.dev/it/cookbook/cover-text-boxes-anchored
- Ricetta Nº 200 · Output e integrazione · Livello 3 (Avanzato) · Output: Canvas, PDF
- Generi: Narrativa, teatro e prosa letteraria
- Richiede postext ≥ 1.93.0, postext-pdf ≥ 1.93.0 · provata con 1.93.0, postext-pdf 1.93.0 il 2026-11-23
- Pagine: [1](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p01.webp?v=84557ea3), [3](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p03.webp?v=84557ea3), [4](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p04.webp?v=84557ea3), [5](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p05.webp?v=84557ea3), [6](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p06.webp?v=84557ea3), [15](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p15.webp?v=84557ea3), [21](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p21.webp?v=84557ea3), [1](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p22.webp?v=84557ea3)
- PDF: https://postext.dev/cookbook/cover-text-boxes-anchored/en/cover-text-boxes-anchored.pdf?v=84557ea3
- Apri nella Sandbox: https://postext.dev/it/sandbox#recipe=cover-text-boxes-anchored&lang=en (.postext: https://postext.dev/cookbook/cover-text-boxes-anchored/en/cover-text-boxes-anchored.postext)
- Ultimo aggiornamento: 2026-11-23
- Altre lingue: [en](https://postext.dev/en/cookbook/cover-text-boxes-anchored.md), [es](https://postext.dev/es/cookbook/cover-text-boxes-anchored.md), [ca](https://postext.dev/ca/cookbook/cover-text-boxes-anchored.md), [de](https://postext.dev/de/cookbook/cover-text-boxes-anchored.md), [fr](https://postext.dev/fr/cookbook/cover-text-boxes-anchored.md), [pt](https://postext.dev/pt/cookbook/cover-text-boxes-anchored.md), [zh](https://postext.dev/zh/cookbook/cover-text-boxes-anchored.md), [ja](https://postext.dev/ja/cookbook/cover-text-boxes-anchored.md), [ar](https://postext.dev/ar/cookbook/cover-text-boxes-anchored.md)

## In breve

Un libretto con due racconti di Edgar Allan Poe e il foglio della sua copertina. Ogni testo della copertina sta sotto, sopra o accanto a un altro: un titolo più lungo fa scendere il resto, e il testo del retro prosegue sotto una citazione.

## Che cosa comporrai

Due racconti di Edgar Allan Poe, «The Masque of the Red Death» e «The Oval Portrait» (l’edizione spagnola compone la traduzione di Carlos Olivera del 1884), in una brossura di 125 × 195 mm, e il foglio della sua copertina. Nessun testo della copertina ha coordinate: ognuno è una casella appesa a qualcos’altro. In prima, il titolo pende dall’alto del pannello, il sottotitolo pende dal titolo e l’autore poggia sul piede. Il titolo occupa due righe in entrambe le edizioni, quindi la sua casella cresce e il sottotitolo scende con lei. In quarta, il testo riempie una casella di 50 mm e le righe che non ci stanno proseguono in una seconda casella, sotto una citazione del racconto. Sopra le pagine, la ricetta disegna il foglio due volte: come si stampa, e con ogni casella riquadrata e la catena segnata.

**Questa ricetta risponde a:**

- Come colloco i testi di una copertina l’uno rispetto all’altro, perché un titolo lungo spinga giù il resto?

## La risposta breve

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

## Ingredienti

**Insegna**

- [Caselle di testo di copertina](https://postext.dev/it/docs/print-covers.md#caselle-di-testo): cover.textBoxes aggiunge cornici di testo al foglio di copertina, ciascuna collocata dal suo rect o ancorata all’area di sicurezza di un pannello o a un’altra casella (sotto, sopra, accanto); next prosegue il testo in un’altra casella, maxHeight la lascia crescere con il testo e fit stabilisce quanto può ridursi il carattere.
- [Foglio di copertina](https://postext.dev/it/docs/print-covers.md#il-foglio-e-i-suoi-pannelli): buildCover compone il foglio di una versione a stampa: quarta, dorso e prima, con alette, o la copertina rigida, la sovraccoperta e i risguardi di un cartonato, con abbondanza e segni di piega. L’impostazione cover lo disegna e un documento Markdown del libro ne riempie i pannelli.

**Usa anche**

- [Cornici di testo concatenate](https://postext.dev/it/docs/composed-pages.md#concatenare-le-cornici)
- [Versioni a stampa, ISBN e dorso](https://postext.dev/it/docs/print-covers.md#versioni-di-un-libro)
- [Copertine, frontespizi e colophon](https://postext.dev/it/docs/configuration-styles.md#stili-dei-titoli)
- [Stili di titolo](https://postext.dev/it/docs/configuration-styles.md#stili-dei-titoli)
- [Aperture progettate](https://postext.dev/it/docs/configuration-headings.md#estensione-e-grafica-avanzata)
- [Testo, filetti e riquadri nei progetti di pagina](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina)
- [Metadati del documento](https://postext.dev/it/docs/document-format.md#front-matter)
- [Stili di paragrafo](https://postext.dev/it/docs/configuration-styles.md#stili-di-paragrafo)
- [Testatine e folio](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina)
- [Figure e tabelle come risorse](https://postext.dev/it/docs/document-format-resources.md#risorse)
- [Tavolozza di colori semantica](https://postext.dev/it/docs/configuration-fonts-colors-viewers.md#tavolozza-dei-colori)
- [Esportazione in PDF](https://postext.dev/it/docs/configuration-pdf-output.md#generare-pdf)
- [Pagine su un canvas](https://postext.dev/it/docs/configuration-programmatic-usage.md#rasterizzare-una-pagina)
- [Carta, rilegatura, scrivania e luce (Folio)](https://postext.dev/it/docs/configuration-fonts-colors-viewers.md#visualizzatore-folio-configurazione)
- [Attributi dei titoli](https://postext.dev/it/docs/document-format.md#attributi-dei-titoli)
- [Colore della carta](https://postext.dev/it/docs/configuration-page-layout.md#pagina)
- [Testatine secondo il ruolo della pagina](https://postext.dev/it/docs/configuration-headers-footers.md#elementi-di-testo)
- [Font incorporati nel PDF](https://postext.dev/it/docs/configuration-pdf-output.md#perché-un-provider-di-font)
- [Testatine per sezione](https://postext.dev/it/docs/configuration-styles.md#stili-dei-titoli)
- [Capitoli non numerati](https://postext.dev/it/docs/configuration-styles.md#stili-dei-titoli)

**La configurazione in breve**

- [`bodyText`](https://postext.dev/it/docs/configuration-text.md#testo-corrente), [`colorPalette`](https://postext.dev/it/docs/configuration-fonts-colors-viewers.md#tavolozza-dei-colori), [`cover`](https://postext.dev/it/docs/print-covers.md#la-grafica-della-copertina), [`folio`](https://postext.dev/it/docs/configuration-html-folio-epub.md#aspetto), [`footer`](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina), [`header`](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina), [`headingStyles`](https://postext.dev/it/docs/configuration-styles.md#stili-dei-titoli), [`headings`](https://postext.dev/it/docs/configuration-headings.md#titoli), [`layout`](https://postext.dev/it/docs/configuration-page-layout.md#impaginazione), [`locale`](https://postext.dev/it/docs/configuration-language.md#sillabazione), [`page`](https://postext.dev/it/docs/configuration-page-layout.md#pagina), [`paragraphStyles`](https://postext.dev/it/docs/configuration-styles.md#stili-di-paragrafo), [`production`](https://postext.dev/it/docs/print-covers.md#versioni-di-un-libro)

**API**

- [`buildCover`](https://postext.dev/it/docs/print-covers.md#dal-codice), [`buildDocumentWithFonts`](https://postext.dev/it/docs/configuration-programmatic-usage.md#caricare-i-font-prima-dellimpaginazione), [`decompressWoff2`](https://postext.dev/it/docs/configuration-pdf-output.md#provider-di-font-per-il-browser-fontsource--woff2), [`inlineSvgFonts`](https://postext.dev/it/docs/configuration-resources.md#font-nel-testo-svg), [`registerResourceImage`](https://postext.dev/it/docs/architecture.md#superficie-dellapi), [`renderPageToCanvas`](https://postext.dev/it/docs/configuration-programmatic-usage.md#rasterizzare-una-pagina), [`renderToPdf`](https://postext.dev/it/docs/configuration-pdf-output.md#generare-pdf)

**Caratteri**

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

## Preparazione

### 1 · Ogni casella pende da un pannello o da un’altra casella

Il codice è [la risposta breve](https://postext.dev/it/cookbook/cover-text-boxes-anchored.md#la-risposta-breve) qui sopra. Un `anchor` nomina una zona del foglio o un’altra casella di testo, e un punto. Su una zona il punto è uno dei nove della sua area di sicurezza, e la casella vi posa il proprio punto corrispondente: `edge: 'top'` centra il titolo in prima e appoggia il suo bordo superiore su quello dell’area di sicurezza; `edge: 'bottom'` appoggia il piede dell’autore sul piede della zona. Su una casella il punto può essere anche `below`, `above`, `right-of` o `left-of`. `x` e `y` spostano la casella da quel punto, in mm. Con un’ancora, `rect` dà solo la misura, così le caselle restano al loro posto quando il dorso si allarga o il libro cambia formato.

### 2 · Il titolo cresce e porta giù il sottotitolo

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

Il titolo è composto in Cinzel corpo 30 su 33. La sua casella è alta 14 mm, una riga. «The Masque of the Red Death» e «La máscara de la muerte» ne chiedono due, quindi la casella cresce con il testo fino ai 40 mm di `maxHeight`; solo oltre quell’altezza il corpo si ridurrebbe. Il sottotitolo è ancorato `below` al titolo, 2 mm sotto, e scende quanto la seconda riga. L’autore è ancorato al piede del pannello e non si muove.

### 3 · La quarta prosegue in un’altra casella

La casella del testo di quarta porta `next: 'blurb-end'`. Quello che non ci sta viene tagliato tra due righe e prosegue in quella casella, che non ha una cornice propria nel Markdown della copertina. La citazione pende dal testo e `blurb-end` dalla citazione, così le tre mantengono le distanze se la prima casella diventa più alta. Solo quando non basta nemmeno la seconda casella il testo della catena si riduce, tutto insieme, fino al 90 % per impostazione predefinita (`fit.minScale`). La riga in maiuscoletto dorato è l’ultimo paragrafo della cornice del testo, e perciò chiude il testo nella seconda casella:

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

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

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

La cornice `front` vuota impedisce a `buildCover` di mettere in prima il titolo, il sottotitolo e l’autore presi dai metadati del libro: qui li mettono le caselle.

### 4 · Una brossura con il dorso calcolato dalle pagine

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

Brossura fresata PUR in segnature da 16 pagine, su carta avoriata da 120 g/m² con mano 2,2. Il libro conta 21 pagine, 32 una volta legato, e il dorso misura circa 4,7 mm. Per impostazione predefinita un dorso sotto i 6 mm non riceve testo, quindi la versione imposta `spineText.minSpine` a 4,5 e il dorso porta titolo e autore. L’ISBN è un numero d’esempio, non assegnato ad alcun libro.

### 5 · Il corpo del libro

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

Occhiello, frontespizio e pagina dei crediti, poi ogni racconto in pagina dispari, abbassato di 50 mm, sotto il suo titolo in Cinzel e un breve filetto rosso. Le testatine portano l’autore in pagina pari e il titolo del racconto in pagina dispari, e il colophon chiude il libro sull’ultima dispari.

### 6 · Il foglio si costruisce dalle pagine già composte

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

`buildCover` prende le pagine, i metadati e il Markdown della copertina e restituisce un documento di una sola pagina, il foglio. Le caselle di testo diventano cornici di quella pagina e si compongono come quelle di una pagina composta. Le cifre del codice a barre chiedono l’OCR-B, che nessun server di font offre; la ricetta le compone in Cinzel.

### 7 · Dove è finita ogni casella

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

La pagina del foglio torna con le sue cornici in `page.composed.frames`, ciascuna con il rettangolo che l’impaginazione le ha dato dopo l’ancoraggio e la crescita, e `continuesTo` quando il suo testo prosegue in un’altra cornice. La seconda vista riquadra le sei caselle sul foglio e traccia la catena dal piede del testo di quarta fino al bordo superiore di `blurb-end`.

## La ricetta completa

Un unico file, composto a partire dalla cartella della ricetta con il testo di esempio e il kit comune del Ricettario già inclusi; costruisce la propria pagina. Per eseguirlo, mettilo in uno `<script type="module">` di una pagina vuota, oppure incollalo nel pannello JS di un nuovo pen di CodePen (come modulo). Importa postext da esm.sh: non c’è niente da installare né da compilare.

- Cartella della ricetta: https://github.com/drnachio/postext/tree/main/cookbook/cover-text-boxes-anchored

### script.js

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

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

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

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

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

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

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

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

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

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

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

# Rights {style="rights"}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

# The Oval Portrait {style="tale"}

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

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

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

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

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

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

# Colophon {style="colophon"}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

## Varianti

### Appendi l’autore sotto il sottotitolo

Così anche l’autore segue il titolo verso il basso, invece di restare al piede del pannello.

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

### Riduci un titolo lungo a una riga

Senza `maxHeight`, la casella del titolo resta di 14 mm e l’impaginazione riduce il titolo finché ci sta: qui su una riga, a circa due terzi del suo corpo.

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

## Errori frequenti

- La casella nominata dal `next` di un’altra riceve il testo che quella le passa. Non darle una cornice propria nel Markdown della copertina, e chiudi la cornice della prima casella con ciò che deve chiudere il testo, come la nota qui.
- Un’ancora che non nomina nulla, che nomina sé stessa o che chiude un anello viene segnalata, e la casella resta sul suo `rect`. Dai a ogni casella ancorata un `rect` di misura reale.
- `maxHeight` non vale per una casella ruotata (`rotate`), che conserva la misura del suo `rect`.

## Crediti

- Ricetta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Testo: The Masque of the Red Death and The Oval Portrait, from The Works of Edgar Allan Poe (Raven Edition, 1903), Project Gutenberg eBooks #2148 and #2147: Edgar Allan Poe ([fonte](https://www.gutenberg.org/ebooks/2148)), pubblico dominio
- Testo: La máscara de la muerte and El retrato oval, translated by Carlos Olivera, from Novelas y cuentos (Garnier Hermanos, Paris, 1884), as transcribed on Wikisource, spelling and punctuation modernised: Carlos Olivera ([fonte](https://es.wikisource.org/wiki/Novelas_y_cuentos_(Poe))), pubblico dominio
- Immagini: The cover painting: a masked ball in a file of coloured rooms under a Gothic vault, with an ebony clock and a figure in a grave-shroud, in oils: Generated With Diffusion Models, originale
- Caratteri: EB Garamond (OFL-1.1), Cinzel (OFL-1.1)
- Codice: MIT · Contenuto di esempio: CC-BY-4.0

## Ricette correlate

- [Nº 198 · Un volume di collana, la serie sui suoi risguardi](https://postext.dev/it/cookbook/collection-volume-endpapers.md): Il volume XI di una collana rilegata in dodici: due ISBN accanto al codice a barre, una copertina comune a tutti i volumi e la collana intera sui risguardi. · Livello 3 (Avanzato) · Narrativa, teatro e prosa letteraria
- [Nº 196 · Una brossura con alette, il dorso ricavato dalle pagine](https://postext.dev/it/cookbook/paperback-cover-with-flaps.md): Una brossura di 120 × 190 mm con alette di 60 mm: si compongono le pagine e buildCover ne ricava il foglio di copertina, con un dorso spesso quanto la carta. · Livello 3 (Avanzato) · Narrativa, teatro e prosa letteraria
- [Nº 197 · Coperta, sovraccoperta e risguardi di un cartonato](https://postext.dev/it/cookbook/hardcover-jacket-and-endpapers.md): Le pagine di una brossura rilegate in tela: un’altra versione con il suo ISBN, e buildCover fa la coperta, la sovraccoperta e i due risguardi. · Livello 3 (Avanzato) · Narrativa, teatro e prosa letteraria
