# 表紙のテキスト枠を固定してつなぐ

> ポーの短編2作の並製本。表紙は互いにぶら下がる6つのテキスト枠で組みます。題名に合わせて伸びる枠と、2つ目の枠へ続く紹介文。

- HTML版: https://postext.dev/ja/cookbook/cover-text-boxes-anchored
- レシピ No. 200 · 出力と組み込み · 難易度 3 (上級) · 出力: Canvas, PDF
- ジャンル: 小説・戯曲・文芸
- 必要なもの postext ≥ 1.93.0, postext-pdf ≥ 1.93.0 · テスト環境 1.93.0, postext-pdf 1.93.0 ／テスト日 2026-11-23
- ページ: [1](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p01.webp?v=84557ea3), [3](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p03.webp?v=84557ea3), [4](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p04.webp?v=84557ea3), [5](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p05.webp?v=84557ea3), [6](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p06.webp?v=84557ea3), [15](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p15.webp?v=84557ea3), [21](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p21.webp?v=84557ea3), [1](https://postext.dev/cookbook/cover-text-boxes-anchored/en/p22.webp?v=84557ea3)
- PDF: https://postext.dev/cookbook/cover-text-boxes-anchored/en/cover-text-boxes-anchored.pdf?v=84557ea3
- Sandboxで開く: https://postext.dev/ja/sandbox#recipe=cover-text-boxes-anchored&lang=en (.postext: https://postext.dev/cookbook/cover-text-boxes-anchored/en/cover-text-boxes-anchored.postext)
- 最終更新: 2026-11-23
- 他の言語: [en](https://postext.dev/en/cookbook/cover-text-boxes-anchored.md), [es](https://postext.dev/es/cookbook/cover-text-boxes-anchored.md), [ca](https://postext.dev/ca/cookbook/cover-text-boxes-anchored.md), [de](https://postext.dev/de/cookbook/cover-text-boxes-anchored.md), [fr](https://postext.dev/fr/cookbook/cover-text-boxes-anchored.md), [it](https://postext.dev/it/cookbook/cover-text-boxes-anchored.md), [pt](https://postext.dev/pt/cookbook/cover-text-boxes-anchored.md), [zh](https://postext.dev/zh/cookbook/cover-text-boxes-anchored.md), [ar](https://postext.dev/ar/cookbook/cover-text-boxes-anchored.md)

## かんたんな説明

エドガー・アラン・ポーの短編2作を収めた小さな本と、その表紙用紙です。表紙の文字はどれも別の文字の下、上、横に置くので、題名が長くなればほかの文字が下がり、裏表紙の文章は引用の下で続きます。

## できあがり

エドガー・アラン・ポーの短編「赤死病の仮面」と「楕円形の肖像」を、英語版は原文で、スペイン語版はカルロス・オリベラの1884年の訳で、125 × 195 mmの並製本にします。表紙用紙も作ります。表紙の文字には座標が一つもありません。どれも何かにぶら下がったテキスト枠です。表1では、書名がゾーンの上端から下がり、副題が書名から下がり、著者名は下端に立ちます。書名はどちらの版でも2行になるので、枠が伸び、副題も一緒に下がります。表4では、紹介文が高さ50 mmの枠を埋め、入りきらない行は短編からの引用の下にある2つ目の枠へ続きます。ページの上には用紙を2回描きます。刷り上がりのままと、各枠を囲んでつながりを示したものです。

**このレシピが答える問い:**

- 表紙の文字を互いの位置に合わせて置き、題名が長くなればほかを押し下げるには？

## 手短な答え

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

## 材料

**学べること**

- [表紙のテキスト枠](https://postext.dev/ja/docs/print-covers.md#テキスト枠): cover.textBoxesは表紙の用紙にテキスト枠を加えます。各枠はrectで置くか、ゾーンの安全領域や別の枠（下、上、横）に固定します。nextは収まらない文章を別の枠へ続け、maxHeightは文章に合わせて枠を伸ばし、fitは文字をどこまで縮めるかを決めます。
- [表紙の用紙](https://postext.dev/ja/docs/print-covers.md#用紙とその各部): buildCoverは印刷版の表紙用紙を組みます。表4、背、表1に袖を付け、上製なら表紙、カバー、見返しも、裁ち落としと折りトンボ付きで作ります。デザインはcover設定、各部の文字は本のMarkdown文書が受け持ちます。

**ほかに使うもの**

- [連結したテキスト枠](https://postext.dev/ja/docs/composed-pages.md#枠をつなぐ)
- [印刷版、ISBN、背幅](https://postext.dev/ja/docs/print-covers.md#本の版)
- [表紙、扉、奥付](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [見出しスタイル](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [デザインした章扉](https://postext.dev/ja/docs/configuration-headings.md#幅と詳細デザイン)
- [ページデザインのテキスト・罫・ボックス](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル)
- [文書のメタデータ](https://postext.dev/ja/docs/document-format.md#フロントマター)
- [段落スタイル](https://postext.dev/ja/docs/configuration-styles.md#段落スタイル)
- [柱とノンブル](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル)
- [リソースとしての図と表](https://postext.dev/ja/docs/document-format-resources.md#リソース)
- [セマンティックカラーパレット](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット)
- [PDFの書き出し](https://postext.dev/ja/docs/configuration-pdf-output.md#pdfの生成)
- [キャンバス上のページ](https://postext.dev/ja/docs/configuration-programmatic-usage.md#ページをビットマップに描画する)
- [用紙、綴じ、机、照明（Folio）](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#folioビューアー設定)
- [見出しの属性](https://postext.dev/ja/docs/document-format.md#見出しの属性)
- [用紙の色](https://postext.dev/ja/docs/configuration-page-layout.md#ページ)
- [ページの役割ごとの柱](https://postext.dev/ja/docs/configuration-headers-footers.md#テキスト要素)
- [PDFに埋め込むフォント](https://postext.dev/ja/docs/configuration-pdf-output.md#なぜフォントプロバイダーが必要か)
- [節ごとの柱](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [番号のない章](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)

**設定の一覧**

- [`bodyText`](https://postext.dev/ja/docs/configuration-text.md#本文), [`colorPalette`](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット), [`cover`](https://postext.dev/ja/docs/print-covers.md#表紙のデザイン), [`folio`](https://postext.dev/ja/docs/configuration-html-folio-epub.md#外観), [`footer`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`header`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`headingStyles`](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル), [`headings`](https://postext.dev/ja/docs/configuration-headings.md#見出し), [`layout`](https://postext.dev/ja/docs/configuration-page-layout.md#レイアウト), [`locale`](https://postext.dev/ja/docs/configuration-language.md#ハイフネーション), [`page`](https://postext.dev/ja/docs/configuration-page-layout.md#ページ), [`paragraphStyles`](https://postext.dev/ja/docs/configuration-styles.md#段落スタイル), [`production`](https://postext.dev/ja/docs/print-covers.md#本の版)

**API**

- [`buildCover`](https://postext.dev/ja/docs/print-covers.md#コードから), [`buildDocumentWithFonts`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#レイアウトの前にフォントを読み込む), [`decompressWoff2`](https://postext.dev/ja/docs/configuration-pdf-output.md#ブラウザー向けフォントプロバイダーfontsource--woff2), [`inlineSvgFonts`](https://postext.dev/ja/docs/configuration-resources.md#svgの文字のフォント), [`registerResourceImage`](https://postext.dev/ja/docs/architecture.md#apiの概要), [`renderPageToCanvas`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#ページをビットマップに描画する), [`renderToPdf`](https://postext.dev/ja/docs/configuration-pdf-output.md#pdfの生成)

**書体**

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

## 作り方

### 1 · どの枠もゾーンか別の枠にぶら下がる

コードは上の[手短な答え](https://postext.dev/ja/cookbook/cover-text-boxes-anchored.md#手短な答え)です。`anchor`は用紙のゾーンか別のテキスト枠を指し、点を一つ選びます。ゾーンなら、その点は安全領域の9つの点のどれかで、枠は自分の同じ点をそこに合わせます。`edge: 'top'`は書名を表1の中央に置き、上端を安全領域の上端にそろえます。`edge: 'bottom'`は著者名の枠の下端をゾーンの下端にそろえます。枠に対しては`below`、`above`、`right-of`、`left-of`も使えます。`x`と`y`はその点からの移動量で、単位はmmです。固定すると`rect`は大きさだけを表すので、背が厚くなっても判型が変わっても、枠は同じ位置関係を保ちます。

### 2 · 書名が伸びて副題を押し下げる

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

書名はCinzelの30ポイント、行送り33ポイントです。枠の高さは14 mmで1行分。「The Masque of the Red Death」も「La máscara de la muerte」も2行になるので、枠は文字に合わせて`maxHeight`の40 mmまで伸びます。文字が縮むのはその高さを超えてからです。副題は書名の`below`、2 mm下に固定されているので、2行目の分だけ下がります。著者名はゾーンの下端に固定されているので動きません。

### 3 · 紹介文は別の枠へ続く

紹介文の枠には`next: 'blurb-end'`があります。入りきらない分は行の間で切れてその枠に続き、その枠は表紙のMarkdownに自分のframeを持ちません。引用は紹介文から、`blurb-end`は引用からぶら下がるので、最初の枠を高くしても3つの間隔は変わりません。2つ目の枠でも足りないときに初めて、つながった文章全体が一緒に縮みます。既定では90 %まで（`fit.minScale`）。金のスモールキャピタルの1行は紹介文のframeの最後の段落なので、2つ目の枠で文章を締めくくります。

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

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

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

空の`front` frameがあると、`buildCover`は本のメタデータから書名、副題、著者名を表1に組みません。ここではテキスト枠がそれを組みます。

### 4 · ページ数から背幅を出す並製本

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

PUR無線綴じ、16ページ折、120 g/m²、嵩高2.2の書籍用紙。本は21ページで、綴じると32ページになり、背幅は約4.7 mmです。既定では6 mm未満の背には文字を入れないので、このバージョンは`spineText.minSpine`を4.5にし、背に書名と著者名を入れます。ISBNは見本の番号で、どの本にも割り当てられていません。

### 5 · 本文

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

小扉、扉、権利表記のページ。続いて各短編が奇数ページから50 mm下げて始まり、上にCinzelの題とごく短い赤い罫が入ります。柱は偶数ページに著者名、奇数ページに短編の題。奥付が最後の奇数ページで本を閉じます。

### 6 · 組んだページから用紙を作る

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

`buildCover`はページ、メタデータ、表紙のMarkdownを受け取り、1ページだけの文書を返します。そのページが用紙です。テキスト枠はそのページのframeになり、組版ページのframeと同じように組まれます。バーコードの数字はOCR-Bを求めますが、どのフォントサーバーにもないので、Cinzelで組みます。

### 7 · 各枠の行き先

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

用紙のページは`page.composed.frames`にframeを持ちます。それぞれ固定と伸びのあとの矩形を持ち、文章が別のframeへ続くときは`continuesTo`もあります。2つ目の図は用紙の上で6つの枠を囲み、紹介文の枠の下端から`blurb-end`の上端までつながりを描きます。

## レシピの全体

レシピのフォルダーから合成した1つのファイルで、サンプルのテキストとレシピ集の共通キットを埋め込んであり、自分でページを組み立てます。動かすには、空のページの`<script type="module">`に入れるか、新しいCodePenのpenのJSパネルに貼り付けます（モジュールとして）。esm.shからpostextを読み込むので、インストールもビルドも要りません。

- レシピのフォルダー: https://github.com/drnachio/postext/tree/main/cookbook/cover-text-boxes-anchored

### script.js

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

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

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

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

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

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

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

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

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

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

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

# Rights {style="rights"}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

# The Oval Portrait {style="tale"}

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

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

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

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

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

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

# Colophon {style="colophon"}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

## アレンジ

### 著者名を副題の下に下げる

著者名もゾーンの下端にとどまらず、書名と一緒に下がります。

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

### 長い書名を1行に縮める

`maxHeight`がなければ書名の枠は14 mmのままで、収まるまで書名を縮めます。ここでは1行になり、元の大きさのおよそ3分の2です。

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

## よくあるつまずき

- 別の枠の`next`が指す枠は、その枠から渡された文章を受け取ります。表紙のMarkdownで自分のframeを与えず、文章を締めくくる内容は最初の枠のframeの最後に書きます。ここの注記の1行と同じです。
- 存在しない名前、自分自身、または輪になる相手を指すanchorは報告され、枠は`rect`の位置に置かれます。固定する枠にも、実際の大きさの`rect`を与えてください。
- `maxHeight`は回転した枠（`rotate`）には効かず、回転した枠は`rect`の大きさのままです。

## クレジット

- レシピ: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- テキスト: The Masque of the Red Death and The Oval Portrait, from The Works of Edgar Allan Poe (Raven Edition, 1903), Project Gutenberg eBooks #2148 and #2147: Edgar Allan Poe ([出典](https://www.gutenberg.org/ebooks/2148)), パブリックドメイン
- テキスト: La máscara de la muerte and El retrato oval, translated by Carlos Olivera, from Novelas y cuentos (Garnier Hermanos, Paris, 1884), as transcribed on Wikisource, spelling and punctuation modernised: Carlos Olivera ([出典](https://es.wikisource.org/wiki/Novelas_y_cuentos_(Poe))), パブリックドメイン
- 画像: The cover painting: a masked ball in a file of coloured rooms under a Gothic vault, with an ebony clock and a figure in a grave-shroud, in oils: Generated With Diffusion Models, オリジナル
- 書体: EB Garamond (OFL-1.1), Cinzel (OFL-1.1)
- コード: MIT · サンプルの内容: CC-BY-4.0

## 関連レシピ

- [No. 198 · 叢書の一冊、見返しにシリーズの全点を](https://postext.dev/ja/cookbook/collection-volume-endpapers.md): 全12巻の上製叢書の第11巻。バーコードの横に2つのISBN、全巻共通の表紙デザイン、そして見返しにはシリーズ全点を並べる。 · 難易度 3 (上級) · 小説・戯曲・文芸
- [No. 196 · 袖付き並製本の表紙、背幅はページから](https://postext.dev/ja/cookbook/paperback-cover-with-flaps.md): 120 × 190 mm、袖60 mmの並製本。先に本文を組み、buildCoverがそのページから表紙用紙を作ります。背幅は紙の厚みどおりになります。 · 難易度 3 (上級) · 小説・戯曲・文芸
- [No. 197 · 上製本の表紙、カバーと見返し](https://postext.dev/ja/cookbook/hardcover-jacket-and-endpapers.md): 並製本のページをクロス装の上製本に仕立て直します。ISBNの違う版を一つ足し、buildCoverで表紙、カバー、前後の見返しを作ります。 · 難易度 3 (上級) · 小説・戯曲・文芸
