# Образец шрифтов: все шрифты загружены до вёрстки

> Образец шрифтов на четырёх страницах: один раз собран слишком рано, как улика, затем со всеми начертаниями из конфигурации и текста до первого измерения.

- Версия HTML: https://postext.dev/ru/cookbook/fonts-before-layout
- Рецепт № 026 · Вывод и интеграция · Уровень 2 (Средний) · Форматы вывода: Canvas
- Жанры: Каталоги
- Требуется postext ≥ 1.25.0 · проверено с 1.65.0 · дата 2026-10-31
- Страницы: [1](https://postext.dev/cookbook/fonts-before-layout/en/p01.webp?v=50ce2cc8), [2](https://postext.dev/cookbook/fonts-before-layout/en/p02.webp?v=50ce2cc8), [3](https://postext.dev/cookbook/fonts-before-layout/en/p03.webp?v=50ce2cc8), [4](https://postext.dev/cookbook/fonts-before-layout/en/p04.webp?v=50ce2cc8)
- Открыть в Sandbox: https://postext.dev/ru/sandbox#recipe=fonts-before-layout&lang=en (.postext: https://postext.dev/cookbook/fonts-before-layout/en/fonts-before-layout.postext)
- Последнее обновление: 2026-10-10
- Другие языки: [en](https://postext.dev/en/cookbook/fonts-before-layout.md), [es](https://postext.dev/es/cookbook/fonts-before-layout.md), [ca](https://postext.dev/ca/cookbook/fonts-before-layout.md), [de](https://postext.dev/de/cookbook/fonts-before-layout.md), [el](https://postext.dev/el/cookbook/fonts-before-layout.md), [fr](https://postext.dev/fr/cookbook/fonts-before-layout.md), [it](https://postext.dev/it/cookbook/fonts-before-layout.md), [pt](https://postext.dev/pt/cookbook/fonts-before-layout.md), [zh](https://postext.dev/zh/cookbook/fonts-before-layout.md), [ja](https://postext.dev/ja/cookbook/fonts-before-layout.md), [ar](https://postext.dev/ar/cookbook/fonts-before-layout.md)

## Коротко

Буклет на четырёх страницах показывает три гарнитуры. Из него видно, почему все шрифты должны загрузиться до вёрстки: иначе строки переносятся не там, где нужно.

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

*House Specimen Nº 3* вымышленного издательства Pellow Lane Press — образец трёх гарнитур на четырёх страницах. На обложке в ультрамариновом поле белое *Ag* курсивом Noto Serif Display, 240 пт, и две моноширинные строки с названиями трёх гарнитур; заголовок стоит под полем. На странице 2 гарнитура Ysabeau Office идёт столбцом от 7 до 14 пт, а за ним следуют испанская, польская и чешская панграммы: для ż, ř и ů нужен второй файл шрифта. Страница 3 — проверка: таблица, набранная IBM Plex Mono и заполненная самим пеном. В ней десять начертаний, объявленных в буклете, шесть из них набраны на страницах, и для каждого указаны файлы, которые загрузил браузер. На странице 4 первый абзац страницы 1 стоит дважды: из ранней сборки и из последней. Ранняя сборка прошла, когда у браузера не было ни одного файла шрифта, поэтому строки в ней кончаются в других местах, а некоторые вылезают за формат набора.

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

- Почему меняются концы строк или слова в PDF налезают друг на друга и как загрузить шрифты до вёрстки?
- Как использовать в вёрстке фирменные или лицензионные шрифты и встроить их в PDF?
- Как понять, что не так с документом (предупреждения, переполнение, вёрстка без сходимости)?

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

```js
// script.js, строк 314–331
// buildDocumentWithFonts starts with prepareFonts: it reads the config and the text for every
// face they ask for (text, headings, chips, table, captions, opener, running heads), in each
// weight and slant, and loads them for the characters the document sets. The page declares its
// files (declareFaces), so they load through document.fonts; a face nothing declares would be
// asked of a resolve(family, weight, style) option. Then it builds, reads the faces the pages
// are set in, loads any that the config did not name and builds again.
let report; // { loaded, missing, synthesized }: lists of { family, weight, style }
const build = () => buildDocumentWithFonts(content(), config(),
  { onFonts: (found) => { report = found; } }); // what the last look at the pages found

kitStatus('Loading fonts…'); // the kit's bar: it also reports any error thrown below
const early = buildDocument(content(), config()); // on purpose: the page has no font yet (page 4)
declareFaces(FONTS);
const fitted = await build(); // every face loaded before a line is measured
audit = auditOf(fitted, report); // page 3's table
drawProof(early, fitted); // page 4's picture
const doc = await build(); // nothing left to load: the same pages, table and picture filled in
showPages(doc, { title: 'Load every font before layout' });
```

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

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

- [Шрифты до вёрстки](https://postext.dev/ru/docs/configuration-programmatic-usage.md#загрузка-шрифтов-перед-вёрсткой): Вёрстка измеряет теми начертаниями, которые загрузил браузер, поэтому движок загружает шрифты документа до неё (prepareFonts, buildDocumentWithFonts), а его кеши измерений следят за начертаниями: если одно приходит позже, измеренное в этой гарнитуре сбрасывается.
- [Шрифт основного текста](https://postext.dev/ru/docs/configuration-text.md#основной-текст): Гарнитура текста, кегль, интерлиньяж и насыщенность; интерлиньяж задаёт и шаг сетки базовых линий.

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

- [Страницы на холсте](https://postext.dev/ru/docs/configuration-programmatic-usage.md#рендеринг-страницы-в-растр)
- [Рисунки и таблицы как ресурсы](https://postext.dev/ru/docs/document-format-resources.md#ресурсы)
- [Рисунки точно здесь](https://postext.dev/ru/docs/document-format-resources.md#блочная-вставка-необязательная-с-явным-местом-в-тексте)
- [Таблицы из данных](https://postext.dev/ru/docs/document-format-resources.md#блочная-вставка-необязательная-с-явным-местом-в-тексте)
- [Стиль таблиц](https://postext.dev/ru/docs/configuration-resources.md#стиль-таблицы)
- [Стиль подписей](https://postext.dev/ru/docs/configuration-resources.md#стиль-подписи)
- [Собственные типы ресурсов](https://postext.dev/ru/docs/configuration-resources.md#типы-ресурсов)
- [Оформленные начальные полосы](https://postext.dev/ru/docs/configuration-headings.md#ширина-и-расширенный-дизайн)
- [Атрибуты заголовков](https://postext.dev/ru/docs/document-format.md#атрибуты-заголовка)
- [Привязка элементов дизайна](https://postext.dev/ru/docs/configuration-headers-footers.md#размещение-элементов)
- [Стили абзацев](https://postext.dev/ru/docs/configuration-styles.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-fonts-colors-viewers.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-resources.md#типы-ресурсов)
- [Шапка главы на всю ширину](https://postext.dev/ru/docs/configuration-headings.md#ширина-и-расширенный-дизайн)
- [Разрывы страниц и колонок](https://postext.dev/ru/docs/document-format-directives.md#pagebreak)

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

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

**API**

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

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

- Ysabeau Office (OFL-1.1), Noto Serif Display (OFL-1.1), IBM Plex Mono (OFL-1.1)

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

### 1 · Объявите все файлы, не загружая их

```js
// script.js, строк 268–287
const SUBSETS = { // the characters each file covers, copied from the family's @font-face CSS
  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' };
const FILES = new Map(); // FontFace → the subset its file covers, for the audit
function declareFaces(fonts) { // Fontsource's static files stand in for your own /fonts/ folder
  for (const { family, weight, style } of facesOf(fonts)) {
    const id = family.toLowerCase().replaceAll(' ', '-');
    for (const [subset, unicodeRange] of Object.entries(SUBSETS)) {
      const file = `${id}@5/files/${id}-${subset}-${weight}-${style}.woff2`;
      // Adding a face fetches nothing: the file downloads when a load or a line needs it.
      const face = new FontFace(family, `url(https://cdn.jsdelivr.net/npm/@fontsource/${file})`,
        { weight: `${weight}`, style, unicodeRange });
      FILES.set(face, subset);
      document.fonts.add(face);
    }
  }
}
```

`FontFace` соответствует одному файлу, как правило `@font-face`, поэтому начертание с файлами latin и latin-ext объявляется двумя объектами `FontFace`: гарнитура, насыщенность и стиль у них общие, а `unicodeRange`, скопированный из CSS гарнитуры, разный. Добавление в `document.fonts` ничего не загружает: браузер запрашивает файл, когда его символы нужны вызову `load()` или строке текста. Postext загружает объявленные на странице начертания через `document.fonts`, а необъявленные спрашивает у опции `resolve`; так остальные рецепты получают файлы Fontsource из набора. `customFonts` в конфигурации описывает только файлы пакета `.postext`, поэтому страница, собранная из Markdown, объявляет свои шрифты сама или передаёт `resolve`.

### 2 · Загрузите начертания, потом собирайте

Код приведён выше, в разделе [«Короткий ответ»](https://postext.dev/ru/cookbook/fonts-before-layout.md#короткий-ответ). `buildDocumentWithFonts` начинает с `prepareFonts`: эта функция находит в конфигурации и тексте все нужные начертания, каждой насыщенности и наклона, и загружает их, беря образцом символы самого документа, поэтому файлы latin-ext приходят вместе с польской и чешской панграммами ([загрузка шрифтов до вёрстки](https://postext.dev/ru/docs/configuration-programmatic-usage.md#загрузка-шрифтов-перед-вёрсткой)). Затем она собирает документ, смотрит, какими начертаниями набраны страницы, догружает те, что не названы в конфигурации, и собирает ещё раз. `onFonts` получает отчёт последнего просмотра: начертания, которые нашлись (`loaded`), которых не хватает (`missing`) и которые браузер синтезировал бы из другой насыщенности или наклона (`synthesized`). Пен собирает документ трижды, потому что буклет печатает собственные улики: один раз слишком рано, один раз с начертаниями и в последний раз с заполненными таблицей и изображением.

### 3 · Составьте таблицу проверки из отчёта

```js
// script.js, строк 291–309
const SET = { loaded: 'yes', synthesized: 'faked', missing: 'in a fallback' }; // the report
const nameOf = (f) => `${f.family.replaceAll('"', '')} ${f.weight} ${f.style}`; // or a FontFace
function auditOf(doc, report) {
  const found = Object.keys(SET).flatMap((kind) => report[kind].map((f) => [nameOf(f), kind]));
  const inPages = new Map(found);
  const loaded = [...FILES].filter(([face]) => face.status === 'loaded');
  const faces = new Map([...facesOf(FONTS), ...Object.keys(SET).flatMap((kind) => report[kind])]
    .map((f) => [nameOf(f), f])); // the declared faces, then any the pages set without a file
  const rows = [...faces].map(([name, f], i, all) => [
    i && all[i - 1][1].family === f.family ? '' : f.family, // each family named once
    `${f.weight}${f.style === 'italic' ? ' italic' : ''}`, SET[inPages.get(name)] ?? 'no',
    loaded.filter(([face]) => nameOf(face) === name).map(([, subset]) => subset).join(' · ')
      || 'none'].map((cell) => ({ content: cell })));
  // What else to read in a finished layout: its content warnings, its passes, its warnings.
  return { rows, note: `${report.loaded.length} of ${rows.length} faces set in the pages · `
    + `${loaded.length} of ${FILES.size} files fetched · fontFallback warnings: `
    + `${fallbacksIn(doc) || 'none'} · ${doc.converged ? '' : 'not '}converged · layout warnings: `
    + `${doc.warnings?.length || 'none'}` };
}
```

Таблица начинается с начертаний, объявленных в `FONTS`, и добавляет к каждому то, что говорит отчёт: набрано на страницах, подделано браузером или набрано запасным шрифтом. В последнем столбце перечислены файлы, чей `FontFace` дошёл до состояния `loaded`. Загружено шестнадцать файлов из двадцати: Postext загружает все четыре начертания текстовой гарнитуры, потому что `**` и `*` могут понадобиться в любом абзаце, а два моноширинных курсива, которых нет ни в одной настройке, не загружались вовсе. Примечание берёт из готового документа ещё три вещи: `contentWarnings`, где начертание, измеренное запасным шрифтом, помечено как `fontFallback`; `converged`, истинное, если проходы вёрстки сошлись; и `warnings`. Проверьте все три, прежде чем показывать или выгружать страницу.

### 4 · Сохраните раннюю сборку как улику

```js
// script.js, строк 126–174
const STRIP = { lines: 8, overrun: 10 }; // page 1's first paragraph; mm shown past the measure
const PROOF = { // px: two strips a lead apart, cut at 300 dpi
  width: Math.round(((MEASURE + STRIP.overrun) / 25.4) * 2 * DPI),
  height: Math.round((((2 * STRIP.lines + 1) * LEAD) / 72) * 2 * DPI) };
const proof = { moved: 0, total: 0, faces: 0 }; // lines the early build broke elsewhere, of all
const fallbacksIn = (doc) => // a build lists each face its font set could not give
  (doc.contentWarnings ?? []).filter((w) => w.kind === 'fontFallback').length;
const proofFigure = () => ({ id: 'proof', typeId: 'figure', kind: 'bitmap', createdAt: 0,
  updatedAt: 0, placement: here,
  bitmap: { fileId: 'proof.png', format: 'png', width: PROOF.width, height: PROOF.height },
  caption: 'The first paragraph of page 1 as the early build set it, measured before the fonts '
    + 'had arrived (above), and as the last build set it (below). The early build broke '
    + `${proof.moved} of its ${proof.total} lines of text elsewhere, and its own warnings name `
    + `${proof.faces} faces set in a fallback. The rule marks the measure.`,
  altText: `Two strips of the same ${STRIP.lines} lines of text. In the upper strip the lines `
    + 'break in other places and some run past a vertical rule; in the lower one every line '
    + 'stops short of it.' });
function drawProof(first, last) {
  const linesOf = (doc) => doc.blocks.filter((b) => b.type === 'paragraph')
    .map((b) => b.lines.map((l) => l.text));
  const [before, after] = [first, last].map(linesOf);
  proof.total = before.flat().length;
  proof.faces = fallbacksIn(first);
  proof.moved = before.flatMap((lines, i) => lines.filter((t, j) => t !== after[i]?.[j])).length;
  const canvas = Object.assign(document.createElement('canvas'), PROOF);
  const ctx = canvas.getContext('2d');
  const strip = (PROOF.height * STRIP.lines) / (2 * STRIP.lines + 1);
  const edge = Math.round((PROOF.width * MEASURE) / (MEASURE + STRIP.overrun));
  // The renderer clips each column 2 pt past its edge, which would cut the early build's lines
  // at the measure: paint a copy of page 1 whose column reaches across the whole strip.
  const wide = (column) => ({ ...column,
    bbox: { ...column.bbox, width: column.bbox.width + (STRIP.overrun / 25.4) * DPI } });
  [first, last].forEach((doc, i) => {
    const page = document.createElement('canvas');
    renderPageToCanvas({ ...doc.pages[0], columns: doc.pages[0].columns.map(wide) }, doc, page,
      { scale: 2 }); // 300 dpi
    const { x, y } = doc.pages[0].columns[0].blocks.find((b) => b.type === 'paragraph').bbox;
    ctx.drawImage(page, 2 * x, 2 * y, PROOF.width, strip,
      0, i * (PROOF.height - strip), PROOF.width, strip);
  });
  ctx.fillStyle = `${palette.ultramarine}1f`; // a pale wash over the margin past the measure
  ctx.fillRect(edge, 0, PROOF.width - edge, PROOF.height);
  ctx.fillStyle = palette.ultramarine; // a hairline at the measure, and each strip's name
  ctx.fillRect(edge, 0, 2, PROOF.height);
  ctx.font = `700 ${(7 / 72) * 2 * DPI}px "IBM Plex Mono"`; // 7 pt, loaded by now
  ['early', 'last'].forEach((name, i) => // on the last line of each strip
    ctx.fillText(name, edge + 12, (i ? PROOF.height : strip) - 16));
  registerResourceImage('proof.png', canvas);
}
```

Пен вызывает `buildDocument` один раз до того, как объявит хотя бы одно начертание, поэтому та сборка измеряет каждое слово запасным шрифтом браузера. Когда настоящие начертания загружены, пен рисует её заново и построчно сравнивает с последней; отсюда число строк в подписи, а число начертаний взято из предупреждений `fontFallback` самой ранней сборки. Обычная строка, измеренная более узким запасным шрифтом, выходит за формат, пока обрезка колонки в 2 пт за её краем не отсечёт последние буквы, поэтому пен рисует страницу 1 с расширенной колонкой, чтобы показать весь выступ. Холст и `postext-pdf` рисуют каждый отрезок строки, выключенной по формату или набранной разными начертаниями, там, где его измерила вёрстка, так что настоящее начертание, более широкое, чем запасное, печатается поверх следующего слова; в PDF, собранном до загрузки шрифтов, слова налезают друг на друга. К следующей сборке от ранней ничего не переходит: `prepareFonts` находит новые начертания в `document.fonts` и сбрасывает ширины, измеренные в этих гарнитурах, поэтому вызывать `clearMeasurementCache()` не нужно.

### 5 · Столбец кеглей в ритме текста

```js
// script.js, строк 30–44
const bodyText = () => ({
  fontFamily: TEXT, fontSize: pt(11), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  textAlign: 'left', firstLineIndent: pt(0), paragraphSpacing: true }); // ragged and spaced
// Every waterfall size and pangram is two leads (31 pt) deep, on the text's 15.5 pt rhythm.
const line = (size) => ({ fontSize: pt(size), lineHeight: pt(2 * LEAD) });
const paragraphStyles = () => [
  ...[7, 8, 9, 10, 11, 12, 14].map((size) => ({ id: `s${size}`, ...line(size) })),
  { id: 'pangram', ...line(13) },
  { id: 'colophon', fontSize: pt(7), lineHeight: pt(10), fontFamily: MONO, color: col('muted') }];
// Size labels: boxless mono chips. A Plex Mono letter is 0.6 em wide, so a one-digit label gets
// half a letter each side and the samples start on one edge.
const tag = { fontFamily: MONO, fontSize: pt(7), color: col('ultramarine'),
  backgroundEnabled: false, borderWidth: pt(0), paddingX: pt(0), gap: mm(2.5) };
const chipStyles = () => [{ id: 'size', ...tag }, { id: 'size-1', ...tag, paddingX: em(0.3) }];
```

Текст набран Ysabeau Office, 11 на 15,5 пт, с пустой строкой между абзацами вместо абзацного отступа. Набор флаговый, поэтому межсловные пробелы сохраняют естественную ширину. Полужирное, курсив и ссылки набраны чёрным; без настройки они взяли бы основной цвет. Каждый кегль столбца и каждая панграмма — стиль абзаца высотой в два интерлиньяжа (31 пт), поэтому страница держит ритм текста 15,5 пт. Метки кеглей — моноширинные плашки; у однозначных кеглей по бокам добавлено по половине знака, и все образцы начинаются от одного края.

### 6 · Три гарнитуры на одной обложке

```js
// script.js, строк 48–74
const Y = { kicker: 14, glyphs: 17, label: FIELD - 12, title: FIELD + 10, // mm from the top edge
  end: FIELD + 42 }; // where the opener ends: under the title, the lead and a line of air
const ITALIC_FOOT = 5; // mm: the italic A's foot reaches this far left of the glyphs' origin
const at = (x, y, width) => ({ anchor: { to: 'page', edge: 'top-left' },
  offset: { x: mm(x), y: mm(y) }, ...(width && { size: { width: mm(width) } }) });
const text = (id, content, style, placement) => ({ kind: 'text', id, content, align: 'left',
  overflow: 'wrap', ...style, placement }); // a running head wraps too, never '…'
const cover = () => ({ level: 1, fontSize: pt(30), italic: true, // headings.levels[0]
  breakBefore: { enabled: true, parity: 'odd' }, // the cover is a recto
  span: 'page', // the heading is set across the page; its field hangs from the bleed
  advancedDesign: { enabled: true, minHeight: mm(Y.end - MARGIN.top), // from the top margin
    slot: { elements: [
      { kind: 'box', id: 'field', style: { backgroundColor: col('ultramarine') }, placement: {
        anchor: { to: 'bleed', edge: 'top-left' }, size: { width: 'fill', height: mm(FIELD) } } },
      text('kicker', '{attr.kicker}', { ...label, fontWeight: 700, color: col('paper') },
        at(MARGIN.inner, Y.kicker)),
      text('glyphs', '{attr.glyphs}', { ...display, fontSize: pt(240), lineHeight: 1,
        color: col('paper') }, at(MARGIN.inner + ITALIC_FOOT, Y.glyphs)),
      text('label', '{attr.label}', { ...label, color: col('mist') }, at(MARGIN.inner, Y.label)),
      text('faces', '{attr.faces}', { ...label, color: col('mist') },
        { anchor: { to: '#label', edge: 'below' }, offset: { y: mm(1.2) } }),
      text('title', '{titleText}', { ...display, fontSize: pt(30), lineHeight: 1.05,
        color: col('ink') }, at(MARGIN.inner, Y.title, PAGE.width - 2 * MARGIN.inner)),
      text('lead', '{attr.lead}', { fontFamily: TEXT, italic: true, fontSize: pt(12),
        lineHeight: 1.35, color: col('ink') }, { anchor: { to: '#title', edge: 'below' },
        offset: { y: mm(3) }, size: { width: mm(MEASURE) } }),
    ] } } });
```

Обложка — оформление уровня H1: буквы из атрибута `glyphs` заголовка набраны акцидентной гарнитурой, 240 пт, а под ними две моноширинные строки с названиями этой гарнитуры, текстовой и служебной, как в образцах шрифтолитейных фирм. `span: 'page'` ставит заголовок на всю ширину страницы, а поле привязано к левому верхнему углу вылета и уходит за верхний край. `minHeight` отсчитывается от верхнего поля и резервирует место до `Y.end`, на 42 мм ниже поля; без него текст начался бы на строку выше, вплотную под вводным абзацем.

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

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

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

### script.js

```js
// ═══ Postext Cookbook · Nº 026 · Type specimen with every font loaded before layout ═════════
// https://postext.dev/en/cookbook/fonts-before-layout
// Code: MIT · Text: original (CC BY 4.0) · Picture: cut from the pen's own early and last builds
// Fonts: Ysabeau Office, Noto Serif Display, IBM Plex Mono (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import { buildDocument, buildDocumentWithFonts, renderPageToCanvas, defaultResourceTypes,
  registerResourceImage } from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'fonts-before-layout';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const PAGE = { width: 180, height: 240 }; // mm
const MARGIN = { top: 22, bottom: 24, inner: 20, outer: 48 }; // mm: inner is the spine side
const MEASURE = PAGE.width - MARGIN.inner - MARGIN.outer; // 112 mm: about 70 letters at 11 pt
const FIELD = 122; // mm from the top edge: the ultramarine field of the opener
const LEAD = 15.5; // pt: the body leading and the step of every vertical space
const DPI = 150; // the page's resolution: the proof on page 4 is cut at twice this
const [TEXT, DISPLAY, MONO] = ['Ysabeau Office', 'Noto Serif Display', 'IBM Plex Mono'];
const palette = { ink: '#16161a', ultramarine: '#3246d3', mist: '#c9d0f6', // mist: 4.6:1 on
  rule: '#cfc9bd', muted: '#6b6a70', paper: '#ffffff' }; // ultramarine, for labels on the field
// Every colour is linked to its palette entry; main-color catches any default left unstated.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = () => Object.entries({ ...palette, 'main-color': palette.ultramarine })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const label = { fontFamily: MONO, fontSize: pt(7.5), letterSpacing: pt(1.2),
  textTransform: 'uppercase' };
const display = { fontFamily: DISPLAY, fontWeight: 900, italic: true };

// #region type: the text face at 11 on 15.5 pt, and a waterfall of it on two leads a line
const bodyText = () => ({
  fontFamily: TEXT, fontSize: pt(11), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  textAlign: 'left', firstLineIndent: pt(0), paragraphSpacing: true }); // ragged and spaced
// Every waterfall size and pangram is two leads (31 pt) deep, on the text's 15.5 pt rhythm.
const line = (size) => ({ fontSize: pt(size), lineHeight: pt(2 * LEAD) });
const paragraphStyles = () => [
  ...[7, 8, 9, 10, 11, 12, 14].map((size) => ({ id: `s${size}`, ...line(size) })),
  { id: 'pangram', ...line(13) },
  { id: 'colophon', fontSize: pt(7), lineHeight: pt(10), fontFamily: MONO, color: col('muted') }];
// Size labels: boxless mono chips. A Plex Mono letter is 0.6 em wide, so a one-digit label gets
// half a letter each side and the samples start on one edge.
const tag = { fontFamily: MONO, fontSize: pt(7), color: col('ultramarine'),
  backgroundEnabled: false, borderWidth: pt(0), paddingX: pt(0), gap: mm(2.5) };
const chipStyles = () => [{ id: 'size', ...tag }, { id: 'size-1', ...tag, paddingX: em(0.3) }];
// #endregion

// #region opener: the H1 as a bleed field, the display face at 240 pt, labels naming the faces
const Y = { kicker: 14, glyphs: 17, label: FIELD - 12, title: FIELD + 10, // mm from the top edge
  end: FIELD + 42 }; // where the opener ends: under the title, the lead and a line of air
const ITALIC_FOOT = 5; // mm: the italic A's foot reaches this far left of the glyphs' origin
const at = (x, y, width) => ({ anchor: { to: 'page', edge: 'top-left' },
  offset: { x: mm(x), y: mm(y) }, ...(width && { size: { width: mm(width) } }) });
const text = (id, content, style, placement) => ({ kind: 'text', id, content, align: 'left',
  overflow: 'wrap', ...style, placement }); // a running head wraps too, never '…'
const cover = () => ({ level: 1, fontSize: pt(30), italic: true, // headings.levels[0]
  breakBefore: { enabled: true, parity: 'odd' }, // the cover is a recto
  span: 'page', // the heading is set across the page; its field hangs from the bleed
  advancedDesign: { enabled: true, minHeight: mm(Y.end - MARGIN.top), // from the top margin
    slot: { elements: [
      { kind: 'box', id: 'field', style: { backgroundColor: col('ultramarine') }, placement: {
        anchor: { to: 'bleed', edge: 'top-left' }, size: { width: 'fill', height: mm(FIELD) } } },
      text('kicker', '{attr.kicker}', { ...label, fontWeight: 700, color: col('paper') },
        at(MARGIN.inner, Y.kicker)),
      text('glyphs', '{attr.glyphs}', { ...display, fontSize: pt(240), lineHeight: 1,
        color: col('paper') }, at(MARGIN.inner + ITALIC_FOOT, Y.glyphs)),
      text('label', '{attr.label}', { ...label, color: col('mist') }, at(MARGIN.inner, Y.label)),
      text('faces', '{attr.faces}', { ...label, color: col('mist') },
        { anchor: { to: '#label', edge: 'below' }, offset: { y: mm(1.2) } }),
      text('title', '{titleText}', { ...display, fontSize: pt(30), lineHeight: 1.05,
        color: col('ink') }, at(MARGIN.inner, Y.title, PAGE.width - 2 * MARGIN.inner)),
      text('lead', '{attr.lead}', { fontFamily: TEXT, italic: true, fontSize: pt(12),
        lineHeight: 1.35, color: col('ink') }, { anchor: { to: '#title', edge: 'below' },
        offset: { y: mm(3) }, size: { width: mm(MEASURE) } }),
    ] } } });
// #endregion

// Running heads at the outer edge of the text; a drop folio there too on the opener (a recto).
const HEADS = { top: 13, bottom: 12 }; // mm from the top and the bottom edge of the page
const head = (id, content, parity, edge, x, pages = 'body') => text(id, content, { parity,
  pages, fontFamily: MONO, fontSize: pt(7.5), color: col('muted') }, { anchor: { to: 'page',
  edge }, offset: { x: mm(x), y: mm(edge.startsWith('top') ? HEADS.top : -HEADS.bottom) } });
const header = () => ({ elements: [
  head('verso', '{pageNumber} · {title}', 'even', 'top-left', MARGIN.outer),
  head('recto', '{chapterTitle} · {pageNumber}', 'odd', 'top-right', -MARGIN.outer)] });
const footer = () => ({ elements: [
  head('drop-folio', '{pageNumber}', 'all', 'bottom-right', -MARGIN.outer, 'opener')] });

const config = () => ({ locale: 'en-us', // the sample is in English
  // "Table 1", not "Table 1.1": the booklet has one chapter. Table captions sit above.
  resourceTypes: defaultResourceTypes(LANG).map((type) => ({ ...type, numberingTemplate: '{n}',
    ...(type.id === 'table' && { captionStyle: { position: 'above' } }) })),
  colorPalette: colorPalette(), layout: { layoutType: 'single' },
  page: { width: mm(PAGE.width), height: mm(PAGE.height), dpi: DPI,
    margins: { top: mm(MARGIN.top), bottom: mm(MARGIN.bottom), left: mm(MARGIN.inner),
      right: mm(MARGIN.outer), mirror: true } },
  bodyText: { ...bodyText(), paragraphContainerSpacing: 'add' }, // samples stay two leads apart
  paragraphStyles: paragraphStyles(), chipStyles: chipStyles(),
  headings: { fontFamily: DISPLAY, fontWeight: 900, color: col('ink'), levels: [cover(),
    { level: 2, fontSize: pt(16), lineHeight: pt(2 * LEAD), marginTop: pt(LEAD),
      marginBottom: pt(0) }] },
  tableStyle: { rules: 'horizontal', borderColor: col('rule'), borderWidth: pt(0.5),
    headerBackground: col('ultramarine'), headerColor: col('paper'), headerFontFamily: MONO,
    headerFontSize: pt(7.5), bodyFontFamily: MONO, bodyFontSize: pt(7.5), cellPadding: mm(1) },
  captionStyle: { fontFamily: MONO, fontSize: pt(7.5), labelColor: col('ultramarine'),
    note: { color: col('muted') } },
  header: header(), footer: footer(),
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The table and the picture come from the builds themselves (section 4).
let audit = { rows: [], note: '' };
const content = () => ({ markdown, resources: resources() }); // read again for each build
const here = { position: 'here' }; // both sit where ::resource puts them
const resources = () => [
  { id: 'faces', typeId: 'table', kind: 'table', createdAt: 0, updatedAt: 0, placement: here,
    caption: 'Every face this booklet declares: whether Postext found it set in the pages, and '
      + 'the files the browser fetched for it.', note: audit.note,
    table: { model: { headerRowCount: 1, columnWidths: [31, 19, 28, 34], rows: [
      ['Family', 'Face', 'In the pages', 'Files fetched']
        .map((cell) => ({ content: cell, isHeader: true })),
      ...audit.rows] } } },
  proofFigure(), // drawn from the builds just below
];

// #region art-proof: page 1's first paragraph from the early build, over the same from the last
const STRIP = { lines: 8, overrun: 10 }; // page 1's first paragraph; mm shown past the measure
const PROOF = { // px: two strips a lead apart, cut at 300 dpi
  width: Math.round(((MEASURE + STRIP.overrun) / 25.4) * 2 * DPI),
  height: Math.round((((2 * STRIP.lines + 1) * LEAD) / 72) * 2 * DPI) };
const proof = { moved: 0, total: 0, faces: 0 }; // lines the early build broke elsewhere, of all
const fallbacksIn = (doc) => // a build lists each face its font set could not give
  (doc.contentWarnings ?? []).filter((w) => w.kind === 'fontFallback').length;
const proofFigure = () => ({ id: 'proof', typeId: 'figure', kind: 'bitmap', createdAt: 0,
  updatedAt: 0, placement: here,
  bitmap: { fileId: 'proof.png', format: 'png', width: PROOF.width, height: PROOF.height },
  caption: 'The first paragraph of page 1 as the early build set it, measured before the fonts '
    + 'had arrived (above), and as the last build set it (below). The early build broke '
    + `${proof.moved} of its ${proof.total} lines of text elsewhere, and its own warnings name `
    + `${proof.faces} faces set in a fallback. The rule marks the measure.`,
  altText: `Two strips of the same ${STRIP.lines} lines of text. In the upper strip the lines `
    + 'break in other places and some run past a vertical rule; in the lower one every line '
    + 'stops short of it.' });
function drawProof(first, last) {
  const linesOf = (doc) => doc.blocks.filter((b) => b.type === 'paragraph')
    .map((b) => b.lines.map((l) => l.text));
  const [before, after] = [first, last].map(linesOf);
  proof.total = before.flat().length;
  proof.faces = fallbacksIn(first);
  proof.moved = before.flatMap((lines, i) => lines.filter((t, j) => t !== after[i]?.[j])).length;
  const canvas = Object.assign(document.createElement('canvas'), PROOF);
  const ctx = canvas.getContext('2d');
  const strip = (PROOF.height * STRIP.lines) / (2 * STRIP.lines + 1);
  const edge = Math.round((PROOF.width * MEASURE) / (MEASURE + STRIP.overrun));
  // The renderer clips each column 2 pt past its edge, which would cut the early build's lines
  // at the measure: paint a copy of page 1 whose column reaches across the whole strip.
  const wide = (column) => ({ ...column,
    bbox: { ...column.bbox, width: column.bbox.width + (STRIP.overrun / 25.4) * DPI } });
  [first, last].forEach((doc, i) => {
    const page = document.createElement('canvas');
    renderPageToCanvas({ ...doc.pages[0], columns: doc.pages[0].columns.map(wide) }, doc, page,
      { scale: 2 }); // 300 dpi
    const { x, y } = doc.pages[0].columns[0].blocks.find((b) => b.type === 'paragraph').bbox;
    ctx.drawImage(page, 2 * x, 2 * y, PROOF.width, strip,
      0, i * (PROOF.height - strip), PROOF.width, strip);
  });
  ctx.fillStyle = `${palette.ultramarine}1f`; // a pale wash over the margin past the measure
  ctx.fillRect(edge, 0, PROOF.width - edge, PROOF.height);
  ctx.fillStyle = palette.ultramarine; // a hairline at the measure, and each strip's name
  ctx.fillRect(edge, 0, 2, PROOF.height);
  ctx.font = `700 ${(7 / 72) * 2 * DPI}px "IBM Plex Mono"`; // 7 pt, loaded by now
  ['early', 'last'].forEach((name, i) => // on the last line of each strip
    ctx.fillText(name, edge + 12, (i ? PROOF.height : strip) - 16));
  registerResourceImage('proof.png', canvas);
}
// #endregion

const markdown = String.raw`---
title: "House Specimen"
author: "Pellow Lane Press"
---

# Three faces, proofed {kicker="Pellow Lane Press · House specimen Nº 3" lead="Our text, display and label faces at work, and proof that each of them had arrived before these lines were set." glyphs="Ag" label="Noto Serif Display 900 italic · 240 pt" faces="Text: Ysabeau Office · Labels: IBM Plex Mono"}

A compositor in a metal shop could only set a line in a face that was in the case. Postext measures every word with the fonts the browser holds at that moment, so a page built a second too early is broken for a fallback face. These pages were built three times: once too early, on purpose, with no font file in the browser; again once Postext had loaded every face the design asks for; and a last time to print their list on page 3 and, on page 4, what the early build got wrong.

## Seven sizes of the text face

Ysabeau, drawn by Christian Thalmann, carries the letterforms of the Garamond tradition into a low-contrast sans serif. Its Office cut sets tabular lining figures and a level hyphen by default.

:::paragraphs{style="s7"}
:chip[7 pt]{style="size-1"} Credits and map legends, where small print needs open counters.
:::

:::paragraphs{style="s8"}
:chip[8 pt]{style="size-1"} Captions and table notes, where the tabular figures keep 1,048 and 2,096 in step.
:::

:::paragraphs{style="s9"}
:chip[9 pt]{style="size-1"} A reference column set close; the long ascenders keep the lines apart.
:::

:::paragraphs{style="s10"}
:chip[10 pt]{style="size"} Notes and asides, a size below the text they sit beside.
:::

:::paragraphs{style="s11"}
:chip[11 pt]{style="size"} The text of this booklet, eleven on fifteen and a half.
:::

:::paragraphs{style="s12"}
:chip[12 pt]{style="size"} A standfirst, or a first reader for children.
:::

:::paragraphs{style="s14"}
:chip[14 pt]{style="size"} A heading, or a line on a poster.
:::

## Beyond Latin-1

Spanish needs nothing beyond the latin file of each face. Polish and Czech need more: ż, ł, ř and ů live in a second file, latin-ext, which the browser fetches only when a load or a line asks for those letters.

:::paragraphs{style="pangram"}
:chip[es]{style="size"} El veloz murciélago hindú comía feliz cardillo y kiwi.

:chip[pl]{style="size"} Zażółć gęślą jaźń.

:chip[cs]{style="size"} Příliš žluťoučký kůň úpěl ďábelské ódy.
:::

:::pagebreak

## The proof

The table below is Postext’s own report. Before it measured a line of the second build, it read the design and the text for every face they ask for, in the text, headings, chips, table, captions, opener and running heads, and loaded each one for the letters these pages set. Once the pages were laid out it looked at the faces their lines were set in, and found none missing.

::resource{id="faces"}

Some faces in the table set nothing in this booklet. Postext loads the regular, the italic, the bold and the bold italic of the text face, because any paragraph may ask for them with a pair of asterisks. The two italics of the mono face were declared and never asked for, so the browser fetched no file for them.

A face with no file would not pass unnoticed. The browser sets a family nobody declared in a system face and fakes a missing bold by thickening the regular; Postext names both in its report and among the warnings of the finished document.

:::pagebreak

## What the early build got wrong

The early build ran before the browser had any of these files, so its words were measured in a fallback face. Drawn in the real faces, its lines no longer fit the measure.

::resource{id="proof"}

When the faces arrived, Postext dropped every width it had measured in their families, and the next build measured each word again.

:::paragraphs{style="colophon"}
Set in Ysabeau Office, Noto Serif Display and IBM Plex Mono (SIL OFL 1.1) · Text: original, CC BY 4.0 · Pellow Lane Press is imaginary.
:::
`; // content.<lang>.md, inlined by the Cookbook

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
// Every face the design may ask for (page 3 lists them), each declared from two files.
const FONTS = {
  'Ysabeau Office': ['400', '400i', '700', '700i'], // text, waterfall, pangrams, lead
  'Noto Serif Display': ['900', '900i'], // the glyphs, the title, the subheads
  'IBM Plex Mono': ['400', '400i', '700', '700i'], // labels, chips, the table, captions
};
const facesOf = (fonts) => Object.entries(fonts).flatMap(([family, specs]) => specs.map((spec) =>
  ({ family, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' })));

// #region declare: one FontFace per file, as a stylesheet has one @font-face rule per file
const SUBSETS = { // the characters each file covers, copied from the family's @font-face CSS
  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' };
const FILES = new Map(); // FontFace → the subset its file covers, for the audit
function declareFaces(fonts) { // Fontsource's static files stand in for your own /fonts/ folder
  for (const { family, weight, style } of facesOf(fonts)) {
    const id = family.toLowerCase().replaceAll(' ', '-');
    for (const [subset, unicodeRange] of Object.entries(SUBSETS)) {
      const file = `${id}@5/files/${id}-${subset}-${weight}-${style}.woff2`;
      // Adding a face fetches nothing: the file downloads when a load or a line needs it.
      const face = new FontFace(family, `url(https://cdn.jsdelivr.net/npm/@fontsource/${file})`,
        { weight: `${weight}`, style, unicodeRange });
      FILES.set(face, subset);
      document.fonts.add(face);
    }
  }
}
// #endregion

// #region audit: page 3's table: every face declared or set, the report's word, its files
const SET = { loaded: 'yes', synthesized: 'faked', missing: 'in a fallback' }; // the report
const nameOf = (f) => `${f.family.replaceAll('"', '')} ${f.weight} ${f.style}`; // or a FontFace
function auditOf(doc, report) {
  const found = Object.keys(SET).flatMap((kind) => report[kind].map((f) => [nameOf(f), kind]));
  const inPages = new Map(found);
  const loaded = [...FILES].filter(([face]) => face.status === 'loaded');
  const faces = new Map([...facesOf(FONTS), ...Object.keys(SET).flatMap((kind) => report[kind])]
    .map((f) => [nameOf(f), f])); // the declared faces, then any the pages set without a file
  const rows = [...faces].map(([name, f], i, all) => [
    i && all[i - 1][1].family === f.family ? '' : f.family, // each family named once
    `${f.weight}${f.style === 'italic' ? ' italic' : ''}`, SET[inPages.get(name)] ?? 'no',
    loaded.filter(([face]) => nameOf(face) === name).map(([, subset]) => subset).join(' · ')
      || 'none'].map((cell) => ({ content: cell })));
  // What else to read in a finished layout: its content warnings, its passes, its warnings.
  return { rows, note: `${report.loaded.length} of ${rows.length} faces set in the pages · `
    + `${loaded.length} of ${FILES.size} files fetched · fontFallback warnings: `
    + `${fallbacksIn(doc) || 'none'} · ${doc.converged ? '' : 'not '}converged · layout warnings: `
    + `${doc.warnings?.length || 'none'}` };
}
// #endregion

// ─── 4 · Build & show ───────────────────────────────────────────────────────
// #region answer: one call loads every face the config and the text ask for, then builds
// buildDocumentWithFonts starts with prepareFonts: it reads the config and the text for every
// face they ask for (text, headings, chips, table, captions, opener, running heads), in each
// weight and slant, and loads them for the characters the document sets. The page declares its
// files (declareFaces), so they load through document.fonts; a face nothing declares would be
// asked of a resolve(family, weight, style) option. Then it builds, reads the faces the pages
// are set in, loads any that the config did not name and builds again.
let report; // { loaded, missing, synthesized }: lists of { family, weight, style }
const build = () => buildDocumentWithFonts(content(), config(),
  { onFonts: (found) => { report = found; } }); // what the last look at the pages found

kitStatus('Loading fonts…'); // the kit's bar: it also reports any error thrown below
const early = buildDocument(content(), config()); // on purpose: the page has no font yet (page 4)
declareFaces(FONTS);
const fitted = await build(); // every face loaded before a line is measured
audit = auditOf(fitted, report); // page 3's table
drawProof(early, fitted); // page 4's picture
const doc = await build(); // nothing left to load: the same pages, table and picture filled in
showPages(doc, { title: 'Load every font before layout' });
// #endregion

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

## Варианты

### Передайте файлы через `resolve`

`kitFonts(FONTS)` в рецепте [«От строки Markdown до оформленной страницы»](https://postext.dev/ru/cookbook/first-page-from-markdown.md) ничего не объявляет: Postext спрашивает у его `resolve` файлы каждого начертания и сам добавляет их в `document.fonts`.

### Забудьте одно начертание

Уберите полужирное IBM Plex Mono, которым набраны надзаголовок, строка заголовка таблицы и метки подписей: браузер утолстит обычное, таблица пометит начертание словом `faked`, а примечание насчитает одно предупреждение `fontFallback`, где IBM Plex Mono 700 названо как `synthesized`.

```diff
-  'IBM Plex Mono': ['400', '400i', '700', '700i'], // labels, chips, the table, captions
+  'IBM Plex Mono': ['400', '400i', '700i'], // labels, chips, the table, captions
```

### Встройте те же начертания в PDF

`renderToPdf` встраивает байты, которые `fontProvider` возвращает для каждого начертания. Провайдер из рецепта [«Настоящий PDF с теми же встроенными шрифтами»](https://postext.dev/ru/cookbook/pdf-with-embedded-fonts.md) отдаёт латинские файлы Fontsource, а они кончаются на Latin-1: для ż, ł, ř и ů этого буклета пусть он возвращает из вашей папки файл начертания целиком.

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

- **Файлы Fontsource содержат буквы, но не символы.** Kit встраивает файл latin начертания из Fontsource, а также latin-ext для č, ł, † и greek для α, χ (у гарнитур, где он есть: у Lora и Gelasio его нет), когда они встречаются в тексте, на экране и в PDF. Символов вроде →, ≈, ✓ и ★ нет ни в одном из этих файлов, и в PDF они пропадают: нарисуйте их, наберите формулой или возьмите начертание, в файлах которого они есть.
- **Предупреждение вёрстки: Резервный шрифт в вёрстке** (`fontFallback`). Начертания, которым набран текст, не было среди загруженных, когда документ верстался (`reason: 'missing'`), или у гарнитуры нет файла для этой насыщенности либо наклона и браузер рисует их из другого начертания (`'synthesized'`), поэтому разрывы строк измерены не тем начертанием, которое встраивает PDF. Решение: Загрузите начертания до первой сборки: `prepareFonts(content, config, { resolve })` — или собирайте через `buildDocumentWithFonts`, которая ещё и загружает начертания, понадобившиеся страницам, и собирает заново. Для `synthesized` загрузите эту насыщенность или наклон либо задайте насыщенность, которая есть у гарнитуры. ([Документация](https://postext.dev/ru/docs/configuration-programmatic-usage.md#предупреждения-в-документе))
- **Предупреждение вёрстки: Отсутствует шрифт** (`missingFont`). Гарнитура из конфигурации не загрузилась в браузере, поэтому текст измерен и нарисован системным резервным шрифтом. Решение: Исправьте имя гарнитуры (одно, без стека CSS) и загрузите все начертания до первой сборки; в пене укажите их в FONTS. ([Документация](https://postext.dev/ru/docs/configuration-fonts-colors-viewers.md#предупреждения-об-отсутствующих-шрифтах))
- **Предупреждение вёрстки: Отсутствует вариант шрифта** (`missingFontVariant`). У собственной гарнитуры нет файла для насыщенности и наклона, которые есть в документе, например курсива или полужирного. Решение: Загрузите или объявите недостающий вариант либо откажитесь от этой насыщенности или наклона. ([Документация](https://postext.dev/ru/docs/configuration-fonts-colors-viewers.md#предупреждения-об-отсутствующих-шрифтах))

- Если вы загружаете начертание сами, `document.fonts.load(font)` без образца текста загрузит только файл с пробелом, то есть латинский, а ż и ř наберутся системным шрифтом. `prepareFonts` передаёт символы самого документа.
- `renderPageToCanvas` и `postext-pdf` обрезают каждую колонку в 2 пт за её краем, поэтому строка, измеренная более узким запасным шрифтом, теряет последние буквы. Сборка, которая её измеряла, называет начертание в `doc.contentWarnings` как `fontFallback`: прочтите этот список, прежде чем показывать или выгружать страницу.

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

- Рецепт: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Шрифты: Ysabeau Office (OFL-1.1), Noto Serif Display (OFL-1.1), IBM Plex Mono (OFL-1.1)
- Код: MIT · Образец содержания: CC-BY-4.0

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

- [№ 040 · Фирменные шрифты в вёрстке, PDF и пакете](https://postext.dev/ru/cookbook/brand-fonts-identity-manual.md): Руководство по стилю вымышленного метро на собственных файлах шрифтов: они загружены один раз для вёрстки, поставщика шрифтов PDF и пакета .postext. · Уровень 3 (Продвинутый) · Руководства, путеводители и справочники
- [№ 056 · Живой редактор с вёрсткой в Web Worker](https://postext.dev/ru/cookbook/web-worker-live-editor.md): Markdown рядом с карманной страницей: Web Worker верстает главу своими шрифтами, а каждое нажатие клавиши отменяет текущую сборку. · Уровень 3 (Продвинутый) · Художественная литература, драматургия и эссеистика
- [№ 012 · От строки Markdown к оформленной странице](https://postext.dev/ru/cookbook/first-page-from-markdown.md): Строка Markdown с метаданными набрана журнальными полосами в две колонки и нарисована на холсте: шесть именованных цветов вместо синего по умолчанию. · Уровень 2 (Средний) · Журналы и зины
