# Книжная страница на сетке базовых линий

> Зеркальная страница в две колонки с полосой набора ровно в 44 интерлиньяжа: текст стоит на одной сетке через средник и корешок.

- Версия HTML: https://postext.dev/ru/cookbook/baseline-grid-book-page
- Рецепт № 013 · Страница и сетка · Уровень 2 (Средний) · Форматы вывода: Canvas
- Жанры: Любой жанр
- Требуется postext ≥ 1.88.1 · проверено с 1.93.0 · дата 2026-11-23
- Страницы: [9](https://postext.dev/cookbook/baseline-grid-book-page/en/p01.webp?v=4021d3b3), [10](https://postext.dev/cookbook/baseline-grid-book-page/en/p02.webp?v=4021d3b3), [11](https://postext.dev/cookbook/baseline-grid-book-page/en/p03.webp?v=4021d3b3)
- Открыть в Sandbox: https://postext.dev/ru/sandbox#recipe=baseline-grid-book-page&lang=en (.postext: https://postext.dev/cookbook/baseline-grid-book-page/en/baseline-grid-book-page.postext)
- Последнее обновление: 2026-10-10
- Другие языки: [en](https://postext.dev/en/cookbook/baseline-grid-book-page.md), [es](https://postext.dev/es/cookbook/baseline-grid-book-page.md), [ca](https://postext.dev/ca/cookbook/baseline-grid-book-page.md), [de](https://postext.dev/de/cookbook/baseline-grid-book-page.md), [el](https://postext.dev/el/cookbook/baseline-grid-book-page.md), [fr](https://postext.dev/fr/cookbook/baseline-grid-book-page.md), [it](https://postext.dev/it/cookbook/baseline-grid-book-page.md), [pt](https://postext.dev/pt/cookbook/baseline-grid-book-page.md), [zh](https://postext.dev/zh/cookbook/baseline-grid-book-page.md), [ja](https://postext.dev/ja/cookbook/baseline-grid-book-page.md), [ar](https://postext.dev/ar/cookbook/baseline-grid-book-page.md)

## Коротко

Три страницы эссе о том, как размечали старинные книги. Показано, как добиться, чтобы каждая строка стояла на одной высоте в обеих колонках и на обеих соседних страницах.

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

Страницы 9–11 из *The Ruled Page*, сборника о книжном деле, занимает эссе «The Secret Canon» о пропорциях, которые средневековые писцы давали страницам. Его поля следуют описанному канону, 2:3:4:6 с зеркальным отражением, на обрезном формате 210 × 280 мм вокруг двух колонок Vollkorn. Сетка базовых линий нарисована поверх страниц бледно-красным, и основной текст обеих колонок и обеих соседних страниц стоит на ней. Название шрифтом Playfair Display занимает первую колонку начальной полосы, рисунок канона стоит вверху второй. Заголовки разделов сдвинуты с сетки на полстроки, а текст под ними на неё возвращается. Примечание мастерской мелким шрифтом идёт со своим интерлиньяжем 10 пт. На странице 11 эссе кончается под рисунком во всю страницу двумя колонками равной длины, вторую закрывают выходные данные.

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

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

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

```js
// script.js, строк 32–53
const LEAD = 13.4; // pt: the body leading is the pitch of the baseline grid
const UNIT = 8; // mm: the margins step 2:3:4:6 in units of 8 mm, like the canon's
const LINES = 44; // lines per column: the text block is a whole number of leads tall
const TRIM = { width: 210, height: 280 }; // mm
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: { mirror: true, // left is the inner margin; mirror swaps it on every verso
    left: mm(2 * UNIT), top: mm(3 * UNIT), right: mm(4 * UNIT), // 16, 24 and 32 mm
    bottom: mm(TRIM.height - 3 * UNIT - LINES * LEAD * MM_PER_PT) }, // 48 mm: six units
  // The layout keeps to the grid whether or not the overlay draws it.
  baselineGrid: { enabled: true, color: col('grid') },
};
const GUTTER = 6; // mm: 162 mm of text block make two columns of 78 mm
const layout = { layoutType: 'double', gutterWidth: mm(GUTTER),
  columnRule: { enabled: true, color: col('rule'), lineWidth: pt(0.4) } };
const body = { fontFamily: 'Vollkorn', fontSize: pt(9.8), lineHeight: pt(LEAD) };
// Lists add no space of their own (any whole number of leads would do). The grid never
// absorbs a list's top margin: the default 1.5 em (14.7 pt here) would set the items
// 1.3 pt off the lines of the column beside them, until the list reaches a new column.
const onGrid = { marginTop: pt(0), marginBottom: pt(0) };
```

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

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

- [Зеркальные поля](https://postext.dev/ru/docs/configuration-page-layout.md#зеркальные-поля): Четыре независимых поля; с включённым mirror левое становится внутренним (корешковым) и меняет сторону на каждой левой полосе, так что страницы складываются в развороты.
- [Сетка базовых линий](https://postext.dev/ru/docs/configuration-page-layout.md#сетка-базовых-линий): Интерлиньяж основного текста и есть сетка, на которой стоит каждая строка, поэтому строки совпадают в соседних колонках и на развороте; вывод сетки поверх страниц только показывает её.

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

- [Выравнивание колонок](https://postext.dev/ru/docs/configuration-page-flow.md#балансировка-колонок)
- [Намеренный отход от сетки](https://postext.dev/ru/docs/architecture.md#элементы-нарушающие-сетку)
- [Размещение рисунков](https://postext.dev/ru/docs/document-format-resources.md#размещение)
- [Висячие и короткие концевые строки](https://postext.dev/ru/docs/configuration-page-flow.md#висячие-строки-короткие-концевые-строки-и-правила-неразрывности)
- [Стили абзацев](https://postext.dev/ru/docs/configuration-styles.md#стили-абзацев)
- [Обрезной формат](https://postext.dev/ru/docs/configuration-page-layout.md#готовые-размеры-страницы)
- [Одна или две колонки](https://postext.dev/ru/docs/configuration-page-layout.md#схемы-колонок)
- [Линейка между колонками](https://postext.dev/ru/docs/configuration-page-layout.md#линейка-между-колонками)
- [Единицы и размеры](https://postext.dev/ru/docs/configuration-fonts-colors-viewers.md#размеры)
- [Шрифт основного текста](https://postext.dev/ru/docs/configuration-text.md#основной-текст)
- [Маркированные списки и контрольные списки](https://postext.dev/ru/docs/configuration-lists-math.md#маркированные-списки)
- [Нумерованные списки](https://postext.dev/ru/docs/configuration-lists-math.md#нумерованные-списки)
- [Уровни заголовков](https://postext.dev/ru/docs/configuration-headings.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-resources.md#ресурсы)
- [Страницы на холсте](https://postext.dev/ru/docs/configuration-programmatic-usage.md#рендеринг-страницы-в-растр)
- [Ссылки, которые размещают рисунки](https://postext.dev/ru/docs/document-format-resources.md#строчная-ссылка-основная-форма)
- [Цвет бумаги](https://postext.dev/ru/docs/configuration-page-layout.md#страница)

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

- [`bodyText`](https://postext.dev/ru/docs/configuration-text.md#основной-текст), [`captionStyle`](https://postext.dev/ru/docs/configuration-resources.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#верхние-и-нижние-колонтитулы), [`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#перенос-слов), [`orderedLists`](https://postext.dev/ru/docs/configuration-lists-math.md#нумерованные-списки), [`page`](https://postext.dev/ru/docs/configuration-page-layout.md#страница), [`paragraphStyles`](https://postext.dev/ru/docs/configuration-styles.md#стили-абзацев), [`unorderedLists`](https://postext.dev/ru/docs/configuration-lists-math.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#рендеринг-страницы-в-растр)

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

- Vollkorn (OFL-1.1), Playfair Display (OFL-1.1), Vollkorn SC (OFL-1.1)

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

### 1 · Пусть с сетки сходят заголовки, но не списки

```js
// script.js, строк 99–112
  headings: { fontFamily: 'Playfair Display', color: col('ink'), balancing,
    levels: [
      // parity 'odd': the essay opens on a recto.
      // Two lines of 46 pt, each four leads tall, then one lead: the text starts on line 10.
      { level: 1, breakBefore: { enabled: true, parity: 'odd' },
        fontSize: pt(46), lineHeight: pt(4 * LEAD), italic: true, color: col('rubric'),
        marginBottom: pt(LEAD) },
      // A lead and a half above puts the head between two grid lines. The margin below
      // needs no fitting: the engine snaps the text under a head to the next grid line.
      { level: 2, fontSize: pt(12.5), lineHeight: pt(LEAD), marginTop: pt(1.5 * LEAD) },
    ] },
  // Lists add no space of their own (onGrid, in the short answer): items stay on the grid.
  unorderedLists: { ...onGrid, bulletChar: '–', color: col('rubric'), fontWeight: 400 },
  orderedLists: { ...onGrid, color: col('rubric') }, // numbers in the rubric, text in ink
```

Отбивка над заголовком сохраняется точно, поэтому 1,5 интерлиньяжа ставят заголовок между двумя линиями сетки, а текст под ним привязывается к следующей линии ([сетка базовых линий](https://postext.dev/ru/docs/configuration-page-layout.md#сетка-базовых-линий)). Список перед первым пунктом к сетке не привязывается, поэтому короткий ответ обнуляет отбивки списка (подошло бы и любое целое число интерлиньяжей); с 1,5 em по умолчанию три пункта на странице 10 стояли бы на 1,3 пт ниже строк соседней колонки. Две строки названия кегля 46 пт занимают по четыре интерлиньяжа, нижняя отбивка — ещё один, и эссе начинается со строки 10.

![Page 10: Lines to stand on.](https://postext.dev/cookbook/baseline-grid-book-page/en/p02.webp?v=4021d3b3)

*Страница 10: список во второй колонке держится сетки соседних абзацев; примечание мастерской попадает между линиями, заголовок под ним стоит на полстроки мимо них, а его текст вернулся на сетку.*

### 2 · Сойдите с сетки намеренно и вернитесь

```js
// script.js, строк 115–120
  paragraphStyles: [
    { id: 'note', fontSize: pt(7.8), lineHeight: pt(10), color: col('muted'),
      boldColor: col('rubric'), firstLineIndent: pt(0), marginTop: pt(LEAD / 2) },
    { id: 'colophon', fontFamily: 'Vollkorn SC', fontSize: pt(7.5), lineHeight: pt(10),
      color: col('muted'), textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD) },
  ],
```

Примечание — это контейнер `:::paragraphs` с набором 7,8/10 пт, мимо сетки. После его последнего абзаца положение округляется вверх до следующей линии, поэтому следующий заголовок стоит там же, где стоял бы после основного текста ([контейнер `:::paragraphs`](https://postext.dev/ru/docs/configuration-styles.md#контейнер-paragraphs)). Выходные данные используют тот же контейнер с набором 7,5/10 пт: четыре строки занимают 40 пт, на 0,2 пт меньше трёх интерлиньяжей, и последняя колонка эссе кончается вровень с соседней.

### 3 · Ставьте рисунки там, где сетка их примет

```js
// script.js, строк 319–332
// mm: a column wide and just short enough for a 17-lead band with its caption; a block wide
const CANON = [COLUMN_W, 61.8], PAGES = [BLOCK_W, 64];
const figure = (id, [width, height], placement, [caption, altText]) => ({
  id, typeId: 'figure', kind: 'svg', svg: { fileId: `${id}.svg`, width, height },
  placement, caption, altText, createdAt: 0, updatedAt: 0,
});
const resources = [
  // A float never lands above the paragraph that cites it. A column 'top' float cited in
  // the first column can still take the head of the second, on the same page.
  figure('canon', CANON, { position: 'top' }, t(CAPTIONS.canon)),
  // A page-wide 'top' float cannot, so it waits for the next page (gotcha: top-float-next-page).
  // Each band is rounded up to whole leads, so the text under it stays on the grid.
  figure('pages', PAGES, { position: 'top', span: 'page' }, t(CAPTIONS.pages)),
];
```

Плавающий объект никогда не встаёт выше абзаца, который на него ссылается ([размещение](https://postext.dev/ru/docs/document-format-resources.md#размещение)). Канон, упомянутый в первой колонке, ещё может занять верх второй на странице 9; сравнение во всю страницу, упомянутое на странице 10, ждёт страницы 11. Каждая такая полоса округляется вверх до целых интерлиньяжей, поэтому текст под рисунком начинается на линии сетки, вровень с соседней колонкой и соседней страницей. Подгоняйте размер рисунка под это округление: при 61,8 мм полоса канона вместе с подписью занимает 17 интерлиньяжей, при 62,5 мм заняла бы 18 и оставила под подписью почти пустую строку.

![Page 11. Figure 1.2. This book’s 210 × 280 mm page twice. Left, divided by the canon into ninths, with a text block of 140 × 187 mm. Right, as the book sets it: margins of 16, 24, 32 and 48 mm and two columns of 44 lines.](https://postext.dev/cookbook/baseline-grid-book-page/en/p03.webp?v=4021d3b3)

*Страница 11: текст под рисунком во всю страницу начинается на линии сетки, и эссе кончается двумя ровными колонками, вторую закрывают выходные данные.*

### 4 · Доверьте выравнивание колонок балансировке

```js
// script.js, строк 86–87
// On by default: it fills a column a keep rule leaves short, and cuts the last page level.
const balancing = { enabled: true };
```

Каждая полная колонка на страницах 9 и 10 кончается на строке 44: полоса набора равна ровно 44 интерлиньяжам, и текст подогнан под неё. Запрет отрывать заголовок от текста и правила для висячих строк вверху и внизу колонки (widow, orphan) и коротких концевых строк включены по умолчанию. Когда одно из них заканчивает колонку строкой раньше, балансировка помещает недостающее место над одним из предыдущих заголовков ([балансировка колонок](https://postext.dev/ru/docs/configuration-page-flow.md#балансировка-колонок)), где оно заметно, поэтому подгоняйте текст, пока ей нечего будет заполнять. На последней странице она делит оставшиеся строки так, чтобы обе колонки кончались на одной.

### 5 · Отразите поля и начните нумерацию со страницы 9

```js
// script.js, строк 57–82
const OUTER = 4 * UNIT; // mm: the heads end where the text block does
const RISE = 1.5 * UNIT; // mm: heads 12 mm into the head margin; the drop folio 12 mm below
const TAB = 7; // mm from a folio to the title beside it
const onPage = (edge, x) => ({ anchor: { to: 'page', edge },
  offset: { x: mm(x), y: mm(RISE) } });
const head = (id, content, parity, placement, extra = {}) => ({
  kind: 'text', id, content, parity, placement, pages: 'body', // never on the opener
  fontFamily: 'Vollkorn SC', fontSize: pt(8.5), fontWeight: 600, letterSpacing: pt(0.8),
  color: col('muted'), ...extra,
});
const folio = { fontFamily: 'Vollkorn', fontWeight: 700, letterSpacing: pt(0),
  color: col('rubric') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', onPage('top-left', OUTER), folio),
  head('verso-title', '{title}', 'even', onPage('top-left', OUTER + TAB)),
  head('recto-title', '{chapterTitle}', 'odd', onPage('top-right', -(OUTER + TAB))),
  head('recto-folio', '{pageNumber}', 'odd', onPage('top-right', -OUTER), folio),
] };
// The opener drops its folio into the foot margin, centred under the text block.
const underBlock = { anchor: { to: 'container', edge: 'top' }, offset: { y: mm(RISE) } };
const footer = { elements: [
  head('drop-folio', '{pageNumber}', 'all', underBlock, { ...folio, pages: 'opener' }),
] };
// startAt prints the folios from 9; pageIndexOffset counts the 8 pages before them, so
// mirroring, parity and breakBefore follow the book (7 would add a blank page).
const continuation = { pageIndexOffset: 8, pageNumbering: { startAt: 9 } };
```

Короткий ответ вычисляет нижнее поле: обрезной формат 280 мм минус верхнее поле 24 мм и полоса набора ровно в `LINES` интерлиньяжей (44 × 13,4 пт = 208 мм) оставляет 48 мм, шесть единиц, как требует прогрессия 2:3:4:6. С `mirror: true` 16 мм, заданные в `left`, — это внутреннее поле: слева на правой полосе и справа на левой ([зеркальные поля](https://postext.dev/ru/docs/configuration-page-layout.md#зеркальные-поля)). Поэтому колонтитулы, привязанные в `OUTER` миллиметрах от края страницы, кончаются там же, где полоса набора, с внешней стороны; `pages: 'body'` убирает их с начальной полосы. `startAt: 9` печатает колонцифры с 9 по 11, а `pageIndexOffset: 8` учитывает восемь страниц перед ними, так что отражение полей, чётность колонтитулов и `breakBefore: 'odd'` следуют сшитой книге. При смещении 7 первая страница считалась бы левой, и переход на нечётную поставил бы перед эссе пустую страницу.

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

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

- Папка с исходными файлами: https://github.com/drnachio/postext/tree/main/cookbook/baseline-grid-book-page

### script.js

```js
// ═══ Postext Cookbook · Nº 013 · A book page on a baseline grid ═════════════════════
// https://postext.dev/en/cookbook/baseline-grid-book-page
// Code: MIT · Text: original (CC BY 4.0) · Pictures: drawn in code (CC BY 4.0)
// Fonts: Vollkorn, Playfair Display, Vollkorn SC (SIL OFL 1.1) · Needs postext ≥ 1.88.1
// An essay on the canon of page proportions, on a page that shows its geometry and grid.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the sample document's language ('en' | 'es' | 'pt' | 'fr' | 'de' | 'it')
const RECIPE = 'baseline-grid-book-page';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// A scribe's colours: ink, one rubric red and the pale red of a ruled page.
const palette = {
  ink: '#211d1a', // text: a warm near-black
  rubric: '#b3261e', // the one accent: title, numbers, folios, the drawings' lines
  grid: '#efc6bd', // the baseline grid, as pale as a manuscript's ruling
  rule: '#d5cbbb', // the column rule and the drawings' hairlines
  muted: '#716860', // running heads, the workshop note, the colophon (5.1:1 on paper)
  tint: '#ede4d3', // the ground of the drawings
  paper: '#fbf8f1',
};
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' } })),
  // Defaults this config does not restate link to main-color: point it at the rubric.
  { id: 'main-color', name: 'rubric (defaults)', value: { hex: palette.rubric, model: 'hex' } },
];

// #region answer: one grid for the whole spread: trim, mirrored margins, two columns, leading
const LEAD = 13.4; // pt: the body leading is the pitch of the baseline grid
const UNIT = 8; // mm: the margins step 2:3:4:6 in units of 8 mm, like the canon's
const LINES = 44; // lines per column: the text block is a whole number of leads tall
const TRIM = { width: 210, height: 280 }; // mm
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: { mirror: true, // left is the inner margin; mirror swaps it on every verso
    left: mm(2 * UNIT), top: mm(3 * UNIT), right: mm(4 * UNIT), // 16, 24 and 32 mm
    bottom: mm(TRIM.height - 3 * UNIT - LINES * LEAD * MM_PER_PT) }, // 48 mm: six units
  // The layout keeps to the grid whether or not the overlay draws it.
  baselineGrid: { enabled: true, color: col('grid') },
};
const GUTTER = 6; // mm: 162 mm of text block make two columns of 78 mm
const layout = { layoutType: 'double', gutterWidth: mm(GUTTER),
  columnRule: { enabled: true, color: col('rule'), lineWidth: pt(0.4) } };
const body = { fontFamily: 'Vollkorn', fontSize: pt(9.8), lineHeight: pt(LEAD) };
// Lists add no space of their own (any whole number of leads would do). The grid never
// absorbs a list's top margin: the default 1.5 em (14.7 pt here) would set the items
// 1.3 pt off the lines of the column beside them, until the list reaches a new column.
const onGrid = { marginTop: pt(0), marginBottom: pt(0) };
// #endregion

// #region heads: the book's title on versos, the essay's on rectos, folios from page 9
const OUTER = 4 * UNIT; // mm: the heads end where the text block does
const RISE = 1.5 * UNIT; // mm: heads 12 mm into the head margin; the drop folio 12 mm below
const TAB = 7; // mm from a folio to the title beside it
const onPage = (edge, x) => ({ anchor: { to: 'page', edge },
  offset: { x: mm(x), y: mm(RISE) } });
const head = (id, content, parity, placement, extra = {}) => ({
  kind: 'text', id, content, parity, placement, pages: 'body', // never on the opener
  fontFamily: 'Vollkorn SC', fontSize: pt(8.5), fontWeight: 600, letterSpacing: pt(0.8),
  color: col('muted'), ...extra,
});
const folio = { fontFamily: 'Vollkorn', fontWeight: 700, letterSpacing: pt(0),
  color: col('rubric') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', onPage('top-left', OUTER), folio),
  head('verso-title', '{title}', 'even', onPage('top-left', OUTER + TAB)),
  head('recto-title', '{chapterTitle}', 'odd', onPage('top-right', -(OUTER + TAB))),
  head('recto-folio', '{pageNumber}', 'odd', onPage('top-right', -OUTER), folio),
] };
// The opener drops its folio into the foot margin, centred under the text block.
const underBlock = { anchor: { to: 'container', edge: 'top' }, offset: { y: mm(RISE) } };
const footer = { elements: [
  head('drop-folio', '{pageNumber}', 'all', underBlock, { ...folio, pages: 'opener' }),
] };
// startAt prints the folios from 9; pageIndexOffset counts the 8 pages before them, so
// mirroring, parity and breakBefore follow the book (7 would add a blank page).
const continuation = { pageIndexOffset: 8, pageNumbering: { startAt: 9 } };
// #endregion

// #region balance: full columns end flush, and the last page ends level
// On by default: it fills a column a keep rule leaves short, and cuts the last page level.
const balancing = { enabled: true };
// #endregion

const config = () => ({
  locale: t({ en: 'en-us', es: 'es', pt: 'pt', fr: 'fr', de: 'de', it: 'it' }), // hyphenation, caption labels
  colorPalette,
  page,
  layout,
  bodyText: { ...body, color: col('ink'), boldColor: col('ink'), italicColor: col('ink'),
    referenceColor: col('rubric'), referenceBold: false,
    firstLineIndent: mm(4), indentAfterHeading: false }, // hyphenation and widow rules are on
  // #region flow: heads that leave the grid and come back to it; lists that never leave it
  headings: { fontFamily: 'Playfair Display', color: col('ink'), balancing,
    levels: [
      // parity 'odd': the essay opens on a recto.
      // Two lines of 46 pt, each four leads tall, then one lead: the text starts on line 10.
      { level: 1, breakBefore: { enabled: true, parity: 'odd' },
        fontSize: pt(46), lineHeight: pt(4 * LEAD), italic: true, color: col('rubric'),
        marginBottom: pt(LEAD) },
      // A lead and a half above puts the head between two grid lines. The margin below
      // needs no fitting: the engine snaps the text under a head to the next grid line.
      { level: 2, fontSize: pt(12.5), lineHeight: pt(LEAD), marginTop: pt(1.5 * LEAD) },
    ] },
  // Lists add no space of their own (onGrid, in the short answer): items stay on the grid.
  unorderedLists: { ...onGrid, bulletChar: '–', color: col('rubric'), fontWeight: 400 },
  orderedLists: { ...onGrid, color: col('rubric') }, // numbers in the rubric, text in ink
  // #endregion
  // #region note: small type leaves the grid on purpose, and the flow snaps back after it
  paragraphStyles: [
    { id: 'note', fontSize: pt(7.8), lineHeight: pt(10), color: col('muted'),
      boldColor: col('rubric'), firstLineIndent: pt(0), marginTop: pt(LEAD / 2) },
    { id: 'colophon', fontFamily: 'Vollkorn SC', fontSize: pt(7.5), lineHeight: pt(10),
      color: col('muted'), textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD) },
  ],
  // #endregion
  captionStyle: { fontSize: pt(8), labelColor: col('rubric'), descriptionItalic: true },
  header,
  footer,
});

// #region art: the two drawings, in the page's palette (lines only: no text, no filters)
const BLOCK_W = TRIM.width - 6 * UNIT; // mm: the text block, 162 mm
const COLUMN_W = (BLOCK_W - GUTTER) / 2; // mm: one column, 78 mm
const svgFile = (w, h, markup) => `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}"`
  + ` width="${w * 10}" height="${h * 10}">`
  + `<rect width="${w}" height="${h}" fill="${palette.tint}"/>${markup}</svg>`;
const ln = (x1, y1, x2, y2, stroke, w = 0.4) => `<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}"`
  + ` stroke="${stroke}" stroke-width="${w}" stroke-linecap="round"/>`;
const leaf = (x, y, w, h) => `<rect x="${x}" y="${y}" width="${w}" height="${h}"`
  + ` fill="${palette.paper}" stroke="${palette.rule}" stroke-width="0.3"/>`;
const ruling = (x, y, w, h, n) => Array.from({ length: n }, (_, i) => // a ruled text block
  ln(x, y + (h * (i + 0.8)) / n, x + w, y + (h * (i + 0.8)) / n, palette.rule, 0.25)).join('');
const dot = (x, y) => `<circle cx="${x}" cy="${y}" r="0.8" fill="${palette.rubric}"/>`;

// Figure 1: the canon constructed on an open spread of 2:3 pages (sizes in mm).
function canonSvg(w, h) {
  const W = (w - 8) / 2, H = 1.5 * W, X = 4, Y = 3.5; // two 2:3 pages, the ninths under them
  const at = (fx, fy) => [X + fx * W, Y + fy * H]; // a point in page widths and heights
  const line = (a, b) => ln(...at(...a), ...at(...b), palette.rubric);
  let s = leaf(X, Y, W, H) + leaf(X + W, Y, W, H);
  s += ruling(...at(2 / 9, 1 / 9), (6 * W) / 9, (6 * H) / 9, 24); // verso text block
  s += ruling(...at(10 / 9, 1 / 9), (6 * W) / 9, (6 * H) / 9, 24); // recto text block
  s += `<circle cx="${X + W / 2}" cy="${Y + (4 * H) / 9}" r="${W / 2}" fill="none"`
    + ` stroke="${palette.muted}" stroke-width="0.35"/>`; // a page wide, a block tall
  s += ln(X + W, Y, X + W, Y + H, palette.muted, 0.5); // the spine
  s += line([0, 1], [2, 0]) + line([0, 0], [2, 1]); // 1 · the spread's diagonals
  s += line([1, 0], [0, 1]) + line([1, 0], [2, 1]); // 2 · each page's diagonal
  s += line([2 / 3, 1 / 3], [2 / 3, 0]) + line([4 / 3, 1 / 3], [4 / 3, 0]); // 3 · the verticals
  s += line([2 / 3, 0], [4 / 3, 1 / 3]) + line([4 / 3, 0], [2 / 3, 1 / 3]); // 4 · across the spine
  for (let i = 0; i <= 18; i++) { // the ninths, ticked under the spread
    const [x, y] = at(i / 9, 1);
    s += ln(x, y + 1.2, x, y + (i % 9 ? 2.8 : 4), palette.muted, 0.3);
  }
  for (const c of [[2 / 9, 1 / 9], [8 / 9, 1 / 9], [2 / 9, 7 / 9], [10 / 9, 1 / 9], [16 / 9, 1 / 9],
    [16 / 9, 7 / 9]]) s += dot(...at(...c)); // 5 · the corners the lines fix
  return svgFile(w, h, s);
}

// Figure 2: this book's page twice, at a quarter of its size.
function pagesSvg(w, h) {
  const k = (h - 8) / TRIM.height, W = TRIM.width * k, H = TRIM.height * k, Y = 4, GAP = 20;
  const X1 = (w - 2 * W - GAP) / 2, X2 = X1 + W + GAP;
  let s = leaf(X1, Y, W, H) + leaf(X2, Y, W, H);
  for (let i = 1; i < 9; i++) { // the canon's ninths
    s += ln(X1 + (i * W) / 9, Y, X1 + (i * W) / 9, Y + H, palette.grid, 0.3);
    s += ln(X1, Y + (i * H) / 9, X1 + W, Y + (i * H) / 9, palette.grid, 0.3);
  }
  s += ruling(X1 + W / 9, Y + H / 9, (6 * W) / 9, (6 * H) / 9, 32);
  s += `<rect x="${X1 + W / 9}" y="${Y + H / 9}" width="${(6 * W) / 9}" height="${(6 * H) / 9}"`
    + ` fill="none" stroke="${palette.rubric}" stroke-width="0.45"/>`;
  const colW = COLUMN_W * k, top = Y + 3 * UNIT * k, tall = LINES * LEAD * MM_PER_PT * k;
  const left = X2 + 2 * UNIT * k;
  for (const x of [left, left + colW + GUTTER * k]) s += ruling(x, top, colW, tall, LINES);
  s += `<rect x="${left}" y="${top}" width="${BLOCK_W * k}" height="${tall}"`
    + ` fill="none" stroke="${palette.rubric}" stroke-width="0.45"/>`;
  s += ln(X1, Y, X1, Y + H, palette.muted, 0.6) + ln(X2, Y, X2, Y + H, palette.muted, 0.6);
  return svgFile(w, h, s);
}
// #endregion

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "The Ruled Page"
subtitle: "Essays on the Making of Books"
---

# The Secret Canon

Before a medieval scribe wrote a word, the page had already been measured. The sheets of a quire were pricked along their edges with an awl and ruled from prick to prick with a dry point or a lead point, so that every line of writing had a line to stand on and every leaf of the book had the same frame. In many manuscripts the ruling can still be seen, faint as a watermark. It records two decisions the scribes never explained: how large the written area should be, and where on the leaf it should sit. The drawing in :ref{id="canon"} gives the answer that three people, working apart in the twentieth century, measured back out of the old books themselves.

In 1946 J. A. van de Graaf published, in a Dutch journal, a construction that finds the text block of a page with a straightedge alone, without measuring anything. A year later the Argentine typographer Raúl Rosarivo argued in *Divina proporción tipográfica* that Gutenberg, Peter Schöffer and Nicolas Jenson had divided their pages into ninths. And Jan Tschichold, who in his youth had championed asymmetric layout, spent his later years showing why the old proportions were so hard to improve on. Their results agree closely. The method is now known as the secret canon because nobody wrote it down, yet it can be measured in manuscript after manuscript and in the first printed books.

## Drawing the canon

All the construction needs is an open spread of two pages and a straightedge:

1. Draw the two diagonals of the spread.
2. On each page, draw the diagonal that runs from the head of the spine to the foot of the fore-edge.
3. Where it crosses a diagonal of the spread, draw a vertical line up to the head of the page.
4. Join its top to the crossing on the facing page.
5. The new line cuts the page diagonal at the inner top corner of the text block. The outer top corner lies on the spread diagonal, the outer bottom corner on the page diagonal, and the rectangle closes itself.

That rectangle is the scribes’ text block. The inner margin is a ninth of the page’s width and the outer margin two ninths; the head margin is a ninth of its height and the foot two ninths. On a page of two by three the four margins run 2:3:4:6, inner, head, outer, foot. The text block has the page’s proportions and is as tall as the page is wide, as the circle shows.

## Villard’s figure

Medieval draughtsmen could also divide a line without a ruler. The thirteenth-century portfolio of Villard de Honnecourt, thirty-three leaves of drawings now in the Bibliothèque nationale de France, contains a figure that divides a line into equal parts with a straightedge alone: a few diagonals across a rectangle, and each crossing marks off a third, a quarter or a fifth of its side, as far as the draughtsman cares to go. Tschichold showed that the same figure finds the ninths of a page. The leaves of the portfolio, as they survive, measure about 235 by 155 millimetres, close to two by three.

Rosarivo came to the ninths from the other end. Working with compass and ruler on books printed in the fifteenth century, he concluded that their type areas had been found by dividing the page into nine parts each way, the text taking six of them, and he called the 2:3 proportion of those pages the secret number. Experts at the Gutenberg Museum in Mainz examined his findings, which the *Gutenberg-Jahrbuch* later published again.

:::paragraphs{style="note"}
**Workshop note.** On a page of 160 by 240 millimetres the canon gives margins of 17.8 millimetres at the spine, 26.7 at the head, 35.6 at the fore-edge and 53.3 at the foot, and a text block of 106.7 by 160 millimetres, as tall as the page is wide. Divide the width and the height into nine and count: one part inside, one above, two outside and two below.
:::

## Lines to stand on

The ruling fixed the lines as well as the frame. Until early in the thirteenth century most scribes wrote their first line on top of the first ruled line; within a generation they had begun to hang it below that line instead, a change regular enough for palaeographers to date manuscripts by it. N. R. Ker, who described it in 1960, placed it around 1230. The ruling drew the columns, too: pairs of vertical lines bounded each column of a two-column book, and the hairline between the columns of this page is the last trace of them.

The printers kept to the discipline. Gutenberg’s Bible is set in two columns of forty lines on its first pages, forty-one on page ten and forty-two on nearly every page after it, which is why bibliographers call it the 42-line Bible. The lines were set closer together inside the same type area, so the frame held more text and the whole Bible needed less paper.

## What a working page keeps

The canon was made for large books meant to last, with room in their margins for a reader’s notes. Few books can afford it now. On this page of 210 by 280 millimetres it would ask for a text block of 140 by 187, and more than half of the paper would stay blank. The page you are reading keeps three things from the canon instead:

- the progression of its margins, still 2:3:4:6, now in steps of eight millimetres: 16 at the spine, 24 at the head, 32 at the fore-edge and 48 at the foot;
- the spread as the unit of design: two inner margins together are as wide as one outer margin, so the white around each text block reads evenly across the open book;
- the ruling itself, now a baseline grid of 13.4 points that the text of both columns stands on, on this page and on the page facing it.

It gives up the ninths. Its text block, 162 by 208 millimetres, is far larger than the canon’s, and it is divided into two columns of 78 millimetres with a gutter of six between them. Set across the whole block, a line of this type would run to more than a hundred characters, too long for the eye to find its way back to the start of the next; a column holds about fifty, and exactly 44 lines. The two pages are drawn side by side in :ref{id="pages"}.

A page that counts its lines can keep the feet of its columns level, too: every full column in this essay ends on the forty-fourth line. When the rules that keep a heading with its text, or keep a paragraph from leaving a single line behind, would end a column a line short, the missing line goes in as a little more space above a heading higher up, and the column still reaches the last line. On the last page of an essay the columns are cut to the same length instead, and the text ends in a level band.

A baseline grid fixes where every line will stand before a word is set, as the awl and the dry point did on parchment. The lists in this essay add no space of their own, so their items fall on the same lines as the paragraphs in the column beside them. A heading may sit between two lines of the grid, with a line and a half above it and half a line below, but the text under it comes straight back to the grid. The workshop note, in smaller type, runs on a closer leading of its own and returns to the grid where it ends. A figure is treated the same way: its band, caption included, is rounded up to whole lines (seventeen for :ref{id="canon"}), so the text below a drawing at the head of a page lines up with the text on the page facing it.

The grid on these pages is drawn in pale red so that the reader can check the text against it. Open the book at any spread and each line of the left page continues across the spine into a line of the right, as the scribes’ ruling ran from prick to prick across both halves of the opened sheet.

:::paragraphs{style="colophon"}
Set in Vollkorn, 9.8 on 13.4 points,

with Playfair Display and Vollkorn SC

(SIL Open Font License 1.1)

Text and drawings: Postext Cookbook, CC BY 4.0
:::
`; // content.<lang>.md, inlined by the Cookbook
// Captions and alt text in every sample language: [caption, altText].
const CAPTIONS = {
  canon: {
    en: ['The canon on an open spread of 2:3 pages. The diagonals fix the corners of both text '
      + 'blocks; the circle, as wide as a page, is exactly as tall as its block.',
    'Two facing pages crossed by red construction lines, a ruled text block where they cross '
      + 'on each page, and a circle as wide as the left page.'],
    es: ['El canon sobre un pliego abierto de páginas 2:3. Las diagonales fijan las esquinas de '
      + 'las dos cajas; el círculo, tan ancho como la página, es tan alto como su caja.',
    'Dos páginas enfrentadas cruzadas por líneas rojas de construcción, una caja pautada donde '
      + 'se cortan en cada página y un círculo tan ancho como la página izquierda.'],
    pt: ['O cânone sobre uma página dupla aberta de páginas 2:3. As diagonais fixam os cantos '
      + 'das duas manchas; o círculo, da largura da página, tem exatamente a altura da mancha.',
    'Duas páginas lado a lado cruzadas por linhas vermelhas de construção, uma mancha pautada '
      + 'onde elas se cruzam em cada página e um círculo da largura da página esquerda.'],
    fr: ['Le canon sur une double page ouverte de pages 2:3. Les diagonales fixent les angles '
      + 'des deux blocs de texte ; le cercle, aussi large que la page, est exactement aussi haut '
      + 'que son bloc.',
    'Deux pages en regard traversées de lignes de construction rouges, un bloc de texte réglé '
      + 'là où elles se croisent sur chaque page, et un cercle aussi large que la page de gauche.'],
    de: ['Der Kanon auf einer aufgeschlagenen Doppelseite aus Seiten im Verhältnis 2:3. Die '
      + 'Diagonalen legen die Ecken beider Satzspiegel fest; der Kreis, so breit wie die Seite, '
      + 'ist genau so hoch wie ihr Satzspiegel.',
    'Zwei gegenüberliegende Seiten mit roten Konstruktionslinien, auf jeder Seite ein linierter '
      + 'Satzspiegel an ihren Schnittpunkten und ein Kreis so breit wie die linke Seite.'],
    it: ['Il canone su una doppia pagina aperta di pagine 2:3. Le diagonali fissano gli angoli '
      + 'delle due gabbie; il cerchio, largo quanto la pagina, è alto esattamente quanto la sua '
      + 'gabbia.',
    'Due pagine affiancate attraversate da linee di costruzione rosse, una gabbia rigata dove '
      + 'le linee si incrociano su ogni pagina e un cerchio largo quanto la pagina di sinistra.'],
  },
  pages: {
    en: ['This book’s 210 × 280 mm page twice. Left, divided by the canon into ninths, with a '
      + 'text block of 140 × 187 mm. Right, as the book sets it: margins of 16, 24, 32 and 48 '
      + 'mm and two columns of 44 lines.',
    'Two identical pages: the left one divided into a nine-by-nine grid around its text block, '
      + 'the right one holding two ruled columns.'],
    es: ['La página de 210 × 280 mm de este libro, dos veces. A la izquierda, dividida en '
      + 'novenos por el canon, con una caja de 140 × 187 mm. A la derecha, tal como la compone '
      + 'el libro: márgenes de 16, 24, 32 y 48 mm y dos columnas de 44 líneas.',
    'Dos páginas iguales: la izquierda, dividida en una cuadrícula de nueve por nueve alrededor '
      + 'de su caja; la derecha, con dos columnas pautadas.'],
    pt: ['A página de 210 × 280 mm deste livro, duas vezes. À esquerda, dividida em nonos pelo '
      + 'cânone, com uma mancha de 140 × 187 mm. À direita, como o livro a compõe: margens de '
      + '16, 24, 32 e 48 mm e duas colunas de 44 linhas.',
    'Duas páginas iguais: a da esquerda dividida numa grade de nove por nove em volta da '
      + 'mancha, a da direita com duas colunas pautadas.'],
    fr: ['La page de 210 × 280 mm de ce livre, deux fois. À gauche, divisée en neuvièmes par le '
      + 'canon, avec un bloc de texte de 140 × 187 mm. À droite, telle que le livre la compose : '
      + 'marges de 16, 24, 32 et 48 mm et deux colonnes de 44 lignes.',
    'Deux pages identiques : celle de gauche divisée en une grille de neuf sur neuf autour de '
      + 'son bloc de texte, celle de droite avec deux colonnes réglées.'],
    de: ['Die Seite dieses Buches, 210 × 280 mm, zweimal. Links vom Kanon in Neuntel geteilt, mit '
      + 'einem Satzspiegel von 140 × 187 mm. Rechts so, wie das Buch sie setzt: Stege von 16, 24, '
      + '32 und 48 mm und zwei Spalten zu 44 Zeilen.',
    'Zwei gleiche Seiten: die linke um ihren Satzspiegel in ein Raster von neun mal neun Feldern '
      + 'geteilt, die rechte mit zwei linierten Spalten.'],
    it: ['La pagina di 210 × 280 mm di questo libro, due volte. A sinistra, divisa in noni dal '
      + 'canone, con una gabbia di 140 × 187 mm. A destra, come la compone il libro: margini di '
      + '16, 24, 32 e 48 mm e due colonne di 44 righe.',
    'Due pagine uguali: quella di sinistra divisa in una griglia di nove per nove attorno alla '
      + 'sua gabbia, quella di destra con due colonne rigate.'],
  },
};

// #region figures: one figure heads the next column, the other the next page
// mm: a column wide and just short enough for a 17-lead band with its caption; a block wide
const CANON = [COLUMN_W, 61.8], PAGES = [BLOCK_W, 64];
const figure = (id, [width, height], placement, [caption, altText]) => ({
  id, typeId: 'figure', kind: 'svg', svg: { fileId: `${id}.svg`, width, height },
  placement, caption, altText, createdAt: 0, updatedAt: 0,
});
const resources = [
  // A float never lands above the paragraph that cites it. A column 'top' float cited in
  // the first column can still take the head of the second, on the same page.
  figure('canon', CANON, { position: 'top' }, t(CAPTIONS.canon)),
  // A page-wide 'top' float cannot, so it waits for the next page (gotcha: top-float-next-page).
  // Each band is rounded up to whole leads, so the text under it stays on the grid.
  figure('pages', PAGES, { position: 'top', span: 'page' }, t(CAPTIONS.pages)),
];
// #endregion

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
// Every face the pages paint, loaded before the first build.
const FONTS = { // text, display and label faces (Vollkorn SC ships no italic)
  Vollkorn: ['400', '400i', '700'], 'Playfair Display': ['700', '700i'],
  'Vollkorn SC': ['400', '600'],
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
await loadSvg('canon.svg', canonSvg(...CANON));
await loadSvg('pages.svg', pagesSvg(...PAGES));
const doc = await buildDocumentWithFonts({ markdown, resources, continuation }, config(),
  kitFonts(FONTS));
showPages(doc, { title: t({ en: 'A book page on a baseline grid',
  es: 'Una página de libro sobre una rejilla base',
  pt: 'Uma página de livro sobre a grade de linhas de base',
  fr: 'Une page de livre sur une grille de ligne de base',
  de: 'Eine Buchseite auf dem Grundlinienraster',
  it: 'Una pagina di libro sulla griglia della linea di base' }) });

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

## Варианты

### Скройте сетку для печати

`enabled` управляет только линиями поверх готовых страниц; вёрстка в любом случае держится сетки 13,4 пт, и ни одна строка не сдвигается.

```diff
-  baselineGrid: { enabled: true, color: col('grid') },
+  baselineGrid: { enabled: false },
```

### Посмотрите, что делает балансировка

С выключенной балансировкой на странице 11 последние восемь строк и выходные данные идут вниз по первой колонке, а вторая остаётся пустой.

```diff
-const balancing = { enabled: true };
+const balancing = { enabled: false };
```

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

- **Объект 'top' уходит на страницу после ссылки, если ему не разрешено открыть страницу со ссылкой.** По умолчанию плавающий объект не поднимается выше собственной ссылки, поэтому объект 'top' на всю ширину, вызванный на странице N, открывает страницу N+1. Задайте placement.citingPage: true у ресурса или в defaultPlacement его типа (либо layout.floatsAtCitingPage для всей книги, начиная с postext 1.25), и он откроет страницу N, а текст над ссылкой сдвинется под него, если объект укладывается в layout.maxTopFraction и строка со ссылкой остаётся на этой странице. Первую страницу главы и страницу после принудительного разрыва он не открывает: там он по-прежнему уходит на следующую, а 'auto' и 'bottom' могут занять низ страницы со ссылкой.

- Правило, по которому объект `top` не встаёт на страницу со ссылкой на него, действует для объектов во всю страницу. Объект `top` шириной в колонку может встать на ту же страницу, вверху следующей колонки, как Figure 1.1 на странице 9.
- Размеры страницы, поля и средник задаются в абсолютных единицах (мм, пт, см, дюймы). Для `em` там нет кегля, от которого считать, и сборка останавливается с ошибкой «dimensionToPx: baseFontSizePx is required for unit "em"».
- Межсловный пробел Vollkorn узок, 0,2 em, поэтому в колонке примерно на 50 знаков некоторые строки с выключкой по формату выходят разреженными или сжатыми. Образец подогнан построчно по отчёту снимка о разреженных строках; после любого изменения текста или ширины строки проверьте его снова.

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

- Рецепт: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Текст: The essay “The Secret Canon” and its Spanish version “El canon secreto”, written for this recipe: Postext Cookbook, CC-BY-4.0
- Изображения: The two drawings, made in code in the page's palette: Postext Cookbook, CC-BY-4.0
- Шрифты: Vollkorn (OFL-1.1), Playfair Display (OFL-1.1), Vollkorn SC (OFL-1.1)
- Код: MIT · Образец содержания: CC-BY-4.0

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

- [№ 016 · Испанский текст с выключкой в карманном романе](https://postext.dev/ru/cookbook/spanish-pocket-novel.md): Начало главы I «Марианелы» карманным изданием: испанские переносы, пробелы уже 1,7×, без коротких концевых строк, приподнятый инициал, карта как Figura 1. · Уровень 2 (Средний) · Художественная литература, драматургия и эссеистика
- [№ 005 · Колонтитулы по чётности страниц в книге эссе](https://postext.dev/ru/cookbook/running-heads-by-parity.md): Верхний колонтитул по чётности и роли страницы: книга слева, сокращённое название эссе справа, колонцифры в плашках на поле и внизу начальных полос. · Уровень 2 (Средний) · Художественная литература, драматургия и эссеистика
- [№ 018 · Заголовки разделов семи уровней](https://postext.dev/ru/cookbook/section-heads-field-manual.md): Разделы с номерами от 1.1 до 1.12 в янтарной капсуле по ширине номера, ещё четыре уровня под ними и седьмой, сделанный стилем заголовка. · Уровень 2 (Средний) · Руководства, путеводители и справочники
