# Заметки на полях и всплывающее окно по координатам

> Заметки подкрашивают свои слова и ставят флажок на внешнем поле; нажатие открывает заметку во всплывающем окне под словами через rangeRects и pageToClient.

- Версия HTML: https://postext.dev/ru/cookbook/margin-notes-with-popovers
- Рецепт № 215 · Интеграция с CMS · Уровень 2 (Средний) · Форматы вывода: Canvas
- Жанры: Каталоги
- Требуется postext ≥ 1.103.0 · проверено с 1.103.1 · дата 2026-12-04
- Страницы: [1](https://postext.dev/cookbook/margin-notes-with-popovers/en/p01.webp?v=b0783e83)
- ![Четыре заметки рецензента к музейному тексту: каждая подкрашивает свои слова и ведёт пунктир к пронумерованному флажку на широком поле; заметка 2 открыта под своими словами.](https://postext.dev/cookbook/margin-notes-with-popovers/en/s01.webp?v=b0783e83)
- ![Заметка 1, открытая с флажка: всплывающее окно переходит под первую строку, его место считается по координатам страницы через rangeRects и pageToClient.](https://postext.dev/cookbook/margin-notes-with-popovers/en/s02.webp?v=b0783e83)
- Последнее обновление: 2026-12-04
- Другие языки: [en](https://postext.dev/en/cookbook/margin-notes-with-popovers.md), [es](https://postext.dev/es/cookbook/margin-notes-with-popovers.md), [ca](https://postext.dev/ca/cookbook/margin-notes-with-popovers.md), [de](https://postext.dev/de/cookbook/margin-notes-with-popovers.md), [el](https://postext.dev/el/cookbook/margin-notes-with-popovers.md), [fr](https://postext.dev/fr/cookbook/margin-notes-with-popovers.md), [it](https://postext.dev/it/cookbook/margin-notes-with-popovers.md), [pt](https://postext.dev/pt/cookbook/margin-notes-with-popovers.md), [zh](https://postext.dev/zh/cookbook/margin-notes-with-popovers.md), [ja](https://postext.dev/ja/cookbook/margin-notes-with-popovers.md), [ar](https://postext.dev/ar/cookbook/margin-notes-with-popovers.md)

## Коротко

Музейный текст для зала с заметками рецензентки. Каждая заметка подкрашивает свои слова и ставит пронумерованный ярлык на широком правом поле, соединённый пунктиром. Нажатие на ярлык открывает заметку в окошке прямо под её словами.

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

Музейный текст для зала об Антикитерском механизме так, как его видит редактор выставки вместе с заметками рецензентки. Каждая из четырёх заметок подкрашивает свои слова и ведёт пунктир к пронумерованному флажку на широком внешнем поле. Заметка 2 открыта: всплывающее окно с комментарием стоит прямо под словами, к которым относится, и указывает уголком на последнее. Нажмите другой флажок или подкрашенные слова, и окно переместится туда; прокрутите страницу или измените размер, и оно останется при своих словах.

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

- Как поставить заметку или всплывающее окно рядом с фрагментом свёрстанной страницы?

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

```js
// script.js, строк 108–130
const view = createViewer(document.getElementById('viewer'), {
  document: doc, markdown, zoom: 'fit-width', maxZoom: 1, labels: L.viewer,
  marks: { noteSide: 'end' }, // the flags in the outer margin, not the nearer one
  annotations: notes.map(({ id, label, range }) => ({ id, kind: 'note', range, label })),
});
let open = null; // the note the popover shows
const place = () => {
  if (!open) return;
  // Under the last piece of the noted words: page px, turned into the window's px.
  const last = rangeRects(doc, open.range).at(-1);
  const at = last && view.pageToClient(last.pageIndex, last.rect.x, last.rect.y + last.rect.height);
  pop.hidden = !at;
  if (at) Object.assign(pop.style, { left: `${at.x}px`, top: `${at.y + 8}px` });
};
const show = (id) => {
  open = notes.find((n) => n.id === id) ?? null;
  if (open) fill(open);
  place();
};
view.on('annotationclick', ({ id }) => show(id)); // a flag or the tinted words
view.on('zoomchange', place); // the pages moved under the popover
view.element.addEventListener('scroll', place, { capture: true, passive: true });
show('n2');
```

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

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

- [Пометки на тексте](https://postext.dev/ru/docs/integration-marks.md#пометки): Подсветка, подчёркивание, зачёркивание, замены, вставки, заметки и рамки, уложенные на текст страниц, нарисованные на canvas или записанные как SVG поверх изображений страниц.
- [Геометрия текста (диапазоны и точки)](https://postext.dev/ru/docs/integration-geometry.md#текст-на-странице): rangeRects превращает диапазон Markdown в прямоугольники на страницах, а caretAt, wordAt и blockAt возвращают точку страницы к позиции, слову или блоку исходника.

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

- [Просмотрщик страниц (postext-viewer)](https://postext.dev/ru/docs/integration-viewer.md#просмотрщик-страниц)
- [Шрифты до вёрстки](https://postext.dev/ru/docs/configuration-programmatic-usage.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**

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

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

- Alegreya (OFL-1.1), Alegreya Sans (OFL-1.1)

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

### 1 · Оставьте поле для флажков

```js
// script.js, строк 29–49
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(160), height: mm(220), dpi: 150,
    margins: { top: mm(20), bottom: mm(24), left: mm(18), right: mm(42) } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Alegreya', fontSize: pt(10.5), lineHeight: pt(15),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'left', firstLineIndent: mm(5), indentAfterHeading: false,
    hyphenation: { enabled: true }, avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: 'Alegreya Sans', color: col('accent'), fontWeight: 700, levels: [
    { level: 1, fontSize: pt(22), lineHeight: pt(26), marginTop: pt(4), marginBottom: pt(15) },
  ] },
  header: { elements: [] },
  footer: { elements: [
    { kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Alegreya Sans',
      fontSize: pt(8.5), fontWeight: 700, color: col('accent'), align: 'left',
      placement: { anchor: { to: 'page', edge: 'bottom-left' },
        offset: { x: mm(18), y: mm(-12) } } },
  ] },
};
```

Внешнее поле в 42 мм вмещает флажки, не стесняя текст. Параметр `marks` просмотрщика передаёт `noteSide: 'end'` в раскладку пометок, поэтому все флажки уходят на правое поле; без него каждый встаёт на поле, ближайшее к его строке. Флажки на одной высоте складываются вниз по полю без наложений, а слишком длинный ярлык обрезается многоточием.

### 2 · Храните заметки как диапазоны с ярлыками

```js
// script.js, строк 80–96
// A tool stores the offsets; the pen finds them from quotes so that both editions run.
const notes = t({
  en: [['In the spring of 1901', 'The wreck was found in 1900; the mechanism came up in 1901.'],
    ['a small ball, half silver and half dark',
      'Is the ball still there? If not, say it is reconstructed.'],
    ['nineteen-year calendar', 'Name it: the Metonic cycle. Readers will look it up.'],
    ['X-ray scans', 'Give the year of the scans, 2005.']],
  es: [['En la primavera de 1901', 'El naufragio se halló en 1900; el mecanismo salió en 1901.'],
    ['una bolita, mitad plateada y mitad oscura',
      '¿Se conserva la bolita? Si no, di que es una reconstrucción.'],
    ['calendario de diecinueve años', 'Dale su nombre: el ciclo metónico. El lector lo buscará.'],
    ['radiografías', 'Pon el año de las radiografías, 2005.']],
}).map(([quote, body], i) => {
  const start = markdown.indexOf(quote);
  const range = { start, end: start + quote.length };
  return { id: `n${i + 1}`, label: String(i + 1), body, range };
});
```

Пометке-заметке нужны диапазон и короткий `label` для флажка, номер или инициал. Сам комментарий, его автор и обсуждение остаются в записях сайта; пометка лишь говорит, куда они относятся.

### 3 · Поставьте окно по координатам страницы

Код приведён в [коротком ответе](https://postext.dev/ru/cookbook/margin-notes-with-popovers.md#короткий-ответ) выше. `rangeRects` даёт куски помеченных слов в px страницы; нижний левый угол последнего куска, переданный в `pageToClient`, возвращается в px окна и годится для элемента с `position: fixed`. Просмотрщик сообщает начальный масштаб в первом кадре, так что слушатель `zoomchange` заново ставит первое окно, когда страницы нарисованы, а слушатель прокрутки на `view.element` держит его под словами.

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

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

- Папка с исходными файлами: https://github.com/drnachio/postext/tree/main/cookbook/margin-notes-with-popovers

### index.html

```html
<main id="pages">
  <div id="viewer"></div>
  <section id="popover" role="dialog" aria-labelledby="popover-title" hidden>
    <h3 id="popover-title"></h3>
    <p class="by"></p>
    <p class="body"></p>
    <button type="button"></button>
  </section>
</main>
```

### style.css

```css
/* The host's frame: the viewer fills the window, the popover floats over it.
   The viewer fills its container, so the container gets a height. */
main#pages { display: block; height: max(560px, 100vh); padding: 0; }
#viewer { width: 100%; height: 100%; }
#viewer .postext-viewer { --pv-background: #e9e5df; --pv-focus: #9a4b16; }
/* Placed in window px from pageToClient, so fixed, not absolute. */
#popover {
  position: fixed; z-index: 2; width: 300px; margin-left: -12px; padding: 14px 16px 12px;
  background: #fff; border: 1px solid #cfc7bc; border-radius: 8px;
  box-shadow: 0 10px 30px -8px rgb(0 0 0 / .35); font: 15px/1.45 system-ui, sans-serif;
  color: #211f1c;
}
#popover::before {
  content: ''; position: absolute; top: -7px; left: 20px; width: 12px; height: 12px;
  background: #fff; border: solid #cfc7bc; border-width: 1px 0 0 1px; transform: rotate(45deg);
}
#popover h3 { margin: 0; font-size: 15px; color: #6d3fbf; }
#popover .by { margin: 0 0 8px; font-size: 13px; color: #5d5850; }
#popover .body { margin: 0 0 10px; }
#popover button {
  min-height: 44px; padding: 0 14px; border: 1px solid #cfc7bc; border-radius: 6px;
  background: #f6f3ee; font: inherit; color: inherit; cursor: pointer;
}
#popover button:focus-visible { outline: 2px solid #9a4b16; outline-offset: 2px; }
```

### script.js

```js
// ═══ Postext Cookbook · Nº 215 · Notes in the margin, with a popover ═════════════════
// https://postext.dev/en/cookbook/margin-notes-with-popovers
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Alegreya, Alegreya Sans (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A museum's gallery text with a reviewer's notes on it: each note tints its words and
// puts a numbered flag in the outer margin. Pressing a flag opens the note in a popover,
// which the host places under the words from their page coordinates. Note 2 opens itself.
import { buildDocumentWithFonts, renderPageToCanvas, rangeRects } 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 = 'margin-notes-with-popovers';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#211f1c', // text
  accent: '#9a4b16', // bronze: title and folio
};
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

// #region page: a wide outer margin, where the reviewer's flags go
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(160), height: mm(220), dpi: 150,
    margins: { top: mm(20), bottom: mm(24), left: mm(18), right: mm(42) } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Alegreya', fontSize: pt(10.5), lineHeight: pt(15),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'left', firstLineIndent: mm(5), indentAfterHeading: false,
    hyphenation: { enabled: true }, avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: 'Alegreya Sans', color: col('accent'), fontWeight: 700, levels: [
    { level: 1, fontSize: pt(22), lineHeight: pt(26), marginTop: pt(4), marginBottom: pt(15) },
  ] },
  header: { elements: [] },
  footer: { elements: [
    { kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Alegreya Sans',
      fontSize: pt(8.5), fontWeight: 700, color: col('accent'), align: 'left',
      placement: { anchor: { to: 'page', edge: 'bottom-left' },
        offset: { x: mm(18), y: mm(-12) } } },
  ] },
};
// #endregion

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "Gallery Notes"
author: "Hana Petrou"
---

# A calculator from the sea

In the spring of 1901 sponge divers working off the island of Antikythera, between Crete and the Peloponnese, brought up bronze statues, glass and pottery from a Roman-era wreck. Among the finds was a lump of corroded bronze and wood the size of a shoebox. The next year, as it dried and split, an archaeologist noticed a toothed wheel in one of the fragments.

The lump is now in 82 pieces and is known as the Antikythera mechanism. Inside a wooden case, a train of bronze gears, cut by hand, turned pointers on dials front and back. Turning a handle moved the date. The front dial showed the positions of the Sun and the Moon against the zodiac, and a small ball, half silver and half dark, turned to show the phase of the Moon.

The back carried two spiral dials. The upper one counted the months of a nineteen-year calendar; the lower one marked, month by month, when eclipses of the Sun and Moon could be expected. Inscriptions on the case explained how to read them, in letters so small that most were read only in this century, with X-ray scans of the fragments.

No other geared device of comparable complexity survives from the ancient world, and nothing like it is known again until the astronomical clocks of medieval Europe. Who built it, and where, is still argued over; the writing on its dials points to a Greek maker working in the second or first century BC.
`; // content.<lang>.md, inlined by the Cookbook

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = {
  Alegreya: ['400'],
  'Alegreya Sans': ['700'],
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown }, config, kitFonts(FONTS));
kitStatus(t({ en: 'Gallery Notes · review', es: 'Notas de sala · revisión' }));

// #region notes: the reviewer's notes, as a review tool stores them
// A tool stores the offsets; the pen finds them from quotes so that both editions run.
const notes = t({
  en: [['In the spring of 1901', 'The wreck was found in 1900; the mechanism came up in 1901.'],
    ['a small ball, half silver and half dark',
      'Is the ball still there? If not, say it is reconstructed.'],
    ['nineteen-year calendar', 'Name it: the Metonic cycle. Readers will look it up.'],
    ['X-ray scans', 'Give the year of the scans, 2005.']],
  es: [['En la primavera de 1901', 'El naufragio se halló en 1900; el mecanismo salió en 1901.'],
    ['una bolita, mitad plateada y mitad oscura',
      '¿Se conserva la bolita? Si no, di que es una reconstrucción.'],
    ['calendario de diecinueve años', 'Dale su nombre: el ciclo metónico. El lector lo buscará.'],
    ['radiografías', 'Pon el año de las radiografías, 2005.']],
}).map(([quote, body], i) => {
  const start = markdown.indexOf(quote);
  const range = { start, end: start + quote.length };
  return { id: `n${i + 1}`, label: String(i + 1), body, range };
});
// #endregion

const L = t({
  en: { note: 'Note', by: 'M. Ortega, reviewer', close: 'Close', viewer: {} },
  es: { note: 'Nota', by: 'M. Ortega, revisora', close: 'Cerrar',
    viewer: { viewer: 'Páginas del texto de sala', page: 'Página {n} de {count}',
      kinds: { note: 'Nota' } } },
});
const pop = document.getElementById('popover');

// #region answer: note flags in the margin, and a popover placed from page coordinates
const view = createViewer(document.getElementById('viewer'), {
  document: doc, markdown, zoom: 'fit-width', maxZoom: 1, labels: L.viewer,
  marks: { noteSide: 'end' }, // the flags in the outer margin, not the nearer one
  annotations: notes.map(({ id, label, range }) => ({ id, kind: 'note', range, label })),
});
let open = null; // the note the popover shows
const place = () => {
  if (!open) return;
  // Under the last piece of the noted words: page px, turned into the window's px.
  const last = rangeRects(doc, open.range).at(-1);
  const at = last && view.pageToClient(last.pageIndex, last.rect.x, last.rect.y + last.rect.height);
  pop.hidden = !at;
  if (at) Object.assign(pop.style, { left: `${at.x}px`, top: `${at.y + 8}px` });
};
const show = (id) => {
  open = notes.find((n) => n.id === id) ?? null;
  if (open) fill(open);
  place();
};
view.on('annotationclick', ({ id }) => show(id)); // a flag or the tinted words
view.on('zoomchange', place); // the pages moved under the popover
view.element.addEventListener('scroll', place, { capture: true, passive: true });
show('n2');
// #endregion

// The popover's text, and a button that closes it.
function fill({ label, body }) {
  pop.querySelector('h3').textContent = `${L.note} ${label}`;
  pop.querySelector('.by').textContent = L.by;
  pop.querySelector('.body').textContent = body;
}
const close = pop.querySelector('button');
close.textContent = L.close;
close.addEventListener('click', () => { open = null; pop.hidden = true; });

// The states the Cookbook photographs: the last note open as well.
kitShots({ firstNote: () => { view.revealAnnotation('n1'); show('n1'); } });

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

## Варианты

### Открывайте заметку при наведении

Событие `hover` несёт id пометок под указателем, верхнюю первой.

```diff
 view.on('annotationclick', ({ id }) => show(id)); // a flag or the tinted words
+view.on('hover', ({ annotations }) => annotations[0] && show(annotations[0]));
```

### Пусть каждый флажок встаёт на ближайшее поле

На странице в две колонки заметки левой колонки тогда уйдут на левое поле.

```diff
-  marks: { noteSide: 'end' }, // the flags in the outer margin, not the nearer one
+  marks: {}, // each flag in the margin nearer its words
```

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

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

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

- [№ 213 · Выделение цветом по списку диапазонов](https://postext.dev/ru/cookbook/highlights-from-ranges.md): Записи инструмента рецензирования, каждая — диапазон в Markdown и вердикт, нарисованные на страницах выделениями трёх цветов через setAnnotations. · Уровень 1 (Базовый) · Газеты и информационные бюллетени
- [№ 217 · Якоря после правки: сдвинуты, неоднозначны или потеряны](https://postext.dev/ru/cookbook/anchors-through-a-revision.md): textAnchor хранит каждую заметку с её словами и контекстом; resolveAnchor находит её в следующей редакции: на месте, сдвинутой, неоднозначной или потерянной. · Уровень 2 (Средний) · Руководства, путеводители и справочники
- [№ 222 · Те же пометки на страницах справа налево и вертикальных](https://postext.dev/ru/cookbook/marks-on-rtl-and-vertical-pages.md): Один способ записать пометки для арабской страницы справа налево и японской в вертикальных колонках: layoutAnnotations следует их строкам. · Уровень 3 (Продвинутый) · Любой жанр
