# Страница китайской прозы на сетке 28 × 28

> «Родина» Лу Синя на странице 大32开: 28 знаков в строке, 28 строк, переносы по GB, пунктуация Kaiming и пробел между ханьцзы и латиницей.

- Версия HTML: https://postext.dev/ru/cookbook/chinese-novel-horizontal
- Рецепт № 074 · Шрифт и текст · Уровень 2 (Средний) · Форматы вывода: Canvas, PDF
- Жанры: Художественная литература, драматургия и эссеистика
- Требуется postext ≥ 1.65.0, postext-pdf ≥ 1.65.0 · проверено с 1.65.0, postext-pdf 1.65.0 · дата 2026-10-31
- Страницы: [70](https://postext.dev/cookbook/chinese-novel-horizontal/en/p01.webp?v=abd0ad35), [71](https://postext.dev/cookbook/chinese-novel-horizontal/en/p02.webp?v=abd0ad35), [72](https://postext.dev/cookbook/chinese-novel-horizontal/en/p03.webp?v=abd0ad35), [73](https://postext.dev/cookbook/chinese-novel-horizontal/en/p04.webp?v=abd0ad35), [74](https://postext.dev/cookbook/chinese-novel-horizontal/en/p05.webp?v=abd0ad35), [75](https://postext.dev/cookbook/chinese-novel-horizontal/en/p06.webp?v=abd0ad35), [76](https://postext.dev/cookbook/chinese-novel-horizontal/en/p07.webp?v=abd0ad35)
- PDF: https://postext.dev/cookbook/chinese-novel-horizontal/en/chinese-novel-horizontal.pdf?v=abd0ad35
- Открыть в Sandbox: https://postext.dev/ru/sandbox#recipe=chinese-novel-horizontal&lang=en (.postext: https://postext.dev/cookbook/chinese-novel-horizontal/en/chinese-novel-horizontal.postext)
- Последнее обновление: 2026-10-31
- Другие языки: [en](https://postext.dev/en/cookbook/chinese-novel-horizontal.md), [es](https://postext.dev/es/cookbook/chinese-novel-horizontal.md), [ca](https://postext.dev/ca/cookbook/chinese-novel-horizontal.md), [de](https://postext.dev/de/cookbook/chinese-novel-horizontal.md), [el](https://postext.dev/el/cookbook/chinese-novel-horizontal.md), [fr](https://postext.dev/fr/cookbook/chinese-novel-horizontal.md), [it](https://postext.dev/it/cookbook/chinese-novel-horizontal.md), [pt](https://postext.dev/pt/cookbook/chinese-novel-horizontal.md), [zh](https://postext.dev/zh/cookbook/chinese-novel-horizontal.md), [ja](https://postext.dev/ja/cookbook/chinese-novel-horizontal.md), [ar](https://postext.dev/ar/cookbook/chinese-novel-horizontal.md)

## Коротко

Начало рассказа Лу Синя в виде страницы китайской книги в мягкой обложке. Показывает, как уместить ровно 28 знаков в строке и 28 строк на странице по китайским правилам пунктуации.

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

Начало рассказа Лу Синя «Родина» (故乡, 1921) в том виде, как его набрало бы массовое издание материкового Китая в составе первого сборника: страница 大32开, 140 × 203 мм, полоса набора отсчитана в знаках, 28 в строке и 28 строк на странице, Noto Serif SC в 五号 (10,5 пт). Каждый абзац начинается с отступа в два знака; запятые и кавычки занимают полузнака, как в большинстве книг на материке; ни одна строка не начинается с 。 или ， и не кончается на “. Рассказ открывается на правой полосе заглавием в чёрном начертании суна. Напротив — нарисованная бахча под луной, которую вспоминает рассказчик, со словами, которые её описывают, кистевым шрифтом Ma Shan Zheng. То же для латиницы делает рецепт [«Испанский карманный роман с выключкой по формату»](https://postext.dev/ru/cookbook/spanish-pocket-novel.md).

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

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

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

```js
// script.js, строк 37–53
const cjk = {
  // The type area in characters: 28 ems wide, 28 lines of LEAD tall. page.margins become
  // minimums, and the grid centres the type area in the room they leave.
  grid: { enabled: true, charsPerLine: CHARS, linesPerPage: LINES },
  // What 'zh-Hans' gives by itself, written out so a reader can compare regions and styles.
  region: 'mainland',
  lineBreak: 'gb', // no 。，、”》 opens a line, no “《（ ends one, and no / at either end
  punctuationWidth: 'kaiming', // ，、：； quotes, brackets ½ em; 。？！ one em, ½ at a line end
  compressAdjacent: true, // idle under Kaiming (no pair tops 1.5 em); 'fullwidth' needs it
  latinSpacing: em(0.25), // 1921年, 用Noto Serif SC五号: a quarter em, none of it typed
};
const bodyText = {
  fontFamily: SONG, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  textAlign: 'justify', // spread between the characters, never between words
  firstLineIndent: em(2), indentAfterHeading: true, // two characters, every paragraph
};
```

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

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

- [Сетка знаков](https://postext.dev/ru/docs/configuration-east-asian.md#сетка-знаков): Полоса набора, заданная по-китайски: знаков в строке на строк на странице (cjk.grid). Ширина строки равна целому числу em, поля растут, чтобы поставить её по центру, а сетку можно показать на экране.
- [Разбиение на строки в китайском](https://postext.dev/ru/docs/configuration-east-asian.md#восточноазиатская-типографика): Строки китайского, японского и корейского текста разрываются между знаками, а знаки, которые не могут открывать или закрывать строку (。，」 и 「《), остаются на своём месте, со строгостью, которую задаёт cjk.lineBreak или подразумевает регион локали.
- [Ширина китайских знаков препинания](https://postext.dev/ru/docs/configuration-east-asian.md#ширина-знаков-препинания): Знаки полной ширины, кайминский стиль, половинная ширина в конце строки или везде (cjk.punctuationWidth); соседние знаки сжимаются, скобки подрезаются у края строки, а если так принято в издательстве, знаки выносятся за край набора.

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

- [Выключка за счёт знаков](https://postext.dev/ru/docs/justification.md#китайский-японский-и-корейский)
- [Отбивка между китайским и латиницей](https://postext.dev/ru/docs/configuration-east-asian.md#пробел-между-иероглифами-и-латиницей)
- [Китайские, японские и корейские шрифты](https://postext.dev/ru/docs/configuration-pdf-output.md#шрифты-для-китайского-японского-и-корейского)
- [Отступы, выключка и отбивка абзацев](https://postext.dev/ru/docs/configuration-text.md#основной-текст)
- [Шрифт основного текста](https://postext.dev/ru/docs/configuration-text.md#основной-текст)
- [Колонтитулы и колонцифры](https://postext.dev/ru/docs/configuration-headers-footers.md#верхние-и-нижние-колонтитулы)
- [Оформленные начальные полосы](https://postext.dev/ru/docs/configuration-headings.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-page-layout.md#зеркальные-поля)
- [Стили абзацев](https://postext.dev/ru/docs/configuration-styles.md#стили-абзацев)
- [Закладки PDF](https://postext.dev/ru/docs/configuration-fonts-colors-viewers.md#создание-pdf-конфигурация)
- [Цвет бумаги](https://postext.dev/ru/docs/configuration-page-layout.md#страница)
- [Экспорт в PDF](https://postext.dev/ru/docs/configuration-pdf-output.md#создание-pdf)
- [Шрифты, встроенные в PDF](https://postext.dev/ru/docs/configuration-pdf-output.md#зачем-нужен-провайдер-шрифтов)
- [Рисунки и таблицы как ресурсы](https://postext.dev/ru/docs/document-format-resources.md#ресурсы)
- [Колонтитулы разделов](https://postext.dev/ru/docs/configuration-styles.md#стили-заголовков)

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

- [`bodyText`](https://postext.dev/ru/docs/configuration-text.md#основной-текст), [`cjk`](https://postext.dev/ru/docs/configuration-east-asian.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#стили-абзацев)

**API**

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

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

- Noto Serif SC (OFL-1.1), Noto Sans SC (OFL-1.1), Ma Shan Zheng (OFL-1.1)

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

### 1 · Страница, отсчитанная в знаках

Код приведён выше, в разделе [«Короткий ответ»](https://postext.dev/ru/cookbook/chinese-novel-horizontal.md#короткий-ответ). `cjk.grid` делает ширину строки равной 28 em от `bodyText.fontSize` (294 пт, 103,7 мм), а полосу набора — 28 строкам `lineHeight` (462 пт, 163 мм) и подгоняет под них поля, поэтому полная строка ханьцзы вмещает ровно 28 знаков, а каждая полная страница кончается на одной и той же строке ([сетка знаков](https://postext.dev/ru/docs/configuration-east-asian.md#сетка-знаков)). Пять настроек под сеткой `locale: 'zh-Hans'` и так выставляет сам; они выписаны, чтобы их можно было менять по одной, хотя `compressAdjacent` ничего не меняет, пока `punctuationWidth` не равен `'fullwidth'`: в режиме Kaiming два соседних знака и так не занимают больше 1,5 em. На [странице 71](https://postext.dev/cookbook/chinese-novel-horizontal/en/p02.webp?v=abd0ad35) заключительная 。 абзаца не помещается, а открыть строку ей запрещают правила начала строки (любой уровень `lineBreak`, кроме `'none'`; `'gb'` добавляет косую черту). Строка вбирает её, набрав 。 после 事 вполовину ширины (вгонка): 事。宏 сближается, и абзац не переходит на новую строку ([ширина знаков препинания](https://postext.dev/ru/docs/configuration-east-asian.md#ширина-знаков-препинания)). Короткие строки растягиваются между знаками, а не между словами, и на этих страницах не больше чем на 0,05 em ([китайский, японский и корейский](https://postext.dev/ru/docs/justification.md#китайский-японский-и-корейский)).

![Opening page 71: 故乡.](https://postext.dev/cookbook/chinese-novel-horizontal/en/p02.webp?v=abd0ad35)

*Страница 71: последние строки абзаца. 事。宏 сближено, чтобы 看。 осталось в строке, а не открывало новую.*

### 2 · Страница 大32开 с увеличенным верхним полем

```js
// script.js, строк 57–62
const page = {
  width: mm(TRIM.width), height: mm(TRIM.height), dpi: 150, backgroundColor: col('paper'),
  // 22 + 18 mm leave 163 mm, exactly 28 lines of 16.5 pt; 18 mm a side leave the 103.7 mm
  // measure 0.3 mm to share. A grid that no longer fits is cut down (cjkGridClamped).
  margins: { top: mm(22), bottom: mm(18), left: mm(18), right: mm(18), mirror: true },
};
```

При включённой сетке поля — это минимумы: сетка ставит полосу набора в оставленное ими место, а остаток делит. 22 и 18 мм оставляют ровно 163 мм, поэтому верхнее поле и остаётся на 4 мм больше нижнего, как принято в китайских книгах; 18 мм с каждого бока дают делить 0,3 мм. Если попросить знаков или строк больше, чем помещается, сетка урежется до того, что помещается, с предупреждением `cjkGridClamped`; кегль и интерлиньяж останутся как заданы.

### 3 · Заглавие спущено на целое число строк

```js
// script.js, строк 66–84
const SINK = 8; // lines of LEAD: a whole number, so the text under it keeps to the grid
const centred = (y) => ({ anchor: { to: 'container', edge: 'top' }, offset: { y: mm(y) } });
const opener = {
  enabled: true,
  minHeight: pt(SINK * LEAD),
  slot: { elements: [
    // The spacing after the last character is advance, not ink: the title stays centred.
    { kind: 'text', id: 'title', content: '{titleText}', fontFamily: SONG, fontWeight: 900,
      fontSize: pt(46), letterSpacing: pt(23), lineHeight: 1.1, color: col('ink'),
      align: 'center', placement: centred(6) },
    { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(1.2),
      color: col('night'), placement: { ...centred(30), size: { width: mm(8) } } },
    { kind: 'text', id: 'author', content: '{author}', fontFamily: HEI, fontSize: pt(10.5),
      letterSpacing: pt(5), color: col('ink'), align: 'center', placement: centred(34) },
  ] },
};
// parity 'any': a story opens on the next page, left or right.
const chapter = { level: 1, breakBefore: { enabled: true, parity: 'any' },
  marginTop: pt(0), marginBottom: pt(0), advancedDesign: opener };
```

`minHeight` — восемь строк по 16,5 пт, поэтому текст под заглавием начинается с девятой строки сетки, на тех же базовых линиях, что и на всех страницах. Трекинг в 23 пт даёт полузнака между 故 и 乡, обычную разрядку заглавия из двух знаков; при центрировании строки Postext не учитывает разрядку после последнего знака, и заглавие стоит на оси страницы ([стили заголовков](https://postext.dev/ru/docs/configuration-styles.md#стили-заголовков)).

### 4 · Книга на левой полосе, рассказ на правой

```js
// script.js, строк 88–107
const HEAD_Y = 11; // mm from the top edge to the heads; the hairline 5 mm lower
const label = { fontFamily: HEI, fontSize: pt(8), color: col('muted'), pages: 'body' };
const at = (edge, x, y = HEAD_Y) => ({ anchor: { to: 'page', edge },
  offset: { x: mm(x), y: mm(y) } });
const header = { elements: [
  { kind: 'text', id: 'verso-folio', content: '{pageNumber}', parity: 'even', ...label,
    placement: at('top-left', SIDE) },
  { kind: 'text', id: 'verso-book', content: '{title}', parity: 'even', ...label,
    letterSpacing: pt(4), placement: at('top', 0) },
  { kind: 'text', id: 'recto-story', content: '{chapterTitle}', parity: 'odd', ...label,
    letterSpacing: pt(4), placement: at('top', 0) },
  { kind: 'text', id: 'recto-folio', content: '{pageNumber}', parity: 'odd', ...label,
    placement: at('top-right', -SIDE) },
  { kind: 'rule', id: 'hairline', direction: 'horizontal', thickness: pt(0.5), color: col('rule'),
    pages: 'body', placement: { ...at('top-left', SIDE, HEAD_Y + 5), size: { width: mm(MEASURE) } },
  },
] };
// The opener has no head: its folio drops to the foot, centred under the text.
const footer = { elements: [{ kind: 'text', id: 'drop-folio', content: '{pageNumber}',
  ...label, pages: 'opener', align: 'center', placement: at('bottom', 0, -10) }] };
```

В книгах прозы материкового Китая над левыми полосами стоит заглавие книги, над правыми — рассказа, по центру, колонцифра у наружного края, под ними волосная линейка. `pages: 'body'` не пускает колонтитулы на начальную полосу и на иллюстрацию, а начальная полоса получает колонцифру внизу. Колонтитулы набраны Noto Sans SC, шрифтом хэй, в 8 пт: мелко, но это уже другой голос, чем сун основного текста.

### 5 · Иллюстрация на весь лист

```js
// script.js, строк 111–143
// The plate, a painting: a JPEG in assets/ cut to the 140 × 203 mm trim, declared at its pixels.
const resources = [{
  id: 'moon', typeId: 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: 'plate-1120.jpg', format: 'jpeg', width: 1120, height: 1624 },
  altText: t({
    en: 'A golden full moon in a deep blue sky over a strip of sea. On the sand below, among '
      + 'rows of striped watermelons, a boy with a silver collar stabs a steel fork at the '
      + 'sand ahead of him, and the small animal he aimed at runs off between his legs.',
    es: 'Una luna llena dorada en un cielo azul oscuro sobre una franja de mar. En la arena, '
      + 'entre hileras de sandías rayadas, un muchacho con un aro de plata al cuello clava una '
      + 'horquilla de acero en la arena, delante de él, y el animalillo al que apuntaba huye '
      + 'entre sus piernas.',
  }),
}];
const quote = { fontFamily: KAI, fontSize: pt(14), lineHeight: 1.5, color: col('paper') };
// # 月下的瓜地 {style="plate" line1="…" line2="…" line3="…"}: a page with no head or folio.
// 'page' spans the design over the sheet: a heading's design in the column is cut at its foot.
const plate = {
  id: 'plate', span: 'page', runningChapter: false, toc: false, // out of the PDF outline
  breakBefore: { enabled: true, parity: 'any' }, // (gotcha: style-inherits-break)
  header: { elements: [] }, footer: { elements: [] },
  advancedDesign: { enabled: true, slot: { elements: [
    { kind: 'image', id: 'picture', resourceId: 'moon', placement: { // the whole trim
      anchor: { to: 'bleed', edge: 'top-left' },
      size: { width: mm(TRIM.width), height: mm(TRIM.height) } } },
    { kind: 'text', id: 'line1', content: '{attr.line1}', ...quote, align: 'left',
      placement: { anchor: { to: 'container', edge: 'top-left' }, offset: { y: mm(2) } } },
    { kind: 'text', id: 'line2', content: '{attr.line2}', ...quote, align: 'left',
      placement: { anchor: { to: '#line1', edge: 'below' } } },
    { kind: 'text', id: 'line3', content: '{attr.line3}', ...quote, align: 'left',
      placement: { anchor: { to: '#line2', edge: 'below' } } },
  ] } },
};
```

Иллюстрация принадлежит отдельному заголовку `# 月下的瓜地 {style="plate" …}`, стиль которого рисует страницу и убирает с неё колонтитул и колонцифру. Ей нужно `span: 'page'`: оформление заголовка, остающееся в колонке, обрезается по её нижнему краю, за 18 мм до обреза. `runningChapter: false` вместе с `toc: false` не пускает её в оглавление PDF, которое открывается на 故乡. Три строки цитаты — три атрибута и три текстовых элемента: у текста в оформлении собственный разбивщик строк, который не знает ширин китайской пунктуации; в разбитых вручную строках заодно нет запятых, как обычно и бывает в китайском акцидентном наборе.

### 6 · Латиница и цифры в китайском тексте

```js
// script.js, строк 147–153
const paragraphStyles = [
  // 小五 (9 pt) nudged to 9.1875 pt: 32 of its characters fill the 28-em measure exactly.
  { id: 'note', fontSize: pt((CHARS * BODY) / 32), lineHeight: pt(LEAD), color: col('ink'),
    firstLineIndent: em(2), marginTop: pt(LEAD) }, // on the grid, a line below the text
  { id: 'colophon', fontFamily: HEI, fontSize: pt(7), lineHeight: pt(11), color: col('muted'),
    textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD / 2) },
];
```

В примечании и колофоне на [странице 76](https://postext.dev/cookbook/chinese-novel-horizontal/en/p07.webp?v=abd0ad35) цифры и латинские имена встречаются с ханьцзы. `latinSpacing` ставит четверть em всюду, где они соприкасаются, как в 1921年 из примечания и 用Noto Serif SC五号 из колофона, набранных вовсе без пробела ([пробел между ханьцзы и латиницей](https://postext.dev/ru/docs/configuration-east-asian.md#пробел-между-иероглифами-и-латиницей)); в строке с выключкой по формату первым растёт он, до половины em. Примечание набрано в 9,1875 пт, а не в 9 пт 小五, чтобы 32 его знака заполнили формат: при 9 пт в каждой строке оставалось две трети em, и они уходили в эти пробелы. В Markdown имена шрифтов соединены неразрывными пробелами (U+00A0), которых пробел между ханьцзы и латиницей не трогает: с обычными пробелами флаговые строки колофона разрывали Noto Sans / SC.

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

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

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

### script.js

```js
// ═══ Postext Cookbook · Nº 074 · A Chinese novel page on a 28 × 28 grid ════════════
// https://postext.dev/en/cookbook/chinese-novel-horizontal
// Code: MIT · Text: Lu Xun, 故乡 (1921), public domain, zh.wikisource · Plate: diffusion models
// Fonts: Noto Serif SC, Noto Sans SC, Ma Shan Zheng (SIL OFL 1.1) · Needs postext ≥ 1.65.0
import {
  buildDocument, withLoadedFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'chinese-novel-horizontal';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// The night of the story's memory, and ink on a cream paper.
const palette = {
  ink: '#1f1c19', // text: a warm near-black
  night: '#1d3150', // the accent: the deep blue of the plate's sky, the opener's rule
  rule: '#c9c1b2', // the hairline under the running heads
  muted: '#6a645b', // running heads, folios, the colophon
  paper: '#fbf8f1', // a cream book paper
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'night (defaults)', value: { hex: palette.night, model: 'hex' } },
];
const SONG = 'Noto Serif SC'; // 宋: the text, and the title in its black weight
const HEI = 'Noto Sans SC'; // 黑: running heads, folios, the author, the colophon
const KAI = 'Ma Shan Zheng'; // 楷: a brush regular script for the plate's quotation
const [BODY, LEAD] = [10.5, 16.5]; // pt: 五号 on a 6 pt line gap, the grid's pitch
const [CHARS, LINES] = [28, 28];
const TRIM = { width: 140, height: 203 }; // mm: 大32开
const MEASURE = (CHARS * BODY * 25.4) / 72; // 103.7 mm: 28 ems of 五号
const SIDE = (TRIM.width - MEASURE) / 2; // 18.1 mm: the grid centres the measure

// #region answer: 28 characters × 28 lines of 五号, mainland line breaks and Kaiming marks
const cjk = {
  // The type area in characters: 28 ems wide, 28 lines of LEAD tall. page.margins become
  // minimums, and the grid centres the type area in the room they leave.
  grid: { enabled: true, charsPerLine: CHARS, linesPerPage: LINES },
  // What 'zh-Hans' gives by itself, written out so a reader can compare regions and styles.
  region: 'mainland',
  lineBreak: 'gb', // no 。，、”》 opens a line, no “《（ ends one, and no / at either end
  punctuationWidth: 'kaiming', // ，、：； quotes, brackets ½ em; 。？！ one em, ½ at a line end
  compressAdjacent: true, // idle under Kaiming (no pair tops 1.5 em); 'fullwidth' needs it
  latinSpacing: em(0.25), // 1921年, 用Noto Serif SC五号: a quarter em, none of it typed
};
const bodyText = {
  fontFamily: SONG, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  textAlign: 'justify', // spread between the characters, never between words
  firstLineIndent: em(2), indentAfterHeading: true, // two characters, every paragraph
};
// #endregion

// #region page: 大32开 with a head margin larger than the foot
const page = {
  width: mm(TRIM.width), height: mm(TRIM.height), dpi: 150, backgroundColor: col('paper'),
  // 22 + 18 mm leave 163 mm, exactly 28 lines of 16.5 pt; 18 mm a side leave the 103.7 mm
  // measure 0.3 mm to share. A grid that no longer fits is cut down (cjkGridClamped).
  margins: { top: mm(22), bottom: mm(18), left: mm(18), right: mm(18), mirror: true },
};
// #endregion

// #region opener: the title in the Song face's black weight, sunk 8 lines
const SINK = 8; // lines of LEAD: a whole number, so the text under it keeps to the grid
const centred = (y) => ({ anchor: { to: 'container', edge: 'top' }, offset: { y: mm(y) } });
const opener = {
  enabled: true,
  minHeight: pt(SINK * LEAD),
  slot: { elements: [
    // The spacing after the last character is advance, not ink: the title stays centred.
    { kind: 'text', id: 'title', content: '{titleText}', fontFamily: SONG, fontWeight: 900,
      fontSize: pt(46), letterSpacing: pt(23), lineHeight: 1.1, color: col('ink'),
      align: 'center', placement: centred(6) },
    { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(1.2),
      color: col('night'), placement: { ...centred(30), size: { width: mm(8) } } },
    { kind: 'text', id: 'author', content: '{author}', fontFamily: HEI, fontSize: pt(10.5),
      letterSpacing: pt(5), color: col('ink'), align: 'center', placement: centred(34) },
  ] },
};
// parity 'any': a story opens on the next page, left or right.
const chapter = { level: 1, breakBefore: { enabled: true, parity: 'any' },
  marginTop: pt(0), marginBottom: pt(0), advancedDesign: opener };
// #endregion

// #region heads: the book on the verso, the story on the recto, a hairline under both
const HEAD_Y = 11; // mm from the top edge to the heads; the hairline 5 mm lower
const label = { fontFamily: HEI, fontSize: pt(8), color: col('muted'), pages: 'body' };
const at = (edge, x, y = HEAD_Y) => ({ anchor: { to: 'page', edge },
  offset: { x: mm(x), y: mm(y) } });
const header = { elements: [
  { kind: 'text', id: 'verso-folio', content: '{pageNumber}', parity: 'even', ...label,
    placement: at('top-left', SIDE) },
  { kind: 'text', id: 'verso-book', content: '{title}', parity: 'even', ...label,
    letterSpacing: pt(4), placement: at('top', 0) },
  { kind: 'text', id: 'recto-story', content: '{chapterTitle}', parity: 'odd', ...label,
    letterSpacing: pt(4), placement: at('top', 0) },
  { kind: 'text', id: 'recto-folio', content: '{pageNumber}', parity: 'odd', ...label,
    placement: at('top-right', -SIDE) },
  { kind: 'rule', id: 'hairline', direction: 'horizontal', thickness: pt(0.5), color: col('rule'),
    pages: 'body', placement: { ...at('top-left', SIDE, HEAD_Y + 5), size: { width: mm(MEASURE) } },
  },
] };
// The opener has no head: its folio drops to the foot, centred under the text.
const footer = { elements: [{ kind: 'text', id: 'drop-folio', content: '{pageNumber}',
  ...label, pages: 'opener', align: 'center', placement: at('bottom', 0, -10) }] };
// #endregion

// #region plate: the moonlit melon field faces the opener, the quotation set in Kai
// The plate, a painting: a JPEG in assets/ cut to the 140 × 203 mm trim, declared at its pixels.
const resources = [{
  id: 'moon', typeId: 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: 'plate-1120.jpg', format: 'jpeg', width: 1120, height: 1624 },
  altText: t({
    en: 'A golden full moon in a deep blue sky over a strip of sea. On the sand below, among '
      + 'rows of striped watermelons, a boy with a silver collar stabs a steel fork at the '
      + 'sand ahead of him, and the small animal he aimed at runs off between his legs.',
    es: 'Una luna llena dorada en un cielo azul oscuro sobre una franja de mar. En la arena, '
      + 'entre hileras de sandías rayadas, un muchacho con un aro de plata al cuello clava una '
      + 'horquilla de acero en la arena, delante de él, y el animalillo al que apuntaba huye '
      + 'entre sus piernas.',
  }),
}];
const quote = { fontFamily: KAI, fontSize: pt(14), lineHeight: 1.5, color: col('paper') };
// # 月下的瓜地 {style="plate" line1="…" line2="…" line3="…"}: a page with no head or folio.
// 'page' spans the design over the sheet: a heading's design in the column is cut at its foot.
const plate = {
  id: 'plate', span: 'page', runningChapter: false, toc: false, // out of the PDF outline
  breakBefore: { enabled: true, parity: 'any' }, // (gotcha: style-inherits-break)
  header: { elements: [] }, footer: { elements: [] },
  advancedDesign: { enabled: true, slot: { elements: [
    { kind: 'image', id: 'picture', resourceId: 'moon', placement: { // the whole trim
      anchor: { to: 'bleed', edge: 'top-left' },
      size: { width: mm(TRIM.width), height: mm(TRIM.height) } } },
    { kind: 'text', id: 'line1', content: '{attr.line1}', ...quote, align: 'left',
      placement: { anchor: { to: 'container', edge: 'top-left' }, offset: { y: mm(2) } } },
    { kind: 'text', id: 'line2', content: '{attr.line2}', ...quote, align: 'left',
      placement: { anchor: { to: '#line1', edge: 'below' } } },
    { kind: 'text', id: 'line3', content: '{attr.line3}', ...quote, align: 'left',
      placement: { anchor: { to: '#line2', edge: 'below' } } },
  ] } },
};
// #endregion

// #region styles: the editor's note in 小五 Song, the colophon in Hei
const paragraphStyles = [
  // 小五 (9 pt) nudged to 9.1875 pt: 32 of its characters fill the 28-em measure exactly.
  { id: 'note', fontSize: pt((CHARS * BODY) / 32), lineHeight: pt(LEAD), color: col('ink'),
    firstLineIndent: em(2), marginTop: pt(LEAD) }, // on the grid, a line below the text
  { id: 'colophon', fontFamily: HEI, fontSize: pt(7), lineHeight: pt(11), color: col('muted'),
    textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD / 2) },
];
// #endregion

const config = () => ({
  locale: 'zh-Hans', // written out, never LANG (gotcha: cjk-locale-tag)
  colorPalette, page, layout: { layoutType: 'single' }, cjk, bodyText,
  // The designs paint the titles; weight 400 keeps the heading blocks in the loaded face.
  headings: { fontFamily: SONG, fontWeight: 400, levels: [chapter] },
  headingStyles: [plate], paragraphStyles, header, footer,
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "呐喊"
author: "鲁迅"
---

# 月下的瓜地 {style="plate" line1="深蓝的天空中挂着一轮金黄的圆月" line2="下面是海边的沙地" line3="都种着一望无际的碧绿的西瓜"}

# 故乡

我冒了严寒，回到相隔二千余里，别了二十余年的故乡去。

时候既然是深冬；渐近故乡时，天气又阴晦了，冷风吹进船舱中，呜呜的响，从篷隙向外一望，苍黄的天底下，远近横着几个萧索的荒村，没有一些活气。我的心禁不住悲凉起来了。

阿！这不是我二十年来时时记得的故乡？

我所记得的故乡全不如此。我的故乡好得多了。但要我记起他的美丽，说出他的佳处来，却又没有影像，没有言辞了。仿佛也就如此。于是我自己解释说：故乡本也如此，——虽然没有进步，也未必有如我所感的悲凉，这只是我自己心情的改变罢了，因为我这次回乡，本没有什么好心绪。

我这次是专为了别他而来的。我们多年聚族而居的老屋，已经公同卖给别姓了，交屋的期限，只在本年，所以必须赶在正月初一以前，永别了熟识的老屋，而且远离了熟识的故乡，搬家到我在谋食的异地去。

第二日清早晨我到了我家的门口了。瓦楞上许多枯草的断茎当风抖着，正在说明这老屋难免易主的原因。几房的本家大约已经搬走了，所以很寂静。我到了自家的房外，我的母亲早已迎着出来了，接着便飞出了八岁的侄儿宏儿。

我的母亲很高兴，但也藏着许多凄凉的神情，教我坐下，歇息，喝茶，且不谈搬家的事。宏儿没有见过我，远远的对面站着只是看。

但我们终于谈到搬家的事。我说外间的寓所已经租定了，又买了几件家具，此外须将家里所有的木器卖去，再去增添。母亲也说好，而且行李也略已齐集，木器不便搬运的，也小半卖去了，只是收不起钱来。

“你休息一两天，去拜望亲戚本家一回，我们便可以走了。”母亲说。

“是的。”

“还有闰土，他每到我家来时，总问起你，很想见你一回面。我已经将你到家的大约日期通知他，他也许就要来了。”

这时候，我的脑里忽然闪出一幅神异的图画来：深蓝的天空中挂着一轮金黄的圆月，下面是海边的沙地，都种着一望无际的碧绿的西瓜，其间有一个十一二岁的少年，项带银圈，手捏一柄钢叉，向一匹猹尽力的刺去，那猹却将身一扭，反从他的胯下逃走了。

这少年便是闰土。我认识他时，也不过十多岁，离现在将有三十年了；那时我的父亲还在世，家景也好，我正是一个少爷。那一年，我家是一件大祭祀的值年。这祭祀，说是三十多年才能轮到一回，所以很郑重；正月里供祖像，供品很多，祭器很讲究，拜的人也很多，祭器也很要防偷去。我家只有一个忙月（我们这里给人做工的分三种：整年给一定人家做工的叫长年；按日给人做工的叫短工；自己也种地，只在过年过节以及收租时候来给一定的人家做工的称忙月），忙不过来，他便对父亲说，可以叫他的儿子闰土来管祭器的。

我的父亲允许了；我也很高兴，因为我早听到闰土这名字，而且知道他和我仿佛年纪，闰月生的，五行缺土，所以他的父亲叫他闰土。他是能装弶捉小鸟雀的。

我于是日日盼望新年，新年到，闰土也就到了。好容易到了年末，有一日，母亲告诉我，闰土来了，我便飞跑的去看。他正在厨房里，紫色的圆脸，头戴一顶小毡帽，颈上套一个明晃晃的银项圈，这可见他的父亲十分爱他，怕他死去，所以在神佛面前许下愿心，用圈子将他套住了。他见人很怕羞，只是不怕我，没有旁人的时候，便和我说话，于是不到半日，我们便熟识了。

我们那时候不知道谈些什么，只记得闰土很高兴，说是上城之后，见了许多没有见过的东西。

第二日，我便要他捕鸟。他说：

“这不能。须大雪下了才好。我们沙地上，下了雪，我扫出一块空地来，用短棒支起一个大竹匾，撒下秕谷，看鸟雀来吃时，我远远地将缚在棒上的绳子只一拉，那鸟雀就罩在竹匾下了。什么都有：稻鸡、角鸡、鹁鸪、蓝背……”

我于是又很盼望下雪。

闰土又对我说：

“现在太冷，你夏天到我们这里来。我们日里到海边检贝壳去，红的绿的都有，鬼见怕也有，观音手也有，晚上我和爹管西瓜去，你也去。”

“管贼么？”

“不是。走路的人口渴了摘一个瓜吃，我们这里是不算偷的。要管的是獾猪、刺猬、猹。月亮地下，你听，啦啦的响了，猹在咬瓜了。你便捏了胡叉，轻轻地走去……”

我那时并不知道这所谓猹的是怎么一件东西——便是现在也没有知道——只是无端的觉得状如小狗而很凶猛。

“他不咬人么？”

“有胡叉呢。走到了，看见猹了，你便刺。这畜生很伶俐，倒向你奔来，反从胯下窜了。他的皮毛是油一般的滑。……”

我素不知道天下有这许多新鲜事：海边有如许五色的贝壳；西瓜有这样危险的经历，我先前单知道他在水果店里出卖罢了。

“我们沙地里，潮汛要来的时候，就有许多跳鱼儿只是跳，都有青蛙似的两个脚。……”

阿！闰土的心里有无穷无尽的希奇的事，都是我往常的朋友所不知道的。他们不知道一些事，闰土在海边时，他们都和我一样只看见院子里高墙上的四角的天空。

可惜正月过去了，闰土须回家里去，我急得大哭，他也躲到厨房里，哭着不肯出门，但终于被他父亲带走了。他后来还托他的父亲带给我一包贝壳和几枝很好看的鸟毛，我也曾送他一两次东西，但从此没有再见面。

现在我的母亲提起了他，我这儿时的记忆，忽而全都闪电似的苏生过来，似乎看到了我的美丽的故乡了。我应声说：

“这好极！他，——怎样？……”

“他？……他景况也很不如意……”母亲说着，便向房外看，“这些人又来了。说是买木器，顺手也就随便拿走的，我得去看看。”

母亲站起身，出去了。门外有几个女人的声音，我便招宏儿走近面前，和他闲话：问他可会写字，可愿意出门。

“我们坐火车去么？”

“我们坐火车去。”

“船呢？”

“先坐船，……”

“哈！这模样了！胡子这么长了！”一种尖利的怪声突然大叫起来。

我吃了一吓，赶忙抬起头，却见一个凸颧骨，薄嘴唇，五十岁上下的女人站在我面前，两手搭在髀间，没有系裙，张着两脚，正像一个画图仪器里细脚伶仃的圆规。

我愕然了。

“不认识了么？我还抱你咧！”

我愈加愕然了。幸而我的母亲也就进来，从旁说：

“他多年出门，统忘却了。你该记得罢，”便向着我说，“这是斜对门的杨二嫂，……开豆腐店的。”

哦，我记得了。我孩子时候，在斜对门的豆腐店里确乎终日坐着一个杨二嫂，人都叫伊“豆腐西施”。但是擦着白粉，颧骨没有这么高，嘴唇也没有这么薄。而且终日坐着，我也从没有见过这圆规式的姿势。那时人说：因为伊，这豆腐店的买卖非常好。但这大约因为年龄的关系，我却并未蒙着一毫感化，所以竟完全忘却了。然而圆规很不平，显出鄙夷的神色，仿佛嗤笑法国人不知道拿破仑，美国人不知道华盛顿似的，冷笑说：

“忘了？这真是贵人眼高。……”

“那有这事……我……”我惶恐着，站起来说。

“那么，我对你说。迅哥儿，你阔了，搬动又笨重，你还要什么这些破烂木器，让我拿去罢。我们小户人家，用得着。”

“我并没有阔哩。我须卖了这些，再去……”

“阿呀呀，你放了道台了，还说不阔？你现在有三房姨太太；出门便是八抬的大轿，还说不阔？吓，什么都瞒不过我。”

我知道无话可说了，便闭了口，默默的站着。

“阿呀阿呀，真是愈有钱，便愈是一毫不肯放松，愈是一毫不肯放松，便愈有钱……”圆规一面愤愤的回转身，一面絮絮的说，慢慢向外走，顺便将我母亲的一副手套塞在裤腰里，出去了。

此后又有近处的本家和亲戚来访问我。我一面应酬，偷空便收拾些行李，这样的过了三四天。

一日是天气很冷的午后，我吃过午饭，坐着喝茶，觉得外面有人进来了，便回头去看。我看时，不由的非常出惊，慌忙站起身，迎着走去。

这来的便是闰土。虽然我一见便知道是闰土，但又不是我这记忆上的闰土了。他身材增加了一倍；先前的紫色的圆脸，已经变作灰黄，而且加上了很深的皱纹；眼睛也像他父亲一样，周围都肿得通红，这我知道，在海边种地的人，终日吹着海风，大抵是这样的。他头上是一顶破毡帽，身上只一件极薄的棉衣，浑身瑟索着；手里提着一个纸包和一枝长烟管，那手也不是我所记得的红活圆实的手，却又粗又笨而且开裂，像是松树皮了。

我这时很兴奋，但不知道怎么说才好，只是说：

“阿！闰土哥，——你来了？……”

我接着便有许多话，想要连珠一般涌出：角鸡、跳鱼儿、贝壳、猹，……但又总觉得被什么挡着似的。单在脑里面回旋，吐不出口外去。

他站住了，脸上现出欢喜和凄凉的神情；动着嘴唇，却没有作声。他的态度终于恭敬起来了，分明的叫道：

“老爷！……”

我似乎打了一个寒噤；我就知道，我们之间已经隔了一层可悲的厚障壁了。我也说不出话。

:::paragraphs{style="note"}
（本篇作于1921年1月，同年5月1日发表于《新青年》第9卷第1号，1923年8月收入小说集《呐喊》。这里节选前半篇，至闰土来访为止。文字据1948年版《鲁迅全集》第一卷，改排为简体横排：引号『』改作“”，“馀”“偸”改作“余”“偷”。）
:::

:::paragraphs{style="colophon"}
本书正文用Noto Serif SC五号字排，每行28字，每面28行；书眉、页码和版本说明用Noto Sans SC，篇首题句用Ma Shan Zheng，均为SIL OFL字体。篇首插图为一幅绘画。
:::

:::paragraphs{style="colophon"}
Lu Xun, 故乡 (My Old Home), 1921: the first half of the story · Text: public domain, from zh.wikisource · Plate: a painting.
:::
`; // content.<lang>.md, inlined by the Cookbook

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { // every face the pages use, loaded before the build
  'Noto Serif SC': ['400', '900'], // SONG: the text; the title
  'Noto Sans SC': ['400'], // HEI: running heads, folios, the author, the colophon
  'Ma Shan Zheng': ['400'], // KAI: the plate's quotation
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
// Each voice loads the files of the characters it sets (gotcha: cjk-fonts-slices).
const part = (re) => markdown.match(re)?.[0] ?? '';
const colophon = part(/:::paragraphs\{style="colophon"\}[\s\S]*$/);
await loadFonts(FONTS, markdown);
await loadCjkFonts({ [SONG]: ['400'] }, markdown);
await loadCjkFonts({ [SONG]: ['900'] }, '故乡');
await loadCjkFonts({ [HEI]: ['400'] }, `呐喊故乡鲁迅0123456789${colophon}`);
await loadCjkFonts({ [KAI]: ['400'] }, part(/^# .*style="plate".*$/m));
await loadImage(resources[0].bitmap.fileId, asset(resources[0].bitmap.fileId));
// The plate is page 70 of the book, a verso: folios and parity follow the book.
const continuation = { pageIndexOffset: 69, pageNumbering: { startAt: 70 } };
const doc = await withLoadedFonts(
  () => buildDocument({ markdown, resources, continuation }, config()),
  { ...kitFonts(FONTS), text: markdown });
showPages(doc, { title: t({ en: 'A Chinese novel page on a 28 × 28 grid',
  es: 'Una página de novela china en una retícula de 28 × 28' }) });
offerPdf(() => renderToPdf(doc, { fontProvider: cjkPdfProvider, resourceBytes: imageBytes }),
  `${RECIPE}.pdf`);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ─── Kit · cjk v2 ── Chinese, Japanese and Korean books · postext.dev/cookbook
// Fontsource ships a CJK family as about a hundred files per weight, each
// declared in its stylesheet with the unicode-range it covers. The screen
// loads the files the sample touches; the PDF gets the same files for the
// characters its pages set in each face, and embeds each as a subset.
// A book bound on the right (vertical text) is shown with its spreads
// mirrored: page 1 alone on the left of the spine, then [3 | 2].

/** The files of a Fontsource face, read from its stylesheet: { url, range,
 *  ranges }, the last declared first (the order the browser tries them in). */
function cjkSlices(family, weight, style) {
  cjkSlices.cache ??= new Map();
  const id = fontsourceId(family);
  const css = `${id}/${weight}${style === 'italic' ? '-italic' : ''}.css`;
  if (!cjkSlices.cache.has(css)) {
    let at;
    cjkSlices.cache.set(css, fontsourceAt(id).then((a) => fetch(at = a + css.slice(id.length + 1)))
      .then((res) => {
        if (!res.ok) throw new Error(`Fontsource has no ${family} ${weight} ${style} (${res.status})`);
        return res.text();
      })
      .then((text) => [...text.matchAll(/@font-face\s*{([^}]*)}/g)].map(([, rule]) => {
        const range = /unicode-range:\s*([^;]+);/.exec(rule)?.[1].trim() ?? 'U+0-10FFFF';
        const ranges = range.split(',').map((part) => {
          const [lo, hi = lo] = part.trim().slice(2).split('-');
          return [parseInt(lo, 16), parseInt(hi, 16)];
        });
        return { url: new URL(/url\(([^)]+?\.woff2)\)/.exec(rule)[1], at).href, range, ranges };
      }).reverse()));
  }
  return cjkSlices.cache.get(css);
}

/** The file of `slices` the screen sets code point `cp` in, if any: the
 *  last one loadCjkFonts adds whose range holds it. A numbered file that
 *  repeats a letter of latin is added after latin, and wins it. */
function cjkSliceFor(slices, cp) {
  const holds = (slice) => slice.ranges.some(([lo, hi]) => cp >= lo && cp <= hi);
  return slices.reduce((last, slice) => (holds(slice) ? slice : last), undefined);
}

/** Whether Fontsource serves `family` as a Chinese, Japanese or Korean
 *  family (its subsets name the script). Fails when the API does not
 *  answer: a CJK face taken for a Latin one would paint in a system face. */
async function isCjkFamily(family) {
  const meta = await fontsourceMeta(family);
  if (!meta) throw new Error(`api.fontsource.org did not describe ${family}: reload to try again`);
  return !!meta.subsets?.some((subset) => /^(chinese|japanese|korean)/.test(subset));
}

/** faces = { 'Noto Serif TC': ['400', '700'] }, as for loadFonts: the
 *  whole FONTS object may be passed, its other families are left to
 *  loadFonts. Adds one FontFace per file of each CJK face with its
 *  unicodeRange, then loads the files `text` touches. `text` is what the
 *  faces set: the sample for the text face; a book in several voices calls
 *  it once per voice (loadCjkFonts({ 'LXGW WenKai TC': ['400'] }, quotes)),
 *  so the heading and quotation faces fetch and check only their own
 *  characters. Fails when a character of `text` is in no file of a face.
 *  List every weight the pages use: a weight left to the engine's later round
 *  gets the latin file only. With { vertical: true } it also loads each
 *  family's vertical forms (brackets, quotes, pause marks) for the canvas,
 *  which needs loadVerticalAlternates imported from postext. Resolves to
 *  the number of files loaded. */
async function loadCjkFonts(faces, text, { vertical = false } = {}) {
  kitStatus('Loading fonts…');
  let loaded = 0;
  try {
    if (vertical && typeof loadVerticalAlternates !== 'function') {
      throw new Error('loadCjkFonts(…, { vertical: true }) needs loadVerticalAlternates imported from postext');
    }
    for (const [family, specs] of Object.entries(faces)) {
      if (!(await isCjkFamily(family))) continue;
      const twin = [];
      for (const spec of new Set(specs)) {
        const weight = parseInt(spec, 10);
        const style = spec.endsWith('i') ? 'italic' : 'normal';
        const slices = await cjkSlices(family, weight, style);
        const missing = [...new Set(text)].filter((ch) => /\S/.test(ch) && !cjkSliceFor(slices, ch.codePointAt(0)));
        if (missing.length) {
          throw new Error(`${family} ${spec} has no file for ${missing.slice(0, 12).join(' ')}: `
            + `give each face the text it sets (loadCjkFonts({ '${family}': ['${spec}'] }, text))`);
        }
        for (const slice of slices) {
          document.fonts.add(new FontFace(family, `url(${slice.url}) format('woff2')`,
            { weight: String(weight), style, unicodeRange: slice.range }));
          twin.push({ source: slice.url, weight: String(weight), style, unicodeRange: slice.range });
        }
        const font = `${style === 'italic' ? 'italic ' : ''}${weight} 16px "${family}"`;
        loaded += (await document.fonts.load(font, text)).length;
        if (!document.fonts.check(font, text)) throw new Error(`${family} ${spec} did not load for the sample`);
      }
      // The same files under a twin name with the `vert` feature on: the
      // canvas paints the punctuation of vertical lines with it.
      if (vertical && twin.length) await loadVerticalAlternates(family, twin);
    }
  } catch (error) {
    kitFail(error);
    throw error;
  }
  return loaded;
}

/** The PDF font provider for recipes with CJK faces: a family whose
 *  Fontsource subsets are Chinese, Japanese or Korean gets the files the
 *  screen set its pages' characters in (`request.codePoints`), each marked
 *  with its unicode-range and its place in the order loadCjkFonts added
 *  them: postext-pdf sets a character two files hold in the one added
 *  last, as the browser does. Any other family gets the latin file
 *  fontsourceProvider fetches (the "pdf" block) and, when the face sets
 *  letters only latin-ext has, that file too. */
async function cjkPdfProvider(family, weight, style, request) {
  if (!(await isCjkFamily(family))) return cjkLatinPdfFiles(family, weight, style, request);
  const meta = await fontsourceMeta(family);
  const weights = meta.weights?.length ? meta.weights : [400, 700];
  const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const s = style === 'italic' && !meta.styles.includes('italic') ? 'normal' : style;
  const slices = await cjkSlices(family, w, s);
  const picked = new Set();
  for (const cp of request?.codePoints ?? []) {
    const slice = cjkSliceFor(slices, cp);
    if (slice) picked.add(slice);
  }
  if (!picked.size) picked.add(slices[0]);
  return Promise.all(slices.map(async (slice, order) => {
    if (!picked.has(slice)) return null;
    const res = await fetch(slice.url);
    if (!res.ok) throw new Error(`Fontsource file ${slice.url} (${res.status})`);
    const bytes = await decompressWoff2(new Uint8Array(await res.arrayBuffer()));
    return Object.assign(bytes, { unicodeRange: slice.range, order });
  })).then((files) => files.filter(Boolean));
}

/** A Latin family set next to the CJK faces: its latin file, then its
 *  latin-ext file when the face sets letters only latin-ext has (ō ū in
 *  Hepburn rōmaji, ǎ in pinyin), the file loadFonts adds on screen for
 *  them, each marked with its unicode-range and its place in that order:
 *  the PDF sets a character in the file the browser took it from. A face
 *  Fontsource ships without latin-ext, or whose file does not come, gets
 *  latin alone, and the PDF names the letters it lacks. */
async function cjkLatinPdfFiles(family, weight, style, request) {
  const meta = await fontsourceMeta(family);
  const beyond = [...(request?.codePoints ?? [])].some(cjkLatinExtOnly);
  if (!beyond || !meta?.subsets?.includes('latin-ext')) return fontsourceProvider(family, weight, style);
  const weights = meta.weights?.length ? meta.weights : [400, 700];
  const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const s = style === 'italic' && !meta.styles.includes('italic') ? 'normal' : style;
  const id = fontsourceId(family);
  const url = `${await fontsourceAt(id)}files/${id}-latin-ext-${w}-${s}.woff2`;
  const [latin, ext] = await Promise.all([fontsourceProvider(family, weight, style), fetch(url)
    .then(async (res) => (res.ok ? decompressWoff2(new Uint8Array(await res.arrayBuffer())) : null), () => null)]);
  const ranges = kitRanges();
  return ext ? [Object.assign(latin, { unicodeRange: ranges.latin, order: 0 }),
    Object.assign(ext, { unicodeRange: ranges['latin-ext'], order: 1 })] : latin;
}

/** Whether code point `cp` is in Fontsource's latin-ext file and not in
 *  its latin file: Latin Extended-A and -B, IPA, the spacing modifiers and
 *  Latin Extended Additional (loadFonts's test for latin-ext), less the
 *  few latin holds too (ı Œ œ ʻ ʼ ˆ ˚ ˜). */
function cjkLatinExtOnly(cp) {
  if (!((cp >= 0x100 && cp <= 0x2ff) || (cp >= 0x1e00 && cp <= 0x1eff))) return false;
  return ![0x131, 0x152, 0x153, 0x2bb, 0x2bc, 0x2c6, 0x2da, 0x2dc].includes(cp);
}

/** showPages for a book bound on either edge. A right-bound book (the
 *  document says so: doc.binding is 'right' for page.binding 'right' and
 *  for vertical text) lies on the desk as it opens: page 1 alone on the
 *  left of the spine, then [3 | 2], the spine shade on each page's inner
 *  edge. `binding` ('left' | 'right') overrides the document's. */
function showBook(docs, { binding, ...options } = {}) {
  const count = showPages(docs, options);
  const right = (binding ?? [docs].flat()[0]?.binding) === 'right';
  if (!document.getElementById('pt-kit-cjk')) {
    // The pages keep direction ltr: a canvas draws text in the direction its
    // element inherits, and under rtl each run would end where the engine
    // starts it, its brackets mirrored.
    document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit-cjk">
      .pt-spread[dir="rtl"] canvas { direction: ltr; }
      .pt-spread[dir="rtl"] 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); }
    </style>`);
  }
  // Each pair stays [verso, recto] in the page; right to left, the verso
  // sits on the right. Phones stack the pages in reading order either way.
  for (const spread of document.querySelectorAll('#pages > .pt-spread')) spread.dir = right ? 'rtl' : 'ltr';
  document.getElementById('pages').dataset.binding = right ? 'right' : 'left';
  return count;
}

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

## Варианты

### Набирайте все знаки во всю ширину (全角式)

Запятые, знаки паузы и кавычки занимают целый знак, 。” — два, и текста в строку входит меньше.

```diff
-  punctuationWidth: 'kaiming', // ，、：； quotes, brackets ½ em; 。？！ one em, ½ at a line end
-  compressAdjacent: true, // idle under Kaiming (no pair tops 1.5 em); 'fullwidth' needs it
+  punctuationWidth: 'fullwidth',
+  compressAdjacent: false,
```

### Показывайте сетку во время вёрстки

Холст рисует светло-серый квадрат на месте каждого знака каждой строки (稿纸); в PDF его нет, пока `renderToPdf` не получит `characterGrid: true`.

```diff
-  grid: { enabled: true, charsPerLine: CHARS, linesPerPage: LINES },
+  grid: { enabled: true, charsPerLine: CHARS, linesPerPage: LINES, show: true },
```

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

- **Китайские шрифты загружаются частями через блок cjk.** Fontsource отдаёт китайскую, японскую или корейскую гарнитуру примерно сотней файлов на насыщенность, каждый со своим диапазоном знаков. loadFonts загружает только файл latin, поэтому на экране иероглифы берутся из системного шрифта и измеряются неверно, а fontsourceProvider отдаёт PDF тот же файл latin, и они печатаются пустыми квадратами. Укажите блок cjk набора kit, вызовите loadCjkFonts(FONTS, markdown) после loadFonts (по разу на каждый шрифт, с текстом, который он набирает, если в книге несколько шрифтов CJK) и передайте renderToPdf fontProvider: cjkPdfProvider: оба берут файлы, в которых есть знаки текста.
- **Помечайте документ zh-Hans или zh-Hant, а не LANG.** Издания рецепта — en и es, но китайский образец в обоих китайский: `locale: LANG` пометил бы его английским или испанским, переносил бы латинские слова, подписывал бы рисунки Figure или Figura и задал бы PDF неверный язык. Начиная с postext 1.30 тег — это ещё и язык, на котором формируется текст (измеряется, рисуется и встраивается): под английским или испанским тегом китайское начертание набирает цифры и общую с латиницей пунктуацию в других формах, и строки разрываются иначе. Пишите тег сами: 'zh-Hans' (нормы материкового Китая: разрыв строк GB, пунктуация кайминг) или 'zh-Hant' (Тайвань: центрированная пунктуация полной ширины); 'zh-HK' для Гонконга. Просто 'zh' читается как упрощённый, материковый. Японскому образцу нужен 'ja' (подводный камень ja-locale-tag).
- **Пунктуация каждого региона — шрифтом этого региона.** Знаки препинания при сжатии теряют пустую половину с той стороны, которую задаёт регион документа, а не с той, где она нарисована в шрифте. При zh-Hans запятая в режиме Kaiming сохраняет левую половину своего кегельного квадрата, где глиф стоит в шрифте для упрощённого письма, и отдаёт правую. В шрифте для традиционного письма ，。 стоят по центру квадрата, поэтому в отброшенную половину попадает часть глифа и запятая налезает на следующий знак. Так ведёт себя в упрощённом тексте LXGW WenKai TC, единственный текстовый шрифт кайшу на Fontsource. Тексты для материкового Китая, примечания и цитаты набирайте Noto Serif SC или Noto Sans SC, шрифты TC оставьте для zh-Hant, а кистевой шрифт с упрощёнными знаками (Ma Shan Zheng) берите только для акцидентных строк: к тексту оформления сжатие знаков не применяется. Кроме того, LXGW WenKai TC рисует старые формы, которых нет ни в материковом, ни в тайваньском стандарте: 為 с верхом 爫, как у 爲, и 令 (в 冷, 領) с низом 卩. Проверьте знаки, которые попадают на страницу.
- **В китайском нет курсива.** В гарнитурах CJK нет курсива, и китайская типографика выделяет точками у знаков, а не наклоном. В документе с китайским тегом *…* ставит точки выделения у китайских знаков и оставляет курсив латинским словам (cjk.emphasis: 'dots', по умолчанию для китайского); :dots[…] ставит их где угодно. При cjk.emphasis: 'italic' или в документе с тегом en или es *…* заставляет холст наклонять прямые глифы: такой синтетический наклон в китайской типографике не применяют (PDF берёт прямое начертание). Оставьте китайский тег либо выделяйте полужирным или начертанием кай (LXGW WenKai) через стиль абзаца или плашки.
- **Стиль заголовка наследует разрыв страницы своего уровня.** Запись headingStyles берёт каждое пропущенное поле у своего уровня заголовка, в том числе breakBefore. Страница содержания или выходных данных со стилем на H1 после :::pagebreak наследует parity 'odd' и оказывается после пустой страницы. Дайте такому стилю breakBefore: { enabled: false }.
- **Предупреждение вёрстки: Знаковая сетка слишком велика** (`cjkGridClamped`). `cjk.grid` требует больше знаков в строке или строк на странице, чем помещается в поля при кегле и интерлиньяже основного текста, поэтому сетка набрана с наибольшим числом, которое помещается. Решение: Уменьшите `charsPerLine` или `linesPerPage`, сузьте поля (они — минимум) либо задайте меньший `bodyText.fontSize` или `lineHeight`. ([Документация](https://postext.dev/ru/docs/configuration-east-asian.md#сетка-знаков))

- Иллюстрация — заголовок, а заголовок получает закладку PDF: без `runningChapter: false` и `toc: false` в её стиле оглавление открылось бы на 月下的瓜地, закладке первого уровня перед 故乡. Любой одной из двух настроек мало. В размеченном PDF заголовок иллюстрации всё равно остаётся H1.
- Собственный шрифт заголовков должен быть среди тех, что загружает `FONTS`, даже если все заглавия рисует оформление: с насыщенностью 700 по умолчанию вспомогательный код нашёл в вёрстке Noto Serif SC 700 и с предупреждением загрузил её латинский файл. `headings.fontWeight: 400` оставляет блоки заголовков в шрифте текста.

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

- Рецепт: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Текст: “My Old Home” (故乡, 1921), the first half, from the 1948 Complete Works, in simplified characters: Lu Xun (鲁迅) ([источник](https://zh.wikisource.org/wiki/故鄉)), общественное достояние
- Текст: The editor’s note and the colophon: Postext Cookbook, оригинал
- Изображения: The plate: the moonlit melon field of the story, a painting: Generated With Diffusion Models, оригинал
- Шрифты: Noto Serif SC (OFL-1.1), Noto Sans SC (OFL-1.1), Ma Shan Zheng (OFL-1.1)
- Код: MIT · Образец содержания: MIT

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

- [№ 016 · Испанский текст с выключкой в карманном романе](https://postext.dev/ru/cookbook/spanish-pocket-novel.md): Начало главы I «Марианелы» карманным изданием: испанские переносы, пробелы уже 1,7×, без коротких концевых строк, приподнятый инициал, карта как Figura 1. · Уровень 2 (Средний) · Художественная литература, драматургия и эссеистика
- [№ 014 · Ровные пробелы в узких колонках с выключкой](https://postext.dev/ru/cookbook/justification-lab.md): Разбивка Кнута — Пласса с пробелами в пределах 0,8–1,6 нормы рядом с жадной, где разреженные, висячие и короткие строки отмечены по VDT. · Уровень 3 (Продвинутый) · Журналы и зины
- [№ 038 · Роман в мягкой обложке: спуск и главы с правой полосы](https://postext.dev/ru/cookbook/trade-paperback-novel.md): The Awakening в мягкой обложке 140 × 216 мм: живописная обложка и оборот без колонтитулов, главы с правой полосы со спуском под курсивной цифрой. · Уровень 2 (Средний) · Художественная литература, драматургия и эссеистика
