# Свой canvas: renderPage, rangeRects и caretAt

> Просмотр страниц, написанный вручную, без postext-viewer: renderPage рисует каждую страницу, rangeRects — выделение, caretAt и caretRect — курсор.

- Версия HTML: https://postext.dev/ru/cookbook/own-canvas-page-view
- Рецепт № 221 · Интеграция с CMS · Уровень 3 (Продвинутый) · Форматы вывода: Canvas, Управление на лету
- Жанры: Художественная литература, драматургия и эссеистика
- Требуется postext ≥ 1.103.0 · проверено с 1.103.1 · дата 2026-12-04
- Страницы: [1](https://postext.dev/cookbook/own-canvas-page-view/en/p01.webp?v=3650bf2d), [2](https://postext.dev/cookbook/own-canvas-page-view/en/p02.webp?v=3650bf2d)
- ![Две страницы на собственном холсте приложения: выделение, нарисованное четырёхугольниками из rangeRects, и курсор из caretRect, над ними выделенные слова и их диапазон в Markdown.](https://postext.dev/cookbook/own-canvas-page-view/en/s01.webp?v=3650bf2d)
- Последнее обновление: 2026-12-04
- Другие языки: [en](https://postext.dev/en/cookbook/own-canvas-page-view.md), [es](https://postext.dev/es/cookbook/own-canvas-page-view.md), [ca](https://postext.dev/ca/cookbook/own-canvas-page-view.md), [de](https://postext.dev/de/cookbook/own-canvas-page-view.md), [el](https://postext.dev/el/cookbook/own-canvas-page-view.md), [fr](https://postext.dev/fr/cookbook/own-canvas-page-view.md), [it](https://postext.dev/it/cookbook/own-canvas-page-view.md), [pt](https://postext.dev/pt/cookbook/own-canvas-page-view.md), [zh](https://postext.dev/zh/cookbook/own-canvas-page-view.md), [ja](https://postext.dev/ja/cookbook/own-canvas-page-view.md), [ar](https://postext.dev/ar/cookbook/own-canvas-page-view.md)

## Коротко

Две страницы книги о маяке, показанные на сайте кодом, который сайт написал сам. Абзац выделен синим, тонкий оранжевый курсор стоит внутри слова, а панель над страницами показывает выделенный текст.

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

Вторая глава книги *A Light on Skerry Rock* о маяке в просмотре страниц, который сайт пишет сам. Пакета просмотрщика нет: каждая страница — canvas сайта, один раз нарисованный через `renderPage`. Поверх него сайт рисует синее выделение на целый абзац и оранжевый курсор внутри слова «clockwork». Нажмите и протяните по странице, чтобы выделить; ведите указатель, и курсор идёт за ним от одной границы символа к другой. Панель над страницами показывает выделение как Markdown с позициями, то есть то, что инструмент рецензирования хранит рядом с комментарием.

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

- Как сделать собственный просмотр страницы на canvas, с выделением, без postext-viewer?

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

```js
// script.js, строк 132–171
function paint({ page, pageIndex, scale, base, canvas }) {
  const ctx = canvas.getContext('2d');
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.drawImage(base, 0, 0);
  ctx.setTransform(scale, 0, 0, scale, 0, 0); // from here on, page px as the layout gives them
  const [start, end] = [state.anchor, state.focus].sort((a, b) => a - b);
  ctx.fillStyle = 'rgb(47 111 214 / 0.28)';
  for (const piece of rangeRects(doc, { start, end }).filter((p) => p.pageIndex === pageIndex)) {
    ctx.beginPath(); // a quad, not a rect: right for turned frames and vertical pages too
    piece.quad.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));
    ctx.fill();
  }
  const caret = caretRect(doc, state.caret); // a line from the text's top to its foot
  if (caret?.pageIndex !== pageIndex) return;
  Object.assign(ctx, { strokeStyle: '#d9480f', lineWidth: 2.5 });
  ctx.beginPath();
  ctx.moveTo(caret.from.x, caret.from.y);
  ctx.lineTo(caret.to.x, caret.to.y);
  ctx.stroke();
}
// The pointer in page px, and the character boundary nearest it.
const hitOf = ({ page, pageIndex, canvas }, e) => {
  const r = canvas.getBoundingClientRect();
  return caretAt(doc, pageIndex, (e.clientX - r.left) * (page.width / r.width),
    (e.clientY - r.top) * (page.height / r.height));
};
for (const view of views) {
  view.canvas.addEventListener('pointerdown', (e) => {
    const hit = hitOf(view, e); // a press starts a new selection where it lands
    if (!hit) return;
    Object.assign(state, { anchor: hit.offset, focus: hit.offset, caret: hit.offset, drag: true });
    update();
  });
  view.canvas.addEventListener('pointermove', (e) => {
    const hit = hitOf(view, e); // the caret follows the pointer; a drag moves the focus too
    if (!hit) return;
    Object.assign(state, { caret: hit.offset }, state.drag && { focus: hit.offset });
    update();
  });
}
```

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

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

- [Геометрия текста (диапазоны и точки)](https://postext.dev/ru/docs/integration-geometry.md#текст-на-странице): rangeRects превращает диапазон Markdown в прямоугольники на страницах, а caretAt, wordAt и blockAt возвращают точку страницы к позиции, слову или блоку исходника.
- [Страницы на холсте](https://postext.dev/ru/docs/configuration-programmatic-usage.md#рендеринг-страницы-в-растр): buildDocument верстает Markdown с конфигурацией в страницы; renderPageToCanvas рисует любую страницу в любом масштабе.

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

- [Пометки на тексте](https://postext.dev/ru/docs/integration-marks.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#перенос-слов), [`page`](https://postext.dev/ru/docs/configuration-page-layout.md#страница)

**API**

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

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

- Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)

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

### 1 · Сверстайте обычную книжную страницу

```js
// script.js, строк 32–52
const opener = { enabled: true, minHeight: mm(36), slot: { elements: [
  { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: 'Source Sans 3',
    fontSize: pt(7.5), fontWeight: 600, letterSpacing: pt(1.4), textTransform: 'uppercase',
    color: col('accent'), placement: { anchor: { to: 'container', edge: 'top-left' },
      offset: { y: mm(4) } } },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Source Serif 4',
    fontSize: pt(22), lineHeight: 1.1, fontWeight: 600, color: col('ink'), align: 'left',
    overflow: 'wrap', placement: { anchor: { to: '#kicker', edge: 'below' },
      offset: { y: mm(2.5) }, size: { width: mm(90) } } },
] } };
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'Source Sans 3', fontSize: pt(7), fontWeight: 600,
  letterSpacing: pt(0.8), color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(10) } }, ...extra });
const folio = { color: col('accent') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-title', '{title}', 'even', 'top-left', OUTER + 7),
  head('recto-chapter', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 7)),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };
```

Просмотр ничего не знает об оформлении: опущенная начальная полоса с надзаголовком из атрибутов заголовка и колонтитулы, меняющие сторону вместе со страницей. Другая конфигурация даст другие страницы, и тот же код будет рисовать на них.

### 2 · Храните позиции, а не пиксели

```js
// script.js, строк 122–128
// The selection runs from `anchor` (where the press began) to `focus` (where the pointer is),
// in either order; the caret is one offset. A zoom or a new layout leaves them valid.
const at = (words) => markdown.indexOf(words);
const [from, to] = t({ en: ['The lens itself', 'paraffin burner.'],
  es: ['La lente misma', 'quemador de parafina.'] });
const state = { anchor: at(from), focus: at(to) + to.length, drag: false,
  caret: at(t({ en: 'clockwork', es: 'mecanismo de relojería' })) + 5 };
```

Сайт хранит три числа: где началось нажатие, где сейчас указатель и где курсор. Все три — позиции в Markdown, поэтому они значат то же самое после масштабирования или новой вёрстки, и именно их хранит комментарий. Pen открывается с выделенным абзацем и поставленным курсором, чтобы показать, что он делает, ещё до первого касания.

### 3 · Нарисуйте страницу, а поверх — в px страницы

Код приведён в [коротком ответе](https://postext.dev/ru/cookbook/own-canvas-page-view.md#короткий-ответ) выше. Каждая страница рисуется один раз в том размере, в каком её показывают; перерисовка копирует этот растр и задаёт масштаб контекста, поэтому куски из `rangeRects` и линия из `caretRect` рисуются как есть, в px страницы. Каждый кусок рисуется по своему `quad`: здесь это прямоугольник, на других страницах — повёрнутая или вертикальная фигура. `caretAt` превращает указатель, пересчитанный в px страницы, в ближайшую позицию. Все поля описаны в документации [Текст на странице](https://postext.dev/ru/docs/integration-geometry.md).

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

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

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

### index.html

```html
<main id="pages">
  <section id="view">
    <div id="bar" role="status">
      <span id="selection"></span>
      <span id="offsets"></span>
    </div>
    <div id="sheets"></div>
  </section>
</main>
```

### style.css

```css
/* The host's own page view: a status line over the pages, each page a canvas of its own. */
#view {
  display: grid; gap: 16px; justify-items: center; align-content: start;
  width: min(810px, 100%); min-height: min(608px, 75vw); /* the card's 4:3, pages and bar inside */
}
#bar {
  box-sizing: border-box; width: 100%; display: flex; flex-wrap: wrap;
  justify-content: space-between; gap: 4px 24px; padding: 10px 16px; border-radius: 6px;
  background: #16181d; border: 1px solid #23262d; color: #f4f1ea;
  font: 14px/1.4 system-ui, sans-serif;
}
#offsets { color: #b9bcc4; font-variant-numeric: tabular-nums; }
#sheets { display: flex; flex-wrap: wrap; gap: 24px; justify-content: center; }
#sheets canvas {
  display: block; max-width: 100%; background: #fff; cursor: text;
  touch-action: none; user-select: none;
  box-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 18px 40px -16px rgb(0 0 0 / .8);
}
```

### script.js

```js
// ═══ Postext Cookbook · Nº 221 · Your own canvas page view ═════════════════════════════
// https://postext.dev/en/cookbook/own-canvas-page-view
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Source Serif 4, Source Sans 3 (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A page view built by hand, without postext-viewer: each page painted once with renderPage,
// then a selection drawn from rangeRects and a caret from caretAt and caretRect, both following
// the pointer. The pen opens with a selection made and the caret in the next paragraph.
import {
  buildDocumentWithFonts, renderPage, renderPageToCanvas, rangeRects, caretAt, caretRect,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'own-canvas-page-view';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#1c1e21', // text
  accent: '#9a3b1f', // a lamp-room red: kicker, rule, folios
  muted: '#62676d', // 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, 13.5]; // mm from the outer edge to the folios; pt of body leading

// #region book: a chapter opener and running heads that change side with the page
const opener = { enabled: true, minHeight: mm(36), slot: { elements: [
  { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: 'Source Sans 3',
    fontSize: pt(7.5), fontWeight: 600, letterSpacing: pt(1.4), textTransform: 'uppercase',
    color: col('accent'), placement: { anchor: { to: 'container', edge: 'top-left' },
      offset: { y: mm(4) } } },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Source Serif 4',
    fontSize: pt(22), lineHeight: 1.1, fontWeight: 600, color: col('ink'), align: 'left',
    overflow: 'wrap', placement: { anchor: { to: '#kicker', edge: 'below' },
      offset: { y: mm(2.5) }, size: { width: mm(90) } } },
] } };
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'Source Sans 3', fontSize: pt(7), fontWeight: 600,
  letterSpacing: pt(0.8), color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(10) } }, ...extra });
const folio = { color: col('accent') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-title', '{title}', 'even', 'top-left', OUTER + 7),
  head('recto-chapter', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 7)),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };
// #endregion

const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(130), height: mm(195), dpi: 150,
    margins: { top: mm(18), bottom: mm(19), left: mm(17), right: mm(OUTER), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Source Serif 4', fontSize: pt(9.5), 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: 'Source Sans 3', color: col('ink'), fontWeight: 600, levels: [
    { level: 1, fontFamily: 'Source Serif 4', fontSize: pt(22), advancedDesign: opener },
    { level: 2, fontSize: pt(9), lineHeight: pt(LEAD), letterSpacing: pt(0.2),
      marginTop: pt(LEAD), marginBottom: pt(0) },
  ] },
  header,
  footer: { elements: [] },
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "A Light on Skerry Rock"
author: "Mairi Fraser"
---

# The lamp room {kicker="Chapter two"}

The lamp room sits at the top of the tower, above the watch room and reached by an iron ladder through a hatch in the floor. It is a cage of brass and glass eleven feet across, and on a winter night it was the only warm place on the rock. The keeper on watch climbed to it every hour from sunset to sunrise, trimmed the wick, wound the clockwork and wrote the state of the light in the log.

The lens itself was made in Paris in 1871: a drum of glass prisms taller than a man, ground so that every ray from the flame left the tower as a level beam. It weighed nearly four tons and turned on a bath of mercury, so smoothly that a child could push it round with one finger. At its centre stood the paraffin burner. Three concentric wicks gave a flame about the size of a fist, and the lens made of it a flash that ships could see at twenty miles.

Each light on the coast had its own character, so that a master could tell one from another in the dark. Skerry Rock gave two white flashes every fifteen seconds. The timing came from the clockwork in the pedestal, driven by a weight that ran down a tube in the middle of the tower. It needed winding every forty minutes, and a keeper who fell asleep in the watch room woke to a light that had stopped turning. The log records that this happened twice in sixty years, and both times the keeper was fined a week’s pay.

## The daily round

Work in the lamp room began at dawn, when the light was put out. The keeper drew the curtains round the lantern so that the sun would not strike through the lens and set fire to the burner, a danger as real in March as in July. Then came the cleaning. The prisms were wiped with a linen cloth and polished with rouge, the brass with a mixture of whiting and spirit. Soot from the flame settled on everything overnight, and a lens left dirty for a week lost a third of its range.

In the afternoon the keeper filled the reservoir with paraffin, carried up in cans from the store at the foot of the tower, and fitted new wicks if the old ones had burned unevenly. The instructions from the Board ran to forty pages and were read aloud to every new assistant on his first day. Most of them dealt with the lamp room, and the last page ended with a line every keeper knew by heart: the light is never to be left.
`; // content.<lang>.md, inlined by the Cookbook

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = {
  'Source Serif 4': ['400', '400i', '600'],
  'Source Sans 3': ['600'],
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown }, config, kitFonts(FONTS));
kitStatus(t({ en: 'The lamp room · a canvas of your own', es: 'La linterna · un canvas propio' }));

// Each page is painted once at the size it is shown; a repaint copies it and draws over it.
const SHOWN = 336; // CSS px per page
const density = Math.min(window.devicePixelRatio || 1, 2);
const views = doc.pages.map((page, pageIndex) => {
  const scale = (SHOWN * density) / page.width;
  const base = renderPage(page, doc, { scale });
  const canvas = Object.assign(document.createElement('canvas'),
    { width: base.width, height: base.height });
  canvas.style.width = `${SHOWN}px`;
  canvas.setAttribute('role', 'img');
  canvas.setAttribute('aria-label', t({ en: 'Page', es: 'Página' }) + ` ${pageIndex + 1}`);
  return { page, pageIndex, scale, base, canvas };
});
document.getElementById('sheets').replaceChildren(...views.map((v) => v.canvas));

// #region state: what the host keeps, Markdown offsets and never pixels
// The selection runs from `anchor` (where the press began) to `focus` (where the pointer is),
// in either order; the caret is one offset. A zoom or a new layout leaves them valid.
const at = (words) => markdown.indexOf(words);
const [from, to] = t({ en: ['The lens itself', 'paraffin burner.'],
  es: ['La lente misma', 'quemador de parafina.'] });
const state = { anchor: at(from), focus: at(to) + to.length, drag: false,
  caret: at(t({ en: 'clockwork', es: 'mecanismo de relojería' })) + 5 };
// #endregion

// #region answer: paint the page, then the selection's pieces and the caret, in page px
function paint({ page, pageIndex, scale, base, canvas }) {
  const ctx = canvas.getContext('2d');
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.drawImage(base, 0, 0);
  ctx.setTransform(scale, 0, 0, scale, 0, 0); // from here on, page px as the layout gives them
  const [start, end] = [state.anchor, state.focus].sort((a, b) => a - b);
  ctx.fillStyle = 'rgb(47 111 214 / 0.28)';
  for (const piece of rangeRects(doc, { start, end }).filter((p) => p.pageIndex === pageIndex)) {
    ctx.beginPath(); // a quad, not a rect: right for turned frames and vertical pages too
    piece.quad.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));
    ctx.fill();
  }
  const caret = caretRect(doc, state.caret); // a line from the text's top to its foot
  if (caret?.pageIndex !== pageIndex) return;
  Object.assign(ctx, { strokeStyle: '#d9480f', lineWidth: 2.5 });
  ctx.beginPath();
  ctx.moveTo(caret.from.x, caret.from.y);
  ctx.lineTo(caret.to.x, caret.to.y);
  ctx.stroke();
}
// The pointer in page px, and the character boundary nearest it.
const hitOf = ({ page, pageIndex, canvas }, e) => {
  const r = canvas.getBoundingClientRect();
  return caretAt(doc, pageIndex, (e.clientX - r.left) * (page.width / r.width),
    (e.clientY - r.top) * (page.height / r.height));
};
for (const view of views) {
  view.canvas.addEventListener('pointerdown', (e) => {
    const hit = hitOf(view, e); // a press starts a new selection where it lands
    if (!hit) return;
    Object.assign(state, { anchor: hit.offset, focus: hit.offset, caret: hit.offset, drag: true });
    update();
  });
  view.canvas.addEventListener('pointermove', (e) => {
    const hit = hitOf(view, e); // the caret follows the pointer; a drag moves the focus too
    if (!hit) return;
    Object.assign(state, { caret: hit.offset }, state.drag && { focus: hit.offset });
    update();
  });
}
// #endregion
addEventListener('pointerup', () => { state.drag = false; });

// The host's status line: what is selected, as Markdown, and where the caret stands.
function update() {
  views.forEach(paint);
  const [start, end] = [state.anchor, state.focus].sort((a, b) => a - b);
  const words = markdown.slice(start, end).replace(/\s+/g, ' ');
  const shown = words.length > 90 ? `${words.slice(0, 88)}…` : words;
  $('selection').textContent = start === end
    ? t({ en: 'Nothing selected', es: 'Nada seleccionado' }) : `“${shown}”`;
  $('offsets').textContent = t({ en: `Markdown ${start}–${end} · caret at ${state.caret}`,
    es: `Markdown ${start}–${end} · cursor en ${state.caret}` });
}
function $(id) { return document.getElementById(id); }
update();

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

## Варианты

### Выделение слова двойным щелчком

`wordAt` расширяет позицию под точкой до слова вокруг неё, по правилам языка документа (импортируйте её рядом с `caretAt`).

```diff
+  view.canvas.addEventListener('dblclick', (e) => {
+    const r = view.canvas.getBoundingClientRect();
+    const word = wordAt(doc, view.pageIndex, (e.clientX - r.left) * (view.page.width / r.width),
+      (e.clientY - r.top) * (view.page.height / r.height), markdown);
+    if (!word) return;
+    Object.assign(state, { anchor: word.start, focus: word.end });
+    update();
+  });
```

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

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

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

- [№ 212 · Выделить на странице, прочитать диапазон и текст Markdown](https://postext.dev/ru/cookbook/selection-as-markdown-range.md): postext-viewer сообщает о выделении на свёрстанных страницах как о диапазоне в Markdown, вместе с охваченным Markdown и его кусками по строкам. · Уровень 1 (Базовый) · Журналы и зины
- [№ 216 · Щелчок по странице ведёт к исходному тексту](https://postext.dev/ru/cookbook/click-to-markdown-source.md): sourceAt и caretAt превращают щелчок по свёрстанной странице в блок Markdown и позицию; CMS показывает эту строку исходника с пометкой. · Уровень 2 (Средний) · Руководства, путеводители и справочники
- [№ 211 · Книга в просмотрщике страниц: масштаб и переход](https://postext.dev/ru/cookbook/book-in-a-page-viewer.md): createViewer из postext-viewer показывает свёрстанную главу столбцом страниц внутри CMS, а кнопки масштаба и счётчик страниц остаются за самим сайтом. · Уровень 2 (Средний) · Руководства, путеводители и справочники
