# Роман в мягкой обложке: спуск и главы с правой полосы

> The Awakening в мягкой обложке 140 × 216 мм: живописная обложка и оборот без колонтитулов, главы с правой полосы со спуском под курсивной цифрой.

- Версия HTML: https://postext.dev/ru/cookbook/trade-paperback-novel
- Рецепт № 038 · Полные издания · Уровень 2 (Средний) · Форматы вывода: Canvas
- Жанры: Художественная литература, драматургия и эссеистика
- Требуется postext ≥ 1.25.0 · проверено с 1.65.0 · дата 2026-10-31
- Страницы: [1](https://postext.dev/cookbook/trade-paperback-novel/en/p01.webp?v=610215ef), [2](https://postext.dev/cookbook/trade-paperback-novel/en/p02.webp?v=610215ef), [3](https://postext.dev/cookbook/trade-paperback-novel/en/p03.webp?v=610215ef), [4](https://postext.dev/cookbook/trade-paperback-novel/en/p04.webp?v=610215ef), [5](https://postext.dev/cookbook/trade-paperback-novel/en/p05.webp?v=610215ef), [6](https://postext.dev/cookbook/trade-paperback-novel/en/p06.webp?v=610215ef), [7](https://postext.dev/cookbook/trade-paperback-novel/en/p07.webp?v=610215ef), [8](https://postext.dev/cookbook/trade-paperback-novel/en/p08.webp?v=610215ef)
- Открыть в Sandbox: https://postext.dev/ru/sandbox#recipe=trade-paperback-novel&lang=en (.postext: https://postext.dev/cookbook/trade-paperback-novel/en/trade-paperback-novel.postext)
- Последнее обновление: 2026-10-10
- Другие языки: [en](https://postext.dev/en/cookbook/trade-paperback-novel.md), [es](https://postext.dev/es/cookbook/trade-paperback-novel.md), [ca](https://postext.dev/ca/cookbook/trade-paperback-novel.md), [de](https://postext.dev/de/cookbook/trade-paperback-novel.md), [el](https://postext.dev/el/cookbook/trade-paperback-novel.md), [fr](https://postext.dev/fr/cookbook/trade-paperback-novel.md), [it](https://postext.dev/it/cookbook/trade-paperback-novel.md), [pt](https://postext.dev/pt/cookbook/trade-paperback-novel.md), [zh](https://postext.dev/zh/cookbook/trade-paperback-novel.md), [ja](https://postext.dev/ja/cookbook/trade-paperback-novel.md), [ar](https://postext.dev/ar/cookbook/trade-paperback-novel.md)

## Коротко

Первые две главы американского романа в виде книги в мягкой обложке. Каждая глава начинается на правой странице, ниже обычного, под крупным номером.

## Что получится

Восемь страниц книги в мягкой обложке 140 × 216 мм вмещают первые две главы романа Кейт Шопен *The Awakening* (1899). Обложка, картина, созданная диффузионными моделями и загруженная как JPEG, показывает залив от домиков Лебрёнов на Гранд-Айле: люгер на горизонте между дубами и белый зонтик, поднимающийся среди ромашек. Выходные сведения стоят внизу оборота обложки. Каждая глава открывается на правой полосе, текст начинается на 81 мм ниже верха под курсивной цифрой 48 пт, ржаво-красной линейкой 18 мм и первой фразой главы капителью, разбитой по смыслу на две строки по центру. Глава I кончается на странице 5 концовкой с ромашкой, поэтому страница 6 остаётся пустой, без колонтитула и колонцифры, а глава II открывается на странице 7. На левых полосах в колонтитуле стоит автор, на правых заглавие курсивом.

**Рецепт отвечает на вопросы:**

- Как начинать каждую главу на правой полосе со спуском на треть страницы, как в книге в мягкой обложке?
- Как добавить на начальную полосу строку с автором, вводку или лид с буквицей?
- Как намеренно вставить пустые страницы или начать раздел с нового разворота?
- Как задать колонтитулы: название книги слева, название главы справа, номер страницы снаружи?
- Как сделать обложку, авантитул, титул и выходные сведения?
- Как добавить вертикальный отступ между двумя блоками, если пустые строки не действуют?
- Как поставить рисунки без номера: орнаменты, виньетки, логотипы?

## Короткий ответ

```js
// script.js, строк 47–77
// # I {lead="A green and yellow parrot, … kept repeating over and over:"}
// The heading's text is the numeral, printed by {titleText}; the chapter's first sentence
// travels as the heading's lead attribute, printed by {attr.lead} in small capitals: a
// centred display, which a \n in the attribute breaks by sense.
const [LEAD_AT, BODY_AT] = [9, 12]; // grid lines: the lead's top; where the text starts
const NUMERAL = 48; // pt
const RULE_Y = (LEAD_AT - 1.5) * LEAD * MM_PER_PT; // mm: a line and a half above the lead
const NUMERAL_Y = RULE_Y - NUMERAL * MM_PER_PT - 3; // mm: the numeral's box ends 3 mm above it
const centred = (y) => ({ anchor: { to: 'container', edge: 'top' }, offset: { y } });
const opener = {
  enabled: true,
  // The two-line lead ends on line LEAD_AT + 2; minHeight leaves a blank line under it and
  // starts the text on line BODY_AT (a one-line lead would leave two).
  minHeight: line(BODY_AT),
  slot: { elements: [
    { kind: 'text', id: 'numeral', content: '{titleText}', fontFamily: DISPLAY, italic: true,
      fontWeight: 500, fontSize: pt(NUMERAL), lineHeight: 1, color: col('ink'),
      align: 'center', placement: centred(mm(NUMERAL_Y)) },
    { kind: 'rule', id: 'hairline', direction: 'horizontal', thickness: pt(0.6),
      color: col('rubric'), placement: { ...centred(mm(RULE_Y)), size: { width: mm(18) } } },
    { kind: 'text', id: 'lead', content: '{attr.lead}', fontFamily: LABEL, fontWeight: 600,
      fontSize: pt(9.5), letterSpacing: pt(0.6), color: col('ink'), align: 'center',
      lineHeight: LEAD / 9.5, // one grid line to each line of the lead
      placement: { ...centred(line(LEAD_AT)), size: { width: mm(MEASURE) } } },
  ] },
};
// Every chapter opens on a recto: 'odd' adds a blank verso only after a chapter that ends on
// a recto, where the default 'always-odd' leaves a blank page after every chapter.
// marginBottom 0: the level's default 0.5 em would start the text a line lower.
const chapter = { level: 1, breakBefore: { enabled: true, parity: 'odd' },
  marginBottom: pt(0), italic: true, advancedDesign: opener };
```

## Ингредиенты

**Чему учит**

- [Оформленные начальные полосы](https://postext.dev/ru/docs/configuration-headings.md#ширина-и-расширенный-дизайн): Заголовок, нарисованный как свободная композиция из текста, линеек, рамок и иллюстраций; он резервирует нужную высоту над текстом.
- [Главы с правой полосы](https://postext.dev/ru/docs/configuration-headings.md#разрыв-перед-заголовком): Уровень заголовка начинает новую страницу: следующую, ближайшую правую или ближайшую левую, с пустой страницей, если она нужна.
- [Колонтитулы разделов](https://postext.dev/ru/docs/configuration-styles.md#стили-заголовков): У стиля заголовка могут быть свои колонтитулы, поэтому вводная часть, разделы или буквы словаря получают собственное оформление.

**Также используются**

- [Зеркальные поля](https://postext.dev/ru/docs/configuration-page-layout.md#зеркальные-поля)
- [Стили заголовков](https://postext.dev/ru/docs/configuration-styles.md#стили-заголовков)
- [Обложки, титулы и колофоны](https://postext.dev/ru/docs/configuration-styles.md#стили-заголовков)
- [Атрибуты заголовков](https://postext.dev/ru/docs/document-format.md#атрибуты-заголовка)
- [Текст, линейки и рамки в дизайне страницы](https://postext.dev/ru/docs/configuration-headers-footers.md#верхние-и-нижние-колонтитулы)
- [Иллюстрации в дизайне страницы](https://postext.dev/ru/docs/configuration-headers-footers.md#изображения)
- [Геометрия раздела](https://postext.dev/ru/docs/configuration-styles.md#стили-заголовков)
- [Колонтитулы по роли страницы](https://postext.dev/ru/docs/configuration-headers-footers.md#текстовые-элементы)
- [Колонтитулы и колонцифры](https://postext.dev/ru/docs/configuration-headers-footers.md#верхние-и-нижние-колонтитулы)
- [Метаданные документа](https://postext.dev/ru/docs/document-format.md#метаданные-frontmatter)
- [Стили абзацев](https://postext.dev/ru/docs/configuration-styles.md#стили-абзацев)
- [Явный вертикальный отступ](https://postext.dev/ru/docs/document-format-directives.md#space)
- [Рисунки и таблицы как ресурсы](https://postext.dev/ru/docs/document-format-resources.md#ресурсы)
- [Собственные типы ресурсов](https://postext.dev/ru/docs/configuration-resources.md#типы-ресурсов)
- [Рисунки точно здесь](https://postext.dev/ru/docs/document-format-resources.md#блочная-вставка-необязательная-с-явным-местом-в-тексте)
- [Цвет бумаги](https://postext.dev/ru/docs/configuration-page-layout.md#страница)
- [Висячие и короткие концевые строки](https://postext.dev/ru/docs/configuration-page-flow.md#висячие-строки-короткие-концевые-строки-и-правила-неразрывности)

**Конфигурация вкратце**

- [`bodyText`](https://postext.dev/ru/docs/configuration-text.md#основной-текст), [`colorPalette`](https://postext.dev/ru/docs/configuration-fonts-colors-viewers.md#палитра-цветов), [`footer`](https://postext.dev/ru/docs/configuration-headers-footers.md#верхние-и-нижние-колонтитулы), [`header`](https://postext.dev/ru/docs/configuration-headers-footers.md#верхние-и-нижние-колонтитулы), [`headingStyles`](https://postext.dev/ru/docs/configuration-styles.md#стили-заголовков), [`headings`](https://postext.dev/ru/docs/configuration-headings.md#заголовки), [`layout`](https://postext.dev/ru/docs/configuration-page-layout.md#колонки), [`locale`](https://postext.dev/ru/docs/configuration-language.md#перенос-слов), [`page`](https://postext.dev/ru/docs/configuration-page-layout.md#страница), [`paragraphStyles`](https://postext.dev/ru/docs/configuration-styles.md#стили-абзацев), [`resourceTypes`](https://postext.dev/ru/docs/configuration-resources.md#типы-ресурсов)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/ru/docs/configuration-programmatic-usage.md#загрузка-шрифтов-перед-вёрсткой), [`registerResourceImage`](https://postext.dev/ru/docs/architecture.md#состав-api), [`renderPageToCanvas`](https://postext.dev/ru/docs/configuration-programmatic-usage.md#рендеринг-страницы-в-растр)

**Гарнитуры**

- Crimson Pro (OFL-1.1), Cormorant Garamond (OFL-1.1), Cormorant SC (OFL-1.1)

## Порядок работы

### 1 · Начальная полоса из заголовка и его атрибута

Код приведён выше, в разделе [«Короткий ответ»](https://postext.dev/ru/cookbook/trade-paperback-novel.md#короткий-ответ). У глав Шопен нет названий, поэтому каждый заголовок содержит только номер (`# I`), который печатает `{titleText}`. `{attr.lead}` печатает атрибут `lead` заголовка, где лежит первая фраза главы; абзац Markdown под заголовком начинается со следующей фразы ([атрибуты заголовков](https://postext.dev/ru/docs/document-format.md#атрибуты-заголовка)). Вступительная фраза выключена по центру, и `\n` в каждом атрибуте разбивает её по смыслу, после *cage* и после *bright;*. Её рамка начинается на девять линий сетки ниже верха полосы набора, а `minHeight` в 12 строк оставляет под ней одну пустую; без `minHeight` текст начинается сразу под фразой ([охват и расширенное оформление](https://postext.dev/ru/docs/configuration-headings.md#ширина-и-расширенный-дизайн)). `marginBottom: pt(0)` заменяет отступ уровня по умолчанию, пол-em, который сдвинул бы текст на строку ниже.

`breakBefore` с чётностью `'odd'` отправляет каждую главу на правую полосу, и пустая левая появляется только после главы, которая кончилась на правой ([разрыв перед заголовком](https://postext.dev/ru/docs/configuration-headings.md#разрыв-перед-заголовком)). Чтобы попасть на правую полосу там, где заголовка нет, напишите в Markdown `:::pagebreak{parity="odd"}`; в вёрстке из двух и более колонок `:::columnbreak` переносит текст в следующую колонку ([`:::pagebreak`](https://postext.dev/ru/docs/document-format-directives.md#pagebreak)).

### 2 · Страница книги из целых строк

```js
// script.js, строк 33–43
const TRIM = { width: 140, height: 216 }; // mm: 5½ × 8½ in
const [TOP, INNER, OUTER] = [22, 20, 15.5]; // mm; mirrored, so INNER is left on a recto
const LINES = 35; // every full page ends on the same line
const MEASURE = TRIM.width - INNER - OUTER; // 104.5 mm: about 69 characters of Crimson Pro
const MM_PER_PT = 25.4 / 72;
const page = {
  sizePreset: 'custom', width: mm(TRIM.width), height: mm(TRIM.height), dpi: 150,
  backgroundColor: col('paper'),
  margins: { top: mm(TOP), bottom: mm(TRIM.height - TOP - LINES * LEAD * MM_PER_PT),
    left: mm(INNER), right: mm(OUTER), mirror: true },
};
```

Нижнее поле — то, что остаётся от обреза 216 мм после верхнего поля и 35 строк по 14 пт, поэтому каждая полная страница кончается на одной линии, как страницы 3 и 4. При `mirror: true` внутреннее поле 20 мм ложится к корешку и на правых, и на левых полосах ([зеркальные поля](https://postext.dev/ru/docs/configuration-page-layout.md#зеркальные-поля)). Строка шириной 104,5 мм вмещает около 69 знаков Crimson Pro кегля 10,5 пт. Межсловные пробелы основного текста держатся между 0,7 и 1,9 обычного; при минимуме по умолчанию, 0,6, одна строка на этих страницах сжимается до 0,62.

### 3 · Колонтитулы, которые пропускают начальные и пустые страницы

```js
// script.js, строк 81–101
// {author} and {title} come from the frontmatter.
const HEAD_Y = 12; // mm from the top edge to the top of the running heads
const SHIFT = (INNER - OUTER) / 2; // mm: the text block's centre is off the page's centre
const head = (id, content, parity, edge, x, style) => ({
  kind: 'text', id, content, parity, pages: 'body', // never on openers or blank pages
  fontSize: pt(9), color: col('muted'), ...style,
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(HEAD_Y) } },
});
const smallCaps = { fontFamily: LABEL, fontWeight: 600, letterSpacing: pt(1.2) };
const italic = { fontFamily: DISPLAY, italic: true, fontWeight: 500, fontSize: pt(9.75) };
const folio = { fontFamily: TEXT, color: col('ink') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-author', '{author}', 'even', 'top', -SHIFT, smallCaps),
  head('recto-title', '{title}', 'odd', 'top', SHIFT, italic),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };
// Openers carry a drop folio instead, centred under the text block.
const footer = { elements: [{ kind: 'text', id: 'drop-folio', content: '{pageNumber}',
  pages: 'opener', fontFamily: TEXT, fontSize: pt(9), color: col('muted'), align: 'center',
  placement: { anchor: { to: 'container', edge: 'top' }, offset: { y: mm(7) } } }] };
```

`parity: 'even'` ставит автора капителью Cormorant SC на левые полосы, `'odd'` — заглавие курсивом на правые; колонцифры стоят у внешнего края полосы набора. `pages: 'body'` убирает все четыре элемента с начальных полос и со страницы 6, пустой левой полосы, которую добавляет разрыв по чётности. С `pages: 'all'` на этой странице печатались бы *6* и *Kate Chopin*. Начальные полосы получают вместо этого колонцифру внизу, элемент нижнего колонтитула, который `pages: 'opener'` ограничивает ими ([текстовые элементы](https://postext.dev/ru/docs/configuration-headers-footers.md#текстовые-элементы)).

### 4 · Обложка — раздел без колонтитулов

```js
// script.js, строк 105–128
// Page 1 is a recto (gotcha: parity-page1-recto): the cover, the colophon on its verso, and
// chapter I on page 3. # The Awakening {style="cover"} opens the section; chapter I closes it.
// The colophon: 2 + 2 + 1 lines of 11 pt and two gaps of 14.5 pt make 84 pt, six grid lines.
const COLOPHON_LINES = 6;
const COLOPHON_TOP = TOP + (LINES - COLOPHON_LINES) * LEAD * MM_PER_PT; // mm: the section's margin
const onPage = (y) => ({ anchor: { to: 'page', edge: 'top' }, offset: { y: mm(y) } }); // y mm down
const cover = {
  id: 'cover',
  header: { elements: [] }, footer: { elements: [] }, // no running heads on p. 1 or p. 2
  margins: { top: mm(COLOPHON_TOP) },
  advancedDesign: { enabled: true, slot: { elements: [
    { kind: 'image', id: 'art', resourceId: 'cover',
      placement: { anchor: { to: 'bleed', edge: 'top-left' }, size: { width: 'fill' } } },
    { kind: 'text', id: 'title', content: '{title}', fontFamily: DISPLAY, italic: true,
      fontWeight: 500, fontSize: pt(50), lineHeight: 1, color: col('ink'), align: 'center',
      placement: onPage(155) },
    { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(0.6),
      color: col('rubric'), placement: { ...onPage(179), size: { width: mm(18) } } },
    { kind: 'text', id: 'author', content: '{author}', ...smallCaps, fontSize: pt(12),
      letterSpacing: pt(2.4), color: col('rubric'), align: 'center', placement: onPage(184) },
  ] } },
};
const colophon = { id: 'colophon', fontSize: pt(8), lineHeight: pt(11), color: col('muted'),
  textAlign: 'left', firstLineIndent: pt(0), spaceBetween: pt(14.5) };
```

Обложка — заголовок `# The Awakening {style="cover"}`. Его стиль ставит картину на верхние 134 мм, заглавие из метаданных кеглем 50 пт и автора капителью. Стиль действует и на раздел, который открывает заголовок, то есть на страницы 1 и 2, до главы I. Пустые `header` и `footer` не пускают колонцифру на обложку и колонтитулы на страницу с выходными сведениями. Верхнее поле ставит выходные сведения на последние шесть линий сетки полосы набора, и их последняя строка стоит вровень с последней строкой страницы 3 ([стили заголовков](https://postext.dev/ru/docs/configuration-styles.md#стили-заголовков)). Колонка раздела начинается на отметке 165 мм, а оформление, привязанное к странице и вылету, рисуется и над ней: оформление в колонке обрезает только её нижний край.

![Page 2.](https://postext.dev/cookbook/trade-paperback-novel/en/p02.webp?v=610215ef)

*Страница 2: выходные сведения внизу оборота обложки, без колонтитула и колонцифры.*

### 5 · Концовка закрывает каждую главу

```js
// script.js, строк 132–164
// At a chapter's end: :::space, then ::resource{id="tailpiece-1"} (double quotes: gotcha
// resource-double-quotes). The space adds a line to the gap the embed keeps above it.
const ornament = { id: 'ornament', name: 'Ornament', shortLabel: '', captionPrefix: '',
  numberingTemplate: '{n}', resetOn: 'never', counterFormat: 'decimal',
  defaultPlacement: { position: 'here', width: 0.17, align: 'center' } };
const svg = (id, fileId, width, height, altText) => ({ id, typeId: 'ornament', kind: 'svg',
  svg: { fileId, width, height }, altText, createdAt: 0, updatedAt: 0 });
// The cover is a painting, a JPEG in assets/ cut to the art's 140 × 134 mm, declared at its pixels;
// the it edition's is a detail of Signorini's Settignano.
const painting = { id: 'cover', typeId: 'ornament', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: t({ en: 'cover-1190.jpg', it: 'cover-it-1190.jpg' }), format: 'jpeg',
    width: 1190, height: 1139 },
  altText: t({ en: 'The gulf seen between the trunks of water-oaks, a lugger on the horizon; a '
    + 'white sunshade comes up from the beach through the camomile.',
  pt: 'O mar visto entre os troncos de duas árvores, um veleiro no horizonte; uma sombrinha '
    + 'branca sobe da praia por um caminho entre flores amarelas e brancas.',
  fr: 'La mer vue entre les troncs de deux arbres, un voilier à l’horizon ; une ombrelle '
    + 'blanche monte de la plage par un chemin entre des fleurs jaunes et blanches.',
  de: 'Das Meer zwischen den Stämmen zweier Bäume, ein Segelboot am Horizont; ein weißer '
    + 'Sonnenschirm kommt vom Strand einen Weg zwischen gelben und weißen Blumen herauf.',
  it: 'Una strada di Settignano: la bottega del pane e del vino, una donna seduta sulla '
    + 'soglia, un gatto sul selciato al sole.' }) };
const resources = [
  painting,
  // ::resource places each ornament once, so each chapter end has its own id.
  ...t({ en: ['I', 'II'], pt: ['I', 'II', 'III'], fr: ['I', 'II'], de: ['I', 'II'], it: ['I', 'II'] })
    .map((n, i) => svg(`tailpiece-${i + 1}`, 'fleuron.svg', 40, 12,
      t({ en: `A camomile flower between two sprigs closes chapter ${n}.`,
        pt: `Uma flor de camomila entre dois ramos fecha o capítulo ${n}.`,
        fr: `Une fleur de camomille entre deux brins clôt le chapitre ${n}.`,
        de: `Eine Kamillenblüte zwischen zwei Zweigen schließt das Kapitel ${n}.`,
        it: `Un fiore di camomilla tra due rametti chiude il capitolo ${n}.` }))),
];
```

У типа орнамента нет префикса подписи, поэтому ромашка печатается без подписи, шириной 17 % строки, там, где стоит `::resource{id="tailpiece-1"}` ([типы ресурсов](https://postext.dev/ru/docs/configuration-resources.md#типы-ресурсов)). Встроенный в поток ресурс оставляет над собой одну линию сетки, а `:::space` перед ним добавляет вторую между последней строкой главы и цветком ([`:::space`](https://postext.dev/ru/docs/document-format-directives.md#space)). Обе концовки рисуют один файл, `fleuron.svg`, под двумя id, потому что ресурс ставится только один раз.

## Рецепт целиком

Один файл, собранный из папки рецепта; образец текста и общий набор функций рецептов встроены в него; он сам строит свою страницу. Чтобы запустить его, поместите его в `<script type="module">` на пустой странице или вставьте в панель JS нового пена CodePen (как модуль). Он импортирует postext с esm.sh, поэтому ничего не нужно устанавливать и собирать.

- Папка с исходными файлами: https://github.com/drnachio/postext/tree/main/cookbook/trade-paperback-novel

### script.js

```js
// ═══ Postext Cookbook · Nº 038 · Trade paperback: sunk openers and recto chapters ═══
// https://postext.dev/en/cookbook/trade-paperback-novel
// Code: MIT · Text: Chopin, Machado, Goncourt, Collodi, Keyserling (PD) · Covers: diffusion models, Signorini
// Fonts: Crimson Pro, Cormorant Garamond, Cormorant SC (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: 'en' Chopin|'pt' Machado|'fr' Goncourt|'de' Keyserling|'it' Collodi
const RECIPE = 'trade-paperback-novel';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { // every colour in the config links to one of these
  ink: '#231d18', // the text: a warm near-black
  rubric: '#8e3b22', // the one accent: the opener's hairline, the author, the tailpiece
  muted: '#6e655b', // running heads, folios on openers, the colophon
  paper: '#fbf7ef', // a cream book paper
};
// Each colour names its palette entry and carries its hex.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  // The engine's defaults (headings, lists, callouts, captions) link to 'main-color', the rubric.
  { id: 'main-color', name: 'rubric (defaults)', value: { hex: palette.rubric, model: 'hex' } },
];
const TEXT = 'Crimson Pro'; // the text face
const DISPLAY = 'Cormorant Garamond'; // italic numerals and the cover's title
const LABEL = 'Cormorant SC'; // small capitals: the lead, the author's name
const [BODY, LEAD] = [10.5, 14]; // pt: the body size and its leading, the grid's pitch
const line = (n) => pt(n * LEAD); // n grid lines

// #region page: a 140 × 216 mm trade page whose text block holds 35 whole lines
const TRIM = { width: 140, height: 216 }; // mm: 5½ × 8½ in
const [TOP, INNER, OUTER] = [22, 20, 15.5]; // mm; mirrored, so INNER is left on a recto
const LINES = 35; // every full page ends on the same line
const MEASURE = TRIM.width - INNER - OUTER; // 104.5 mm: about 69 characters of Crimson Pro
const MM_PER_PT = 25.4 / 72;
const page = {
  sizePreset: 'custom', width: mm(TRIM.width), height: mm(TRIM.height), dpi: 150,
  backgroundColor: col('paper'),
  margins: { top: mm(TOP), bottom: mm(TRIM.height - TOP - LINES * LEAD * MM_PER_PT),
    left: mm(INNER), right: mm(OUTER), mirror: true },
};
// #endregion

// #region answer: a sunk opener: the numeral, a hairline, and the first sentence in small caps
// # I {lead="A green and yellow parrot, … kept repeating over and over:"}
// The heading's text is the numeral, printed by {titleText}; the chapter's first sentence
// travels as the heading's lead attribute, printed by {attr.lead} in small capitals: a
// centred display, which a \n in the attribute breaks by sense.
const [LEAD_AT, BODY_AT] = [9, 12]; // grid lines: the lead's top; where the text starts
const NUMERAL = 48; // pt
const RULE_Y = (LEAD_AT - 1.5) * LEAD * MM_PER_PT; // mm: a line and a half above the lead
const NUMERAL_Y = RULE_Y - NUMERAL * MM_PER_PT - 3; // mm: the numeral's box ends 3 mm above it
const centred = (y) => ({ anchor: { to: 'container', edge: 'top' }, offset: { y } });
const opener = {
  enabled: true,
  // The two-line lead ends on line LEAD_AT + 2; minHeight leaves a blank line under it and
  // starts the text on line BODY_AT (a one-line lead would leave two).
  minHeight: line(BODY_AT),
  slot: { elements: [
    { kind: 'text', id: 'numeral', content: '{titleText}', fontFamily: DISPLAY, italic: true,
      fontWeight: 500, fontSize: pt(NUMERAL), lineHeight: 1, color: col('ink'),
      align: 'center', placement: centred(mm(NUMERAL_Y)) },
    { kind: 'rule', id: 'hairline', direction: 'horizontal', thickness: pt(0.6),
      color: col('rubric'), placement: { ...centred(mm(RULE_Y)), size: { width: mm(18) } } },
    { kind: 'text', id: 'lead', content: '{attr.lead}', fontFamily: LABEL, fontWeight: 600,
      fontSize: pt(9.5), letterSpacing: pt(0.6), color: col('ink'), align: 'center',
      lineHeight: LEAD / 9.5, // one grid line to each line of the lead
      placement: { ...centred(line(LEAD_AT)), size: { width: mm(MEASURE) } } },
  ] },
};
// Every chapter opens on a recto: 'odd' adds a blank verso only after a chapter that ends on
// a recto, where the default 'always-odd' leaves a blank page after every chapter.
// marginBottom 0: the level's default 0.5 em would start the text a line lower.
const chapter = { level: 1, breakBefore: { enabled: true, parity: 'odd' },
  marginBottom: pt(0), italic: true, advancedDesign: opener };
// #endregion

// #region heads: the author on the verso, the title on the recto, folios outside
// {author} and {title} come from the frontmatter.
const HEAD_Y = 12; // mm from the top edge to the top of the running heads
const SHIFT = (INNER - OUTER) / 2; // mm: the text block's centre is off the page's centre
const head = (id, content, parity, edge, x, style) => ({
  kind: 'text', id, content, parity, pages: 'body', // never on openers or blank pages
  fontSize: pt(9), color: col('muted'), ...style,
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(HEAD_Y) } },
});
const smallCaps = { fontFamily: LABEL, fontWeight: 600, letterSpacing: pt(1.2) };
const italic = { fontFamily: DISPLAY, italic: true, fontWeight: 500, fontSize: pt(9.75) };
const folio = { fontFamily: TEXT, color: col('ink') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-author', '{author}', 'even', 'top', -SHIFT, smallCaps),
  head('recto-title', '{title}', 'odd', 'top', SHIFT, italic),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };
// Openers carry a drop folio instead, centred under the text block.
const footer = { elements: [{ kind: 'text', id: 'drop-folio', content: '{pageNumber}',
  pages: 'opener', fontFamily: TEXT, fontSize: pt(9), color: col('muted'), align: 'center',
  placement: { anchor: { to: 'container', edge: 'top' }, offset: { y: mm(7) } } }] };
// #endregion

// #region cover: a section of its own: art, title, author, no heads, a colophon on its verso
// Page 1 is a recto (gotcha: parity-page1-recto): the cover, the colophon on its verso, and
// chapter I on page 3. # The Awakening {style="cover"} opens the section; chapter I closes it.
// The colophon: 2 + 2 + 1 lines of 11 pt and two gaps of 14.5 pt make 84 pt, six grid lines.
const COLOPHON_LINES = 6;
const COLOPHON_TOP = TOP + (LINES - COLOPHON_LINES) * LEAD * MM_PER_PT; // mm: the section's margin
const onPage = (y) => ({ anchor: { to: 'page', edge: 'top' }, offset: { y: mm(y) } }); // y mm down
const cover = {
  id: 'cover',
  header: { elements: [] }, footer: { elements: [] }, // no running heads on p. 1 or p. 2
  margins: { top: mm(COLOPHON_TOP) },
  advancedDesign: { enabled: true, slot: { elements: [
    { kind: 'image', id: 'art', resourceId: 'cover',
      placement: { anchor: { to: 'bleed', edge: 'top-left' }, size: { width: 'fill' } } },
    { kind: 'text', id: 'title', content: '{title}', fontFamily: DISPLAY, italic: true,
      fontWeight: 500, fontSize: pt(50), lineHeight: 1, color: col('ink'), align: 'center',
      placement: onPage(155) },
    { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(0.6),
      color: col('rubric'), placement: { ...onPage(179), size: { width: mm(18) } } },
    { kind: 'text', id: 'author', content: '{author}', ...smallCaps, fontSize: pt(12),
      letterSpacing: pt(2.4), color: col('rubric'), align: 'center', placement: onPage(184) },
  ] } },
};
const colophon = { id: 'colophon', fontSize: pt(8), lineHeight: pt(11), color: col('muted'),
  textAlign: 'left', firstLineIndent: pt(0), spaceBetween: pt(14.5) };
// #endregion

// #region tailpiece: an ornament type that prints no caption, where ::resource stands
// At a chapter's end: :::space, then ::resource{id="tailpiece-1"} (double quotes: gotcha
// resource-double-quotes). The space adds a line to the gap the embed keeps above it.
const ornament = { id: 'ornament', name: 'Ornament', shortLabel: '', captionPrefix: '',
  numberingTemplate: '{n}', resetOn: 'never', counterFormat: 'decimal',
  defaultPlacement: { position: 'here', width: 0.17, align: 'center' } };
const svg = (id, fileId, width, height, altText) => ({ id, typeId: 'ornament', kind: 'svg',
  svg: { fileId, width, height }, altText, createdAt: 0, updatedAt: 0 });
// The cover is a painting, a JPEG in assets/ cut to the art's 140 × 134 mm, declared at its pixels;
// the it edition's is a detail of Signorini's Settignano.
const painting = { id: 'cover', typeId: 'ornament', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: t({ en: 'cover-1190.jpg', it: 'cover-it-1190.jpg' }), format: 'jpeg',
    width: 1190, height: 1139 },
  altText: t({ en: 'The gulf seen between the trunks of water-oaks, a lugger on the horizon; a '
    + 'white sunshade comes up from the beach through the camomile.',
  pt: 'O mar visto entre os troncos de duas árvores, um veleiro no horizonte; uma sombrinha '
    + 'branca sobe da praia por um caminho entre flores amarelas e brancas.',
  fr: 'La mer vue entre les troncs de deux arbres, un voilier à l’horizon ; une ombrelle '
    + 'blanche monte de la plage par un chemin entre des fleurs jaunes et blanches.',
  de: 'Das Meer zwischen den Stämmen zweier Bäume, ein Segelboot am Horizont; ein weißer '
    + 'Sonnenschirm kommt vom Strand einen Weg zwischen gelben und weißen Blumen herauf.',
  it: 'Una strada di Settignano: la bottega del pane e del vino, una donna seduta sulla '
    + 'soglia, un gatto sul selciato al sole.' }) };
const resources = [
  painting,
  // ::resource places each ornament once, so each chapter end has its own id.
  ...t({ en: ['I', 'II'], pt: ['I', 'II', 'III'], fr: ['I', 'II'], de: ['I', 'II'], it: ['I', 'II'] })
    .map((n, i) => svg(`tailpiece-${i + 1}`, 'fleuron.svg', 40, 12,
      t({ en: `A camomile flower between two sprigs closes chapter ${n}.`,
        pt: `Uma flor de camomila entre dois ramos fecha o capítulo ${n}.`,
        fr: `Une fleur de camomille entre deux brins clôt le chapitre ${n}.`,
        de: `Eine Kamillenblüte zwischen zwei Zweigen schließt das Kapitel ${n}.`,
        it: `Un fiore di camomilla tra due rametti chiude il capitolo ${n}.` }))),
];
// #endregion

const card = { id: 'card', fontFamily: LABEL, fontWeight: 600, // the fr edition's visiting card
  textAlign: 'center', firstLineIndent: pt(0) };

const config = () => ({
  locale: t({ en: 'en-us', pt: 'pt', fr: 'fr', de: 'de', it: 'it' }), // each edition's hyphenation patterns
  colorPalette,
  resourceTypes: [ornament],
  page,
  layout: { layoutType: 'single' },
  bodyText: {
    fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'),
    firstLineIndent: mm(4), indentAfterHeading: false,
    minWordSpacing: 0.7, maxWordSpacing: 1.9, // at the default 0.6 a line closes to 0.62
  },
  // The designs paint every heading; the level's own face is the numeral's (500 italic), so the
  // kit has no unused face to load.
  headings: { fontFamily: DISPLAY, fontWeight: 500, levels: [chapter] },
  headingStyles: [cover],
  paragraphStyles: [colophon, card],
  header,
  footer,
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "The Awakening"
author: "Kate Chopin"
---

# The Awakening {style="cover"}

:::paragraphs{style="colophon"}
First published by Herbert S. Stone & Company, Chicago, in April 1899. Chapters I and II follow Project Gutenberg eBook #160, with Chopin’s spelling and punctuation.

Set in Crimson Pro, Cormorant Garamond and Cormorant SC (SIL Open Font License). The cover, a painting, shows the gulf from the Lebrun cottages on Grand Isle.

A Postext Cookbook edition. The text is in the public domain.
:::

# I {lead="A green and yellow parrot, which hung in a cage\noutside the door, kept repeating over and over:"}

“*Allez vous-en! Allez vous-en! Sapristi!* That’s all right!”

He could speak a little Spanish, and also a language which nobody understood, unless it was the mocking-bird that hung on the other side of the door, whistling his fluty notes out upon the breeze with maddening persistence.

Mr. Pontellier, unable to read his newspaper with any degree of comfort, arose with an expression and an exclamation of disgust.

He walked down the gallery and across the narrow “bridges” which connected the Lebrun cottages one with the other. He had been seated before the door of the main house. The parrot and the mocking-bird were the property of Madame Lebrun, and they had the right to make all the noise they wished. Mr. Pontellier had the privilege of quitting their society when they ceased to be entertaining.

He stopped before the door of his own cottage, which was the fourth one from the main building and next to the last. Seating himself in a wicker rocker which was there, he once more applied himself to the task of reading the newspaper. The day was Sunday; the paper was a day old. The Sunday papers had not yet reached Grand Isle. He was already acquainted with the market reports, and he glanced restlessly over the editorials and bits of news which he had not had time to read before quitting New Orleans the day before.

Mr. Pontellier wore eye-glasses. He was a man of forty, of medium height and rather slender build; he stooped a little. His hair was brown and straight, parted on one side. His beard was neatly and closely trimmed.

Once in a while he withdrew his glance from the newspaper and looked about him. There was more noise than ever over at the house. The main building was called “the house,” to distinguish it from the cottages. The chattering and whistling birds were still at it. Two young girls, the Farival twins, were playing a duet from “Zampa” upon the piano. Madame Lebrun was bustling in and out, giving orders in a high key to a yard-boy whenever she got inside the house, and directions in an equally high voice to a dining-room servant whenever she got outside. She was a fresh, pretty woman, clad always in white with elbow sleeves. Her starched skirts crinkled as she came and went. Farther down, before one of the cottages, a lady in black was walking demurely up and down, telling her beads. A good many persons of the *pension* had gone over to the *Chênière Caminada* in Beaudelet’s lugger to hear mass. Some young people were out under the water-oaks playing croquet. Mr. Pontellier’s two children were there—sturdy little fellows of four and five. A quadroon nurse followed them about with a faraway, meditative air.

Mr. Pontellier finally lit a cigar and began to smoke, letting the paper drag idly from his hand. He fixed his gaze upon a white sunshade that was advancing at snail’s pace from the beach. He could see it plainly between the gaunt trunks of the water-oaks and across the stretch of yellow camomile. The gulf looked far away, melting hazily into the blue of the horizon. The sunshade continued to approach slowly. Beneath its pink-lined shelter were his wife, Mrs. Pontellier, and young Robert Lebrun. When they reached the cottage, the two seated themselves with some appearance of fatigue upon the upper step of the porch, facing each other, each leaning against a supporting post.

“What folly! to bathe at such an hour in such heat!” exclaimed Mr. Pontellier. He himself had taken a plunge at daylight. That was why the morning seemed long to him.

“You are burnt beyond recognition,” he added, looking at his wife as one looks at a valuable piece of personal property which has suffered some damage. She held up her hands, strong, shapely hands, and surveyed them critically, drawing up her fawn sleeves above the wrists. Looking at them reminded her of her rings, which she had given to her husband before leaving for the beach. She silently reached out to him, and he, understanding, took the rings from his vest pocket and dropped them into her open palm. She slipped them upon her fingers; then clasping her knees, she looked across at Robert and began to laugh. The rings sparkled upon her fingers. He sent back an answering smile.

“What is it?” asked Pontellier, looking lazily and amused from one to the other. It was some utter nonsense; some adventure out there in the water, and they both tried to relate it at once. It did not seem half so amusing when told. They realized this, and so did Mr. Pontellier. He yawned and stretched himself. Then he got up, saying he had half a mind to go over to Klein’s hotel and play a game of billiards.

“Come go along, Lebrun,” he proposed to Robert. But Robert admitted quite frankly that he preferred to stay where he was and talk to Mrs. Pontellier.

“Well, send him about his business when he bores you, Edna,” instructed her husband as he prepared to leave.

“Here, take the umbrella,” she exclaimed, holding it out to him. He accepted the sunshade, and lifting it over his head descended the steps and walked away.

“Coming back to dinner?” his wife called after him. He halted a moment and shrugged his shoulders. He felt in his vest pocket; there was a ten-dollar bill there. He did not know; perhaps he would return for the early dinner and perhaps he would not. It all depended upon the company which he found over at Klein’s and the size of “the game.” He did not say this, but she understood it, and laughed, nodding good-by to him.

Both children wanted to follow their father when they saw him starting out. He kissed them and promised to bring them back bonbons and peanuts.

:::space

::resource{id="tailpiece-1"}

# II {lead="Mrs. Pontellier’s eyes were quick and bright;\nthey were a yellowish brown, about the color of her hair."}

She had a way of turning them swiftly upon an object and holding them there as if lost in some inward maze of contemplation or thought.

Her eyebrows were a shade darker than her hair. They were thick and almost horizontal, emphasizing the depth of her eyes. She was rather handsome than beautiful. Her face was captivating by reason of a certain frankness of expression and a contradictory subtle play of features. Her manner was engaging.

Robert rolled a cigarette. He smoked cigarettes because he could not afford cigars, he said. He had a cigar in his pocket which Mr. Pontellier had presented him with, and he was saving it for his after-dinner smoke.

This seemed quite proper and natural on his part. In coloring he was not unlike his companion. A clean-shaved face made the resemblance more pronounced than it would otherwise have been. There rested no shadow of care upon his open countenance. His eyes gathered in and reflected the light and languor of the summer day.

Mrs. Pontellier reached over for a palm-leaf fan that lay on the porch and began to fan herself, while Robert sent between his lips light puffs from his cigarette. They chatted incessantly: about the things around them; their amusing adventure out in the water—it had again assumed its entertaining aspect; about the wind, the trees, the people who had gone to the *Chênière;* about the children playing croquet under the oaks, and the Farival twins, who were now performing the overture to “The Poet and the Peasant.”

Robert talked a good deal about himself. He was very young, and did not know any better. Mrs. Pontellier talked a little about herself for the same reason. Each was interested in what the other said. Robert spoke of his intention to go to Mexico in the autumn, where fortune awaited him. He was always intending to go to Mexico, but some way never got there. Meanwhile he held on to his modest position in a mercantile house in New Orleans, where an equal familiarity with English, French and Spanish gave him no small value as a clerk and correspondent.

He was spending his summer vacation, as he always did, with his mother at Grand Isle. In former times, before Robert could remember, “the house” had been a summer luxury of the Lebruns. Now, flanked by its dozen or more cottages, which were always filled with exclusive visitors from the “*Quartier Français*,” it enabled Madame Lebrun to maintain the easy and comfortable existence which appeared to be her birthright.

Mrs. Pontellier talked about her father’s Mississippi plantation and her girlhood home in the old Kentucky blue-grass country. She was an American woman, with a small infusion of French which seemed to have been lost in dilution. She read a letter from her sister, who was away in the East, and who had engaged herself to be married. Robert was interested, and wanted to know what manner of girls the sisters were, what the father was like, and how long the mother had been dead.

When Mrs. Pontellier folded the letter it was time for her to dress for the early dinner.

“I see Léonce isn’t coming back,” she said, with a glance in the direction whence her husband had disappeared. Robert supposed he was not, as there were a good many New Orleans club men over at Klein’s.

When Mrs. Pontellier left him to enter her room, the young man descended the steps and strolled over toward the croquet players, where, during the half-hour before dinner, he amused himself with the little Pontellier children, who were very fond of him.

:::space

::resource{id="tailpiece-2"}
`; // content.<lang>.md, inlined by the Cookbook

// #region art: the fleuron, drawn in millimetres in the page's colour
function drawFleuron(color) { // a camomile head between two leafy sprigs
  const petals = Array.from({ length: 10 }, (_, i) => `<ellipse cx="22.1" cy="6" rx="1.55" `
    + `ry="0.62" transform="rotate(${i * 36} 20 6)" fill="${color}"/>`).join('');
  const sprig = `<path d="M17.2 6.3C14 7.4 10 7.2 6.4 5.6C5.2 5.1 4.2 5.2 3.4 5.9" fill="none" `
    + `stroke="${color}" stroke-width="0.55" stroke-linecap="round"/>`
    + `<path d="M13.4 6.9C12.6 4.9 10.8 4 9 4.2C10 5.6 11.4 6.6 13.4 6.9Z" fill="${color}"/>`
    + `<path d="M9.2 6.5C8.7 7.9 7.4 8.7 5.9 8.8C6.6 7.5 7.7 6.7 9.2 6.5Z" fill="${color}"/>`
    + `<circle cx="2.8" cy="6.3" r="0.7" fill="${color}"/>`;
  return '<svg xmlns="http://www.w3.org/2000/svg" width="40mm" height="12mm" '
    + `viewBox="0 0 40 12">${petals}<circle cx="20" cy="6" r="1.05" fill="${color}"/>${sprig}`
    + `<g transform="translate(40 0) scale(-1 1)">${sprig}</g></svg>`;
}
// #endregion

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { // every face the pages use, loaded before the build
  'Crimson Pro': ['400', '400i'], // text, colophon, folios
  'Cormorant Garamond': ['500i'], // numerals, cover title, the recto's running head
  'Cormorant SC': ['600'], // the leads, the author on the cover and the verso
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
await loadImage(painting.bitmap.fileId, asset(painting.bitmap.fileId));
await loadSvg('fleuron.svg', drawFleuron(palette.rubric));
const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
showPages(doc, { title: t({ en: 'Trade paperback: sunk openers and recto chapters',
  pt: 'Romance em brochura: aberturas rebaixadas em página ímpar',
  fr: 'Roman broché : ouvertures basses et chapitres au recto',
  de: 'Taschenbuch: tiefe Auftakte und Kapitel rechts',
  it: 'Romanzo in brossura: aperture abbassate e capitoli sul recto' }) });

// ─── 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 · 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 ───────────────────────────────────────────────────────────────────────
```

## Варианты

### Начинать главу II на следующей странице

С чётностью `'any'` глава II открывается на странице 6, левой, и книга кончается на странице 7; колонцифра внизу выключена по центру полосы набора, а не страницы, поэтому и на этой левой полосе стоит под серединой текста.

```diff
-const chapter = { level: 1, breakBefore: { enabled: true, parity: 'odd' },
+const chapter = { level: 1, breakBefore: { enabled: true, parity: 'any' },
```

### Отметить смену сцены внутри главы

Тот же цветок между двумя строками `:::space` отмечает смену сцены, а абзац после него начинается без отступа, потому что `indentAfterHeading` выключен. После *seemed long to him.* цветок попадает в низ страницы 4; второй пробел там уже не помещается и отбрасывается. Разрыв добавляет четыре строки, которые выталкивают концовку главы I одну на страницу 6, под колонтитул, поэтому после него подгоните главу заново.

```diff
 const resources = [
+  svg('break-1', 'fleuron.svg', 40, 12, 'A scene break.'),
```

```md
That was why the morning seemed long to him.

:::space

::resource{id="break-1"}

:::space

“You are burnt beyond recognition,” he added, …
```

## Частые ошибки

- **Страница 1 — правая: планируйте по физическим номерам.** Страница 1 — правая полоса, страница 2 — первая левая, поэтому планируйте развороты по физическим номерам: начальная полоса на чётной странице стоит напротив следующей нечётной.
- **::resource{id="…"} — только с двойными кавычками.** Вставка блоком распознаётся только в виде ::resource{id="…"} с двойными кавычками; любая другая форма остаётся в тексте видимой строкой.
- **Предупреждение вёрстки: Нагромождение чётности** (`parityCascade`). Разрывы по чётности накладываются и дают больше двух пустых страниц подряд. Решение: Проверьте разрывы always-odd и чётность breakBefore; для коротких глав обычно хватает чётности any, чтобы пустых страниц не было. ([Документация](https://postext.dev/ru/docs/configuration-headings.md#разрыв-перед-заголовком))

- При `'always-odd'` после каждого раздела, до подгонки чётности, идёт пустая страница-разделитель: глава I ушла бы на страницу 5 после двух пустых, а в книге стало бы десять страниц.
- Эти страницы подогнаны по тексту. С внешним полем 16 мм вместо 15,5 страница 7 делит *after-din-ner* на втором дефисе и кончается на строку раньше, страница 8 кончает абзац обрывком *spondent.*, а вторая концовка уходит на девятую страницу. Проверяйте низ каждой страницы после изменения ширины строки, кегля или спуска.
- *Mr.* и *Mrs.* связаны с именем неразрывным пробелом (U+00A0). В абзаце, который кончается на *seemed long to him.*, оставлен обычный: неразрывный растянул бы первую строку до 2,2 обычного межсловного пробела.

## Источники и лицензии

- Рецепт: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Текст: The Awakening (1899), chapters I and II: Kate Chopin ([источник](https://www.gutenberg.org/ebooks/160)), общественное достояние
- Текст: Quincas Borba (1891), chapters I to III, the Portuguese edition’s text, in modern spelling: Machado de Assis ([источник](https://pt.wikisource.org/wiki/Quincas_Borba)), общественное достояние
- Текст: Madame Gervaisais (1869), chapters I and II, the French edition’s text, in the first edition’s spelling: Edmond et Jules de Goncourt ([источник](https://fr.wikisource.org/wiki/Madame_Gervaisais)), общественное достояние
- Текст: Beate und Mareile (Beate and Mareile, 1903), chapters 1 and 2 (the second abridged), the German edition’s text, in the spelling of S. Fischer’s edition: Eduard von Keyserling ([источник](https://de.wikisource.org/wiki/Beate_und_Mareile)), общественное достояние
- Текст: Le avventure di Pinocchio (The Adventures of Pinocchio, Felice Paggi, Florence, 1883), chapters I and II, the Italian edition’s text, in the first edition’s spelling, without the chapter summaries: Carlo Collodi ([источник](https://it.wikisource.org/wiki/Le_avventure_di_Pinocchio)), общественное достояние
- Текст: The colophon: Postext Cookbook, оригинал
- Изображения: The cover’s view of the gulf, a painting: Generated With Diffusion Models, оригинал
- Изображения: The Italian edition’s cover: a detail of Settignano (c. 1880), oil on canvas; scan from Wikimedia Commons, a 1,744 × 1,669 px cut reduced to 1,190 px wide: Telemaco Signorini ([источник](https://commons.wikimedia.org/wiki/File:Settignano_(c.1880),_by_Telemaco_Signorini.jpg)), общественное достояние
- Изображения: The camomile tailpiece, drawn in code in the page’s palette: Ignacio Ferro, MIT
- Шрифты: Crimson Pro (OFL-1.1), Cormorant Garamond (OFL-1.1), Cormorant SC (OFL-1.1)
- Код: MIT · Образец содержания: MIT

## Похожие рецепты

- [№ 016 · Испанский текст с выключкой в карманном романе](https://postext.dev/ru/cookbook/spanish-pocket-novel.md): Начало главы I «Марианелы» карманным изданием: испанские переносы, пробелы уже 1,7×, без коротких концевых строк, приподнятый инициал, карта как Figura 1. · Уровень 2 (Средний) · Художественная литература, драматургия и эссеистика
- [№ 017 · Пять начал главы в одной книге](https://postext.dev/ru/cookbook/five-chapter-openers.md): Одно начало на уровне 1 и четыре стиля заголовков, названные в Markdown; каждый меняет акцентный цвет, а некоторые — поля, колонки или колонцифры. · Уровень 3 (Продвинутый) · Любой жанр
- [№ 006 · Вводная часть римскими цифрами, затем страница 1](https://postext.dev/ru/cookbook/front-matter-roman-to-arabic.md): Обложка и вводные страницы — заголовки без номера со счётом строчными римскими; :::numbering снова начинает с 1 на правой полосе, где открывается роман. · Уровень 3 (Продвинутый) · Художественная литература, драматургия и эссеистика
