# Книга в просмотрщике страниц: масштаб и переход

> createViewer из postext-viewer показывает свёрстанную главу столбцом страниц внутри CMS, а кнопки масштаба и счётчик страниц остаются за самим сайтом.

- Версия HTML: https://postext.dev/ru/cookbook/book-in-a-page-viewer
- Рецепт № 211 · Интеграция с CMS · Уровень 2 (Средний) · Форматы вывода: Canvas, Управление на лету
- Жанры: Руководства, путеводители и справочники
- Требуется postext ≥ 1.103.0 · проверено с 1.103.1 · дата 2026-12-04
- Страницы: [1](https://postext.dev/cookbook/book-in-a-page-viewer/en/p01.webp?v=80921e6a), [2](https://postext.dev/cookbook/book-in-a-page-viewer/en/p02.webp?v=80921e6a), [3](https://postext.dev/cookbook/book-in-a-page-viewer/en/p03.webp?v=80921e6a)
- ![Просмотрщик сразу после открытия: целая страница Flour, Water, Salt под собственной панелью инструментов приложения со счётчиком страниц и кнопками масштаба.](https://postext.dev/cookbook/book-in-a-page-viewer/en/s01.webp?v=80921e6a)
- ![После Fit width и перехода на следующую страницу: на панели «Page 2 of 3» и 139 %, текст в размере для чтения.](https://postext.dev/cookbook/book-in-a-page-viewer/en/s02.webp?v=80921e6a)
- Последнее обновление: 2026-12-04
- Другие языки: [en](https://postext.dev/en/cookbook/book-in-a-page-viewer.md), [es](https://postext.dev/es/cookbook/book-in-a-page-viewer.md), [ca](https://postext.dev/ca/cookbook/book-in-a-page-viewer.md), [de](https://postext.dev/de/cookbook/book-in-a-page-viewer.md), [el](https://postext.dev/el/cookbook/book-in-a-page-viewer.md), [fr](https://postext.dev/fr/cookbook/book-in-a-page-viewer.md), [it](https://postext.dev/it/cookbook/book-in-a-page-viewer.md), [pt](https://postext.dev/pt/cookbook/book-in-a-page-viewer.md), [zh](https://postext.dev/zh/cookbook/book-in-a-page-viewer.md), [ja](https://postext.dev/ja/cookbook/book-in-a-page-viewer.md), [ar](https://postext.dev/ar/cookbook/book-in-a-page-viewer.md)

## Коротко

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

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

Третья глава книги *Flour, Water, Salt*, руководства по выпечке хлеба в формате 140 × 210 мм, показанная на сайте так, как редакционная система показывает корректуру. Страницы идут вниз по тёмному столбцу, каждая на своём белом листе, а над ними панель с тем, что нужно корректору: назад и вперёд, уменьшить и увеличить, вписать по ширине, страница целиком и счётчик с текущей страницей и общим числом. Панель принадлежит сайту. Просмотрщик рисует страницы, следит за прокруткой и сообщает о каждой смене страницы и масштаба; сайт рисует свои кнопки по этим сообщениям.

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

- Как показать свёрстанную книгу внутри своей CMS, с масштабом и переходом по страницам?

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

```js
// script.js, строк 148–176
// `view`, not `viewer`: the kit's viewer block declares a function of that name.
const view = createViewer(document.getElementById('viewer'), {
  document: doc,
  markdown, // the source: copying a selection gives the Markdown, not the painted text
  zoom: 'fit-page', // a whole page in view; a number is CSS px per page px
  minZoom: 0.4, maxZoom: 3, gap: 24,
  labels: labels.viewer, // what a screen reader hears: "Page 3 of 41", the selection's size
});
const $ = (id) => document.getElementById(id);
// The viewer says what changed; the host draws its own controls from that.
const showPage = (i) => {
  const folio = doc.pages[i].pageLabel || String(i + 1);
  $('counter').textContent = t({ en: `Page ${folio} of ${doc.pages.length}`,
    es: `Página ${folio} de ${doc.pages.length}` });
  $('prev').disabled = i === 0;
  $('next').disabled = i === doc.pages.length - 1;
};
view.on('pagechange', ({ pageIndex }) => showPage(pageIndex));
const showZoom = (zoom) => { $('percent').textContent = `${Math.round(zoom * 100)} %`; };
view.on('zoomchange', ({ zoom }) => showZoom(zoom));
const clicks = {
  prev: () => view.goToPage(view.pageIndex - 1),
  next: () => view.goToPage(view.pageIndex + 1),
  'zoom-out': () => view.setZoom(view.zoom / 1.25), // clamped to minZoom by the viewer
  'zoom-in': () => view.setZoom(view.zoom * 1.25),
  'fit-width': () => view.setZoom('fit-width'), // a fitted mode follows the container
  'fit-page': () => view.setZoom('fit-page'),
};
for (const [id, run] of Object.entries(clicks)) $(id).addEventListener('click', run);
```

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

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

- [Просмотрщик страниц (postext-viewer)](https://postext.dev/ru/docs/integration-viewer.md#просмотрщик-страниц): postext-viewer показывает страницы свёрстанного документа в прокручиваемой колонке внутри страницы другого приложения: масштаб, переход по страницам, выделения в виде диапазонов Markdown, пометки и слои поверх текста.

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

- [Страницы на холсте](https://postext.dev/ru/docs/configuration-programmatic-usage.md#рендеринг-страницы-в-растр)
- [Шрифты до вёрстки](https://postext.dev/ru/docs/configuration-programmatic-usage.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-page-layout.md#зеркальные-поля)
- [Семантическая палитра](https://postext.dev/ru/docs/configuration-fonts-colors-viewers.md#палитра-цветов)
- [Колонтитулы по роли страницы](https://postext.dev/ru/docs/configuration-headers-footers.md#текстовые-элементы)

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

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

**API**

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

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

- Literata (OFL-1.1), Fraunces (OFL-1.1), Work Sans (OFL-1.1)

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

### 1 · Сверстайте страницу, которая выдержит лупу

```js
// script.js, строк 31–54
const opener = { enabled: true, minHeight: mm(46), slot: { elements: [
  { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: 'Work Sans',
    fontSize: pt(7.5), fontWeight: 600, letterSpacing: pt(1.5), textTransform: 'uppercase',
    color: col('accent'), align: 'left', placement: { anchor: { to: 'container', edge: 'top-left' },
      offset: { y: mm(8) } } },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Fraunces', fontSize: pt(26),
    lineHeight: 1.05, fontWeight: 600, color: col('ink'), align: 'left', overflow: 'wrap',
    placement: { anchor: { to: '#kicker', edge: 'below' }, offset: { y: mm(3) },
      size: { width: mm(90) } } },
  { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(1.25), color: col('accent'),
    placement: { anchor: { to: '#title', edge: 'below' }, offset: { y: mm(4) },
      size: { width: mm(12) } } },
] } };
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'Work Sans', fontSize: pt(7), fontWeight: 500,
  letterSpacing: pt(1.1), textTransform: 'uppercase', color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(11) } }, ...extra });
const folio = { fontWeight: 600, color: col('accent') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-title', '{title}', 'even', 'top-left', OUTER + 8),
  head('recto-chapter', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 8)),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };
```

Просмотрщик увеличивает до 300 %, и страница должна это выдержать: опущенная начальная полоса с надзаголовком из атрибутов заголовка и колонтитулы, меняющие сторону вместе со страницей. Та же конфигурация пошла бы в печать; просмотрщик ничего не добавляет к вёрстке.

### 2 · Откройте просмотрщик и слушайте его

Код приведён в [коротком ответе](https://postext.dev/ru/cookbook/book-in-a-page-viewer.md#короткий-ответ) выше. `createViewer` заполняет свой контейнер, поэтому контейнеру нужна высота, здесь это высота окна минус панель. В первом кадре просмотрщик сообщает начальный масштаб и страницу, поэтому панель слушает только `zoomchange` и `pagechange`. Кнопки масштаба умножают текущее значение; просмотрщик держит его между `minZoom` и `maxZoom` и сохраняет видимое место.

### 3 · Назовите всё на языке читателя

```js
// script.js, строк 135–144
const labels = t({
  en: { prev: 'Previous page', next: 'Next page', 'zoom-out': 'Zoom out', 'zoom-in': 'Zoom in',
    'fit-width': 'Fit width', 'fit-page': 'Whole page', tools: 'Pages',
    viewer: {} }, // the viewer speaks English unless told otherwise
  es: { prev: 'Página anterior', next: 'Página siguiente', 'zoom-out': 'Reducir',
    'zoom-in': 'Ampliar', 'fit-width': 'Ajustar al ancho', 'fit-page': 'Página entera',
    tools: 'Páginas',
    viewer: { viewer: 'Páginas del libro', page: 'Página {n} de {count}',
      selection: '{count} caracteres seleccionados', selectionCleared: 'Selección borrada' } },
});
```

Просмотрщик называет свою область и каждую страницу для экранных чтецов и сообщает длину выделения. По-английски ему ничего не нужно; испанское издание передаёт свои `labels`, а кнопки панели получают имена, потому что две из них показывают только стрелку или знак. Все подписи и параметры перечислены в документации [просмотрщика страниц](https://postext.dev/ru/docs/integration-viewer.md).

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

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

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

### index.html

```html
<main id="pages">
  <nav id="tools">
    <div class="group">
      <button id="prev" type="button">‹</button>
      <span id="counter" role="status"></span>
      <button id="next" type="button">›</button>
    </div>
    <div class="group">
      <button id="zoom-out" type="button">−</button>
      <span id="percent"></span>
      <button id="zoom-in" type="button">+</button>
      <button id="fit-width" type="button" class="word"></button>
      <button id="fit-page" type="button" class="word"></button>
    </div>
  </nav>
  <div id="viewer"></div>
</main>
```

### style.css

```css
/* The host's frame: a toolbar over the viewer. The viewer fills its container,
   so the container gets a height: whatever the window leaves under the toolbar. */
main#pages {
  display: flex; flex-direction: column; height: max(540px, 100vh);
  justify-items: normal; padding: 0;
}
#tools {
  display: flex; flex-wrap: wrap; justify-content: space-between; gap: 8px 24px;
  padding: 8px 16px; background: #16181d; border-bottom: 1px solid #23262d;
  font: 500 14px/1.2 system-ui, sans-serif; color: #f4f1ea;
}
#tools .group { display: flex; align-items: center; gap: 6px; }
#tools button {
  min-width: 44px; min-height: 44px; padding: 0 12px; border: 1px solid #4a505b;
  border-radius: 6px; background: #1f2229; color: #f4f1ea; font: inherit; font-size: 18px;
  cursor: pointer;
}
#tools button.word { font-size: 14px; }
#tools button:hover:not(:disabled) { border-color: #d8a21a; }
#tools button:disabled { color: #6c7079; cursor: default; }
#tools button:focus-visible { outline: 2px solid #d8a21a; outline-offset: 2px; }
#counter, #percent { min-width: 7.5em; text-align: center; font-variant-numeric: tabular-nums; }
#percent { min-width: 4.5em; }
#viewer { flex: 1; min-height: 0; }
/* The viewer's look: custom properties on its own element (.postext-viewer). */
#viewer .postext-viewer {
  --pv-background: #0e1014;
  --pv-page-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 18px 40px -16px rgb(0 0 0 / .8);
  --pv-focus: #d8a21a;
}
```

### script.js

```js
// ═══ Postext Cookbook · Nº 211 · A book in a page viewer ══════════════════════════════
// https://postext.dev/en/cookbook/book-in-a-page-viewer
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Literata, Fraunces, Work Sans (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A chapter of a baking manual, laid out once and shown in postext-viewer as a CMS would show
// it: a scrolling column of pages, zoom buttons, fit to the width or to the page, and a page
// counter. The toolbar is the host's own; the viewer only reports what changed.
import { buildDocumentWithFonts, renderPageToCanvas } from 'https://esm.sh/postext';
import { createViewer } from 'https://esm.sh/postext-viewer';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'book-in-a-page-viewer';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#1f1c19', // text: a warm near-black
  accent: '#8a4b1f', // crust brown: kicker, rule, list numbers, folios
  muted: '#6f675e', // running heads
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion
const [OUTER, LEAD] = [15, 14]; // mm from the outer edge to the folios; pt of body leading

// #region book: a manual's page, a sunk chapter opener and running heads by parity
const opener = { enabled: true, minHeight: mm(46), slot: { elements: [
  { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: 'Work Sans',
    fontSize: pt(7.5), fontWeight: 600, letterSpacing: pt(1.5), textTransform: 'uppercase',
    color: col('accent'), align: 'left', placement: { anchor: { to: 'container', edge: 'top-left' },
      offset: { y: mm(8) } } },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Fraunces', fontSize: pt(26),
    lineHeight: 1.05, fontWeight: 600, color: col('ink'), align: 'left', overflow: 'wrap',
    placement: { anchor: { to: '#kicker', edge: 'below' }, offset: { y: mm(3) },
      size: { width: mm(90) } } },
  { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(1.25), color: col('accent'),
    placement: { anchor: { to: '#title', edge: 'below' }, offset: { y: mm(4) },
      size: { width: mm(12) } } },
] } };
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'Work Sans', fontSize: pt(7), fontWeight: 500,
  letterSpacing: pt(1.1), textTransform: 'uppercase', color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(11) } }, ...extra });
const folio = { fontWeight: 600, color: col('accent') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-title', '{title}', 'even', 'top-left', OUTER + 8),
  head('recto-chapter', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 8)),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };
// #endregion

const config = {
  locale: t({ en: 'en-us', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(140), height: mm(210), dpi: 150,
    margins: { top: mm(20), bottom: mm(22), left: mm(18), right: mm(OUTER), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Literata', fontSize: pt(9.8), lineHeight: pt(LEAD),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'justify', firstLineIndent: mm(4), indentAfterHeading: false,
    hyphenation: { enabled: true }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: 'Work Sans', color: col('ink'), fontWeight: 600, levels: [
    { level: 1, fontFamily: 'Fraunces', fontSize: pt(26), advancedDesign: opener },
    { level: 2, fontSize: pt(9.5), lineHeight: pt(LEAD), letterSpacing: pt(0.3),
      marginTop: pt(LEAD), marginBottom: pt(0) },
  ] },
  orderedLists: { numberFormat: 'arabic', color: col('accent'), fontWeight: 600,
    marginTop: pt(0), marginBottom: pt(0) },
  header,
  footer: { elements: [] },
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "Flour, Water, Salt"
author: "Elena Marsh"
---

# Keeping a levain {kicker="Chapter three"}

A levain is a paste of flour and water in which wild yeasts and lactic acid bacteria live together. It raises the dough, as baker’s yeast does, and it also sours it: the bacteria turn some of the flour’s sugars into lactic and acetic acid, and those acids give a naturally leavened loaf much of its taste and keep it from going stale for days. A levain is not difficult to keep. It asks for the same few things every day, at about the same hour.

## Starting from nothing

Mix 50 g of wholemeal rye flour with 50 g of water at 26 °C in a clean jar, cover it loosely and leave it somewhere warm. Rye is the easiest start: its bran carries more yeasts, and more of the enzymes that free sugar from starch, than white wheat flour does. After 24 hours, throw away all but 50 g, add another 50 g of flour and 50 g of water, and stir. Repeat once a day.

For the first three days the jar may rise fast and smell of cheese or old socks. That is the work of bacteria that thrive in a neutral paste and die off as it turns acid. Around the fourth or fifth day the activity drops, and many people give up here. Keep feeding. Between the sixth and the tenth day the smell turns to yoghurt and green apple, and the paste doubles within six to eight hours of a feed. Then it is ready to bake with.

## The daily feed

Once established, a levain is fed in proportions written as three numbers: levain, flour and water. A feed of 1:5:5 means 10 g of ripe levain, 50 g of flour and 50 g of water. The larger the feed, the longer the levain takes to peak, which lets the baker choose the hour:

1. At 1:1:1 and 24 °C, a levain peaks in about four hours.
2. At 1:5:5, it peaks in eight to ten hours: fed at ten at night, it is ready at breakfast.
3. At 1:10:10 and a cool 20 °C, it can stand for fourteen hours or more.

A ripe levain has a domed top, a web of bubbles against the glass and a smell that is sour but clean. A spoonful dropped into water floats. If the dome has fallen and a grey liquid sits on top, the levain has gone past its peak; it will still raise bread, but the loaf will be more sour and its crumb closer.

## Flour and water

Feed the levain with the flour you bake with, and keep a little rye in the mix if it seems slow: one part rye to four parts white flour is enough to wake it. Tap water is fine in most towns. Chlorine at the levels found in drinking water does not kill a healthy culture, though some bakers leave a jug standing overnight. Water from a domestic softener is another matter: the sodium it adds slows fermentation, so draw from a tap before the softener.

Hydration changes the character of the culture. A stiff levain, at 50 or 60 % water, ferments slowly, favours acetic acid and gives a sharper loaf. A liquid one, at 100 % or more, ferments quickly and gives a milder, more lactic taste. Neither is better than the other; they make two different breads.

## Holidays and the refrigerator

A levain can live in the refrigerator for a week between feeds. Feed it, leave it on the counter for two hours, then close the lid and put it on a middle shelf. Before baking, take it out the evening before and give it two feeds at room temperature. The first will be sluggish; after the second it behaves as it did before.

For longer absences, dry some. Spread a thin layer of ripe levain on baking paper, let it dry at room temperature for two days, crumble it and keep it in a sealed jar. A tablespoon of the flakes, soaked in 50 g of water and fed as on the first day, will be active again within three to five days.

## When something goes wrong

A pink or orange tint, or fuzzy patches on the surface, mean that moulds or other organisms have taken hold. Throw the whole jar away and start again from a dried reserve. A levain that smells of nail-polish remover is only hungry: the yeasts make ethyl acetate when their food runs out. Feed it more often, or with a larger share of flour, and the smell goes within a day or two.
`; // content.<lang>.md, inlined by the Cookbook

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = {
  Literata: ['400', '400i'],
  Fraunces: ['600'],
  'Work Sans': ['500', '600'],
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
// The fonts load before the build, and the viewer paints with the same faces.
const doc = await buildDocumentWithFonts({ markdown }, config, kitFonts(FONTS));
kitStatus(t({ en: 'Flour, Water, Salt · a page viewer', es: 'Harina, agua y sal · un visor' }));

// #region labels: the toolbar and the viewer's announcements in the edition's language
const labels = t({
  en: { prev: 'Previous page', next: 'Next page', 'zoom-out': 'Zoom out', 'zoom-in': 'Zoom in',
    'fit-width': 'Fit width', 'fit-page': 'Whole page', tools: 'Pages',
    viewer: {} }, // the viewer speaks English unless told otherwise
  es: { prev: 'Página anterior', next: 'Página siguiente', 'zoom-out': 'Reducir',
    'zoom-in': 'Ampliar', 'fit-width': 'Ajustar al ancho', 'fit-page': 'Página entera',
    tools: 'Páginas',
    viewer: { viewer: 'Páginas del libro', page: 'Página {n} de {count}',
      selection: '{count} caracteres seleccionados', selectionCleared: 'Selección borrada' } },
});
// #endregion

// #region answer: the viewer in the host's container, and a toolbar it keeps up to date
// `view`, not `viewer`: the kit's viewer block declares a function of that name.
const view = createViewer(document.getElementById('viewer'), {
  document: doc,
  markdown, // the source: copying a selection gives the Markdown, not the painted text
  zoom: 'fit-page', // a whole page in view; a number is CSS px per page px
  minZoom: 0.4, maxZoom: 3, gap: 24,
  labels: labels.viewer, // what a screen reader hears: "Page 3 of 41", the selection's size
});
const $ = (id) => document.getElementById(id);
// The viewer says what changed; the host draws its own controls from that.
const showPage = (i) => {
  const folio = doc.pages[i].pageLabel || String(i + 1);
  $('counter').textContent = t({ en: `Page ${folio} of ${doc.pages.length}`,
    es: `Página ${folio} de ${doc.pages.length}` });
  $('prev').disabled = i === 0;
  $('next').disabled = i === doc.pages.length - 1;
};
view.on('pagechange', ({ pageIndex }) => showPage(pageIndex));
const showZoom = (zoom) => { $('percent').textContent = `${Math.round(zoom * 100)} %`; };
view.on('zoomchange', ({ zoom }) => showZoom(zoom));
const clicks = {
  prev: () => view.goToPage(view.pageIndex - 1),
  next: () => view.goToPage(view.pageIndex + 1),
  'zoom-out': () => view.setZoom(view.zoom / 1.25), // clamped to minZoom by the viewer
  'zoom-in': () => view.setZoom(view.zoom * 1.25),
  'fit-width': () => view.setZoom('fit-width'), // a fitted mode follows the container
  'fit-page': () => view.setZoom('fit-page'),
};
for (const [id, run] of Object.entries(clicks)) $(id).addEventListener('click', run);
// #endregion

// The buttons are named for screen readers, and the two word buttons say it on screen.
for (const id of Object.keys(clicks)) $(id).setAttribute('aria-label', labels[id]);
$('fit-width').textContent = labels['fit-width'];
$('fit-page').textContent = labels['fit-page'];
$('tools').setAttribute('aria-label', labels.tools);

// The states the Cookbook photographs: the second page, fitted to the width.
kitShots({ reading: async () => {
  view.setZoom('fit-width');
  await new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done)));
  view.goToPage(1);
} });

// ─── 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 · shots v1 ── developer recipes, photographed while they run
/** The states the Cookbook photographs the pen in, in order, after its first
 *  view: each an async function that puts the page in that state (a passage
 *  selected, a note open). The recipe page shows these pictures in place of
 *  the bare pages. Your own app leaves this call out. */
function kitShots(states) {
  window.__cbShots = states;
}

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

## Варианты

### Открывайте по ширине столбца

Для вычитки страница шириной с окно читается лучше, чем страница целиком.

```diff
-  zoom: 'fit-page', // a whole page in view; a number is CSS px per page px
+  zoom: 'fit-width', // the page as wide as the container; the column scrolls
```

### Листайте страницы в 3D

[Свёрстанная книга на столе в 3D](https://postext.dev/ru/cookbook/folio-book-on-a-desk.md) открывает такой же документ как книгу, которую читатель листает рукой.

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

- Рецепт: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Шрифты: Literata (OFL-1.1), Fraunces (OFL-1.1), Work Sans (OFL-1.1)
- Код: MIT · Образец содержания: CC-BY-4.0

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

- [№ 213 · Выделение цветом по списку диапазонов](https://postext.dev/ru/cookbook/highlights-from-ranges.md): Записи инструмента рецензирования, каждая — диапазон в Markdown и вердикт, нарисованные на страницах выделениями трёх цветов через setAnnotations. · Уровень 1 (Базовый) · Газеты и информационные бюллетени
- [№ 216 · Щелчок по странице ведёт к исходному тексту](https://postext.dev/ru/cookbook/click-to-markdown-source.md): sourceAt и caretAt превращают щелчок по свёрстанной странице в блок Markdown и позицию; CMS показывает эту строку исходника с пометкой. · Уровень 2 (Средний) · Руководства, путеводители и справочники
- [№ 221 · Свой canvas: renderPage, rangeRects и caretAt](https://postext.dev/ru/cookbook/own-canvas-page-view.md): Просмотр страниц, написанный вручную, без postext-viewer: renderPage рисует каждую страницу, rangeRects — выделение, caretAt и caretRect — курсор. · Уровень 3 (Продвинутый) · Художественная литература, драматургия и эссеистика
