# Маркер для читателя: отрывок и цвет

> Выделите слова в романе, и над ними откроются четыре цвета; выделение доводится до целых слов, хранится как якорь и попадает в список.

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

## Коротко

Роман в приложении для чтения. Выделите несколько слов, и над ними появятся четыре цветные точки; выберите одну, и слова закрасятся этим цветом. Ваши выделения хранятся на устройстве и собраны в список рядом с книгой.

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

Первая глава короткого романа *The Night Ferry* («Ночной паром») в приложении для чтения. Читатель проводит пальцем по фразе, и над ней появляется тёмная панель с четырьмя цветными точками. Одно нажатие, и фраза закрашена жёлтым, зелёным, синим или розовым, а выделение доведено до целых слов. Нажатие на выделение возвращает панель, чтобы сменить цвет или убрать его. Правая колонка: собственный список читателя по порядку чтения, у каждого отрывка свой цвет и страница. Всё хранится на устройстве читателя в виде якорей, которые находят свои слова и тогда, когда издатель выпускает исправленное издание.

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

- Как дать читателям выделять отрывки книги своими цветами?

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

```js
// script.js, строк 172–206
const view = createViewer($('viewer'), {
  document: doc, markdown, zoom: 'fit-width', maxZoom: 0.8, labels: L.viewer,
});
// A drag that starts or ends inside a word takes the whole word.
const snap = ({ start, end }) => {
  const a = wordRangeAt(markdown, start, { locale: config.locale });
  const b = wordRangeAt(markdown, end, { locale: config.locale });
  return { start: a && a.start < start && start < a.end ? a.start : start,
    end: b && b.start < end && end < b.end ? b.end : end };
};
let pending = null; // what the palette acts on: { range } for a new one, { id } for one saved
const offer = (range) => {
  pending = { range: snap(range) };
  view.setSelection(pending.range);
  openPalette(pending.range, null);
};
const pick = (pen) => {
  if (pending?.id) highlights = highlights.map((h) => (h.id === pending.id ? { ...h, pen } : h));
  else if (pending) highlights = [...highlights, { id: nextId(), pen, range: pending.range }];
  closePalette();
  view.setSelection(null);
  save();
  render();
};
const edit = (id) => {
  const h = highlights.find((x) => x.id === id);
  pending = { id };
  openPalette(h.range, h.pen);
};
view.on('select', ({ range }) => {
  if (!range || range.end <= range.start) return closePalette();
  const { start, end } = pending?.range ?? {};
  if (range.start !== start || range.end !== end) offer(range); // not the snapped one echoed back
});
view.on('annotationclick', ({ id }) => edit(id));
```

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

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

- [Пометки на тексте](https://postext.dev/ru/docs/integration-marks.md#пометки): Подсветка, подчёркивание, зачёркивание, замены, вставки, заметки и рамки, уложенные на текст страниц, нарисованные на canvas или записанные как SVG поверх изображений страниц.
- [Якоря, переживающие правку](https://postext.dev/ru/docs/integration-anchors.md#якоря-и-правки): textAnchor хранит диапазон вместе с цитатой и контекстом, чтобы resolveAnchor нашёл его в исправленном тексте; applyEdits вносит принятые правки, а mapOffset переносит остальные позиции.

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

- [Просмотрщик страниц (postext-viewer)](https://postext.dev/ru/docs/integration-viewer.md#просмотрщик-страниц)
- [Геометрия текста (диапазоны и точки)](https://postext.dev/ru/docs/integration-geometry.md#текст-на-странице)
- [Шрифты до вёрстки](https://postext.dev/ru/docs/configuration-programmatic-usage.md#загрузка-шрифтов-перед-вёрсткой)
- [Оформленные начальные полосы](https://postext.dev/ru/docs/configuration-headings.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/document-format.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#загрузка-шрифтов-перед-вёрсткой), `createViewer`, [`renderPageToCanvas`](https://postext.dev/ru/docs/configuration-programmatic-usage.md#рендеринг-страницы-в-растр), `resolveAnchor`, `setAnnotations`, `textAnchor`, `wordRangeAt`

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

- Literata (OFL-1.1), Source Sans 3 (OFL-1.1)

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

### 1 · Храните выделения как якоря, а не как смещения

```js
// script.js, строк 146–168
const KEY = `${RECIPE}:${LANG}`;
const quote = (text) => { // the reader's first highlights, so the pen opens with some
  const start = markdown.indexOf(text);
  return { start, end: start + text.length };
};
const seed = t({
  en: [['yellow', 'a good sailor reads the water the way a scholar reads a book'],
    ['blue', 'Some things, Tom said, a man only writes down in the water.'],
    ['pink', 'as if he had wanted them to last']],
  es: [['yellow', 'un buen marino lee el agua como un estudioso lee un libro'],
    ['blue', 'Hay cosas, dijo Tom, que un hombre solo escribe en el agua.'],
    ['pink', 'como si él hubiera querido que duraran']],
}).map(([pen, text], i) => ({ id: `h${i + 1}`, pen, anchor: textAnchor(markdown, quote(text)) }));
const saved = JSON.parse(localStorage.getItem(KEY) ?? 'null') ?? seed;
// A new edition of the book moves the words: resolveAnchor finds each one again.
let highlights = saved.flatMap((h) => {
  const found = resolveAnchor(markdown, h.anchor);
  return found.status === 'exact' || found.status === 'moved'
    ? [{ ...h, range: { start: found.start, end: found.end } }] : [];
});
const nextId = () => `h${1 + Math.max(0, ...highlights.map((h) => Number(h.id.slice(1)) || 0))}`;
const save = () => localStorage.setItem(KEY, JSON.stringify(
  highlights.map(({ id, pen, range }) => ({ id, pen, anchor: textAnchor(markdown, range) }))));
```

Выделение хранится как цвет и якорь из `textAnchor`: диапазон, слова, которые он покрывал, и немного текста с каждой стороны. Когда приложение открывает книгу, `resolveAnchor` находит каждый якорь в нынешнем тексте. В том же издании ответ будет `exact`; после правки в исходнике — `moved` с новыми смещениями, а вычеркнутый отрывок становится `orphaned`, и приложение его пропускает (или показывает отдельно, чтобы читатель решил сам).

### 2 · Доведите выделение до слов и предложите цвета

Код приведён в [коротком ответе](https://postext.dev/ru/cookbook/reader-highlighter.md#короткий-ответ) выше. Просмотрщик сообщает о каждом законченном выделении как о диапазоне Markdown. `wordRangeAt` расширяет конец, попавший внутрь слова, до целого слова, так что небрежное движение никогда не оставит закрашенной половину слова. Исправленный диапазон возвращается в просмотрщик через `setSelection`, а обработчик пропускает это эхо, иначе палитра предлагалась бы без конца.

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

```js
// script.js, строк 210–248
const bar = $('palette');
for (const [pen, { color, name }] of Object.entries(PENS)) {
  const b = Object.assign(document.createElement('button'), { type: 'button', title: name });
  b.dataset.pen = pen;
  b.style.setProperty('--pen', color);
  b.setAttribute('aria-label', L.pen(name));
  b.addEventListener('click', () => pick(pen));
  bar.insertBefore(b, $('remove'));
}
$('remove').textContent = L.remove;
$('remove').addEventListener('click', () => {
  highlights = highlights.filter((h) => h.id !== pending?.id);
  closePalette();
  save();
  render();
});
function openPalette(range, current) {
  for (const b of bar.querySelectorAll('[data-pen]')) b.setAttribute('aria-pressed', String(b.dataset.pen === current));
  $('remove').hidden = !current;
  bar.hidden = false;
  bar.dataset.range = `${range.start}-${range.end}`;
  place();
}
function closePalette() {
  pending = null;
  bar.hidden = true;
}
// Above the passage's first line, centred on it, in the window's px.
function place() {
  if (bar.hidden) return;
  const [start, end] = bar.dataset.range.split('-').map(Number);
  const first = view.rangeRects({ start, end })[0];
  const at = first && view.pageToClient(first.pageIndex, first.rect.x + first.rect.width / 2, first.rect.y);
  if (!at) return void (bar.hidden = true);
  Object.assign(bar.style, { left: `${at.x}px`, top: `${at.y - 10}px` });
}
view.on('zoomchange', place);
view.element.addEventListener('scroll', place, { capture: true, passive: true });
addEventListener('keydown', (e) => e.key === 'Escape' && closePalette());
```

`rangeRects` даёт первую строку отрывка в пикселях страницы, а `pageToClient` переводит её в пиксели окна, поэтому панель стоит по центру над словами при любом масштабе. Она следует за ними по `zoomchange` и при прокрутке. Панель — это HTML самого приложения: она следует его дизайну, а у её кнопок есть имена для экранных чтецов.

### 4 · Соберите в список то, что отметил читатель

```js
// script.js, строк 252–271
function render() {
  highlights.sort((a, b) => a.range.start - b.range.start);
  view.setAnnotations(highlights.map(({ id, pen, range }) => ({
    id, kind: 'highlight', range, color: PENS[pen].color,
  })));
  $('count').textContent = highlights.length ? L.count(highlights.length) : L.empty;
  $('list').replaceChildren(...highlights.map(({ id, pen, range }) => {
    const item = document.createElement('button');
    item.type = 'button';
    item.style.setProperty('--pen', PENS[pen].color);
    item.innerHTML = '<q></q><small></small>';
    item.querySelector('q').textContent = markdown.slice(range.start, range.end).replace(/[*_]/g, '');
    const page = view.rangeRects(range)[0]?.pageIndex;
    item.querySelector('small').textContent = `${PENS[pen].name} · ${L.page(page + 1)}`;
    item.addEventListener('click', () => view.revealAnnotation(id, { behavior: 'smooth' }));
    return item;
  }));
}
$('title').textContent = L.title;
render();
```

`setAnnotations` рисует каждое выделение своим цветом; список состоит из тех же записей, отсортированных по смещению, со страницей из `rangeRects`. Нажатие на пункт вызывает `revealAnnotation`, который прокручивает к его словам.

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

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

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

### index.html

```html
<main id="pages">
  <div id="viewer"></div>
  <aside id="panel">
    <h2 id="title"></h2>
    <p id="count"></p>
    <div id="list"></div>
  </aside>
  <div id="palette" role="toolbar" hidden>
    <button id="remove" type="button"></button>
  </div>
</main>
```

### style.css

```css
/* A reading app: the pages on a warm desk, the reader's highlights in a column beside them.
   The viewer fills its container, so the container gets a height. */
main#pages {
  display: grid; grid-template-columns: minmax(0, 1fr) 330px; height: max(560px, 100vh);
  justify-items: stretch; gap: 0; padding: 0; font: 15px/1.45 system-ui, sans-serif; color: #22201d;
  color-scheme: light;
}
#viewer { min-height: 0; }
#viewer .postext-viewer {
  --pv-background: #ebe6de; --pv-focus: #7a3e2b; --pv-selection: rgb(122 62 43 / .22);
}
#panel { overflow: auto; padding: 26px 22px; background: #fbf9f6; border-left: 1px solid #ddd6cc; }
#panel h2 { margin: 0; font: 600 22px/1.2 Literata, Georgia, serif; }
#count { margin: 4px 0 18px; font-size: 13px; color: #77706a; }
#list { display: grid; gap: 10px; }
#list button {
  display: grid; gap: 6px; min-height: 44px; padding: 12px 14px 11px 16px; text-align: left;
  background: #fff; border: 1px solid #e3ddd3; border-radius: 10px; cursor: pointer;
  box-shadow: inset 4px 0 0 var(--pen), 0 1px 2px rgb(60 40 20 / .06); color: inherit; font: inherit;
}
#list button:hover { border-color: var(--pen); }
#list button:focus-visible { outline: 2px solid #7a3e2b; outline-offset: 2px; }
#list q { font: italic 15px/1.45 Literata, Georgia, serif; quotes: '“' '”'; }
#list small { font-size: 12px; font-weight: 600; letter-spacing: .02em; color: #77706a; }
/* The palette floats over the passage: placed in window px from pageToClient, so fixed. */
#palette {
  position: fixed; z-index: 2; display: flex; align-items: center; gap: 6px; padding: 6px;
  transform: translate(-50%, -100%); background: #2a2622; border-radius: 999px;
  box-shadow: 0 12px 28px -10px rgb(0 0 0 / .55);
}
#palette[hidden] { display: none; }
#palette::after {
  content: ''; position: absolute; left: 50%; bottom: -5px; width: 10px; height: 10px;
  margin-left: -5px; background: #2a2622; transform: rotate(45deg);
}
#palette [data-pen] {
  width: 44px; height: 44px; padding: 0; border: 0; border-radius: 50%; cursor: pointer;
  background: radial-gradient(circle, var(--pen) 0 13px, transparent 14px);
}
#palette [data-pen]:hover, #palette [aria-pressed='true'] {
  background: radial-gradient(circle, var(--pen) 0 13px, transparent 14px 16px, #fff 17px 18px, transparent 19px);
}
#palette button:focus-visible { outline: 2px solid #fff; outline-offset: -3px; }
#remove {
  min-height: 44px; padding: 0 16px; margin-left: 2px; border: 0; border-left: 1px solid #4a443e;
  border-radius: 0 999px 999px 0; background: none; color: #f4efe8; font: 600 14px system-ui, sans-serif;
  cursor: pointer;
}
#remove[hidden] { display: none; }
```

### script.js

```js
// ═══ Postext Cookbook · Nº 223 · A reader's highlighter ══════════════════════════════
// https://postext.dev/en/cookbook/reader-highlighter
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Literata, Source Sans 3 (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// The first chapter of a novel in a reading app. Select a passage and a palette of four
// colours appears over it; pick one and the passage is highlighted, snapped to whole words,
// and saved on this device as an anchor. Press a highlight to change its colour or remove
// it. The list beside the pages holds every passage, in reading order.
import { buildDocumentWithFonts, renderPageToCanvas, wordRangeAt } from 'https://esm.sh/postext';
import { textAnchor, resolveAnchor } from 'https://esm.sh/postext/annotate';
import { createViewer } from 'https://esm.sh/postext-viewer';

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

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#22201d', // text
  accent: '#7a3e2b', // rust: kicker, rule and folio
  muted: '#77706a', // 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

// #region page: a trade paperback, the chapter opener sunk below a kicker and a short rule
const opener = {
  enabled: true,
  minHeight: mm(46),
  slot: { elements: [
    { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: 'Source Sans 3',
      fontSize: pt(8), fontWeight: 700, letterSpacing: pt(1.6), textTransform: 'uppercase',
      color: col('accent'), align: 'left',
      placement: { anchor: { to: 'container', edge: 'top-left' }, offset: { x: mm(0), y: mm(10) } } },
    { kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Literata',
      fontSize: pt(25), lineHeight: 1.1, fontWeight: 600, color: col('ink'), align: 'left',
      placement: { anchor: { to: '#kicker', edge: 'below' }, offset: { x: mm(0), y: mm(3) },
        size: { width: mm(90), height: 'auto' } } },
    { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(1.5), color: col('accent'),
      placement: { anchor: { to: '#title', edge: 'below' }, offset: { x: mm(0), y: mm(5) },
        size: { width: mm(12) } } },
  ] },
};
const head = (id, content, parity, edge, x, extra = {}) => ({
  kind: 'text', id, content, parity, pages: 'body', fontFamily: 'Source Sans 3',
  fontSize: pt(7.5), fontWeight: 600, letterSpacing: pt(1.2), textTransform: 'uppercase',
  color: col('muted'), placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(12) } },
  ...extra,
});
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(129), height: mm(198), dpi: 150,
    margins: { top: mm(20), bottom: mm(22), left: mm(18), right: mm(15), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Literata', fontSize: pt(10), lineHeight: pt(14.5),
    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: 'Literata', color: col('ink'), fontWeight: 600, levels: [
    { level: 1, fontSize: pt(25), advancedDesign: opener },
  ] },
  header: { elements: [
    head('verso-folio', '{pageNumber}', 'even', 'top-left', 15, { color: col('accent'), fontWeight: 700 }),
    head('verso-title', '{title}', 'even', 'top-left', 23),
    head('recto-title', '{chapterTitle}', 'odd', 'top-right', -23),
    head('recto-folio', '{pageNumber}', 'odd', 'top-right', -15, { color: col('accent'), fontWeight: 700 }),
  ] },
  // The opener drops its folio to the foot, where no running head crowds the title.
  footer: { elements: [head('drop-folio', '{pageNumber}', 'all', 'bottom', 0, {
    pages: 'opener', color: col('accent'), fontWeight: 700,
    placement: { anchor: { to: 'page', edge: 'bottom' }, offset: { x: mm(0), y: mm(-11) } },
  })] },
};
// #endregion

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "The Night Ferry"
author: "Ines Calder"
---

# The Night Ferry {kicker="Chapter one"}

The ferry left at ten, whatever the weather, and on most nights Agnes Lowe was the only passenger who stayed on deck. She liked the cold. She liked the way the town shrank behind the boat until it was a handful of yellow windows, then a line, then nothing at all.

Her father had worked the crossing for thirty-one years. He knew the channel by its sounds: the slap of the tide against the north buoy, the long groan of the chain at the landing, the gulls that only cried when rain was coming. When she was small he had told her that a good sailor reads the water the way a scholar reads a book, slowly, and with a pencil in his hand.

She had not understood him then. She understood him now, on the night she carried his logbook across the water to give it back to the harbour office. Every page was full of small marks. A tick where the light at the point was late. A cross where the engine coughed. Once, in the margin beside an entry for a calm October night, three words in his careful capitals: *saw the whales*.

The office would want the numbers, the dates and the fuel. They would not want the whales. Agnes had decided, somewhere between the ticket booth and the rail, that she would copy those three words into her own notebook before she handed anything over.

The engine changed its note as the boat came round the point. Ahead, the island showed its one street lamp and the white shape of the chapel. A man in an orange coat was waiting at the landing with a rope coiled over his arm, and she knew without seeing his face that it was Tom Harker, who had been her father's deckhand and had never once been late.

"You brought it," he said, when the gangway was down.

"I brought it."

He did not ask to see the book. He walked beside her up the slope to the harbour office, where a light still burned, and he told her about the winter the ice had come into the channel and her father had broken it with a boathook for two hours so the doctor could get across. It was not in the logbook. Some things, Tom said, a man only writes down in the water.

At the office door she stopped and opened the book at the October page. The capitals were smaller than she remembered, pressed hard into the paper, as if he had wanted them to last. She read them twice and closed the cover.

Inside, the clerk thanked her and gave her a receipt, and the book went into a grey box with a number on the side. That was all. When she came out, Tom was looking at the dark water past the landing, and for a moment neither of them spoke.

Then something rose out there, a long black back in the moonlight, and sank again without a sound.
`; // content.<lang>.md, inlined by the Cookbook

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

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown }, config, kitFonts(FONTS));
kitStatus(t({ en: 'The Night Ferry · your highlights', es: 'El ferri de la noche · tus resaltados' }));

// #region colours: the reader's four pens, named for the buttons and the list
const PENS = {
  yellow: { color: '#e0a800', name: t({ en: 'Yellow', es: 'Amarillo' }) },
  green: { color: '#3c9a55', name: t({ en: 'Green', es: 'Verde' }) },
  blue: { color: '#2f7fd6', name: t({ en: 'Blue', es: 'Azul' }) },
  pink: { color: '#d64c86', name: t({ en: 'Pink', es: 'Rosa' }) },
};
// #endregion
const L = t({
  en: { title: 'Highlights', count: (n) => `${n} passage${n === 1 ? '' : 's'} · saved on this device`,
    page: (p) => `Page ${p}`, remove: 'Remove', pen: (name) => `Highlight in ${name.toLowerCase()}`,
    empty: 'Select a passage on the page to highlight it.', viewer: {} },
  es: { title: 'Resaltados', count: (n) => `${n} ${n === 1 ? 'pasaje' : 'pasajes'} · guardados en este dispositivo`,
    page: (p) => `Página ${p}`, remove: 'Quitar', pen: (name) => `Resaltar en ${name.toLowerCase()}`,
    empty: 'Selecciona un pasaje de la página para resaltarlo.',
    viewer: { viewer: 'Páginas del libro', page: 'Página {n} de {count}',
      selection: '{count} caracteres seleccionados', selectionCleared: 'Selección borrada',
      kinds: { highlight: 'Resaltado' } } },
});
const $ = (id) => document.getElementById(id);

// #region store: highlights kept as anchors, found again in the text the app has now
const KEY = `${RECIPE}:${LANG}`;
const quote = (text) => { // the reader's first highlights, so the pen opens with some
  const start = markdown.indexOf(text);
  return { start, end: start + text.length };
};
const seed = t({
  en: [['yellow', 'a good sailor reads the water the way a scholar reads a book'],
    ['blue', 'Some things, Tom said, a man only writes down in the water.'],
    ['pink', 'as if he had wanted them to last']],
  es: [['yellow', 'un buen marino lee el agua como un estudioso lee un libro'],
    ['blue', 'Hay cosas, dijo Tom, que un hombre solo escribe en el agua.'],
    ['pink', 'como si él hubiera querido que duraran']],
}).map(([pen, text], i) => ({ id: `h${i + 1}`, pen, anchor: textAnchor(markdown, quote(text)) }));
const saved = JSON.parse(localStorage.getItem(KEY) ?? 'null') ?? seed;
// A new edition of the book moves the words: resolveAnchor finds each one again.
let highlights = saved.flatMap((h) => {
  const found = resolveAnchor(markdown, h.anchor);
  return found.status === 'exact' || found.status === 'moved'
    ? [{ ...h, range: { start: found.start, end: found.end } }] : [];
});
const nextId = () => `h${1 + Math.max(0, ...highlights.map((h) => Number(h.id.slice(1)) || 0))}`;
const save = () => localStorage.setItem(KEY, JSON.stringify(
  highlights.map(({ id, pen, range }) => ({ id, pen, anchor: textAnchor(markdown, range) }))));
// #endregion

// #region answer: a selection, snapped to whole words, offered the four pens
const view = createViewer($('viewer'), {
  document: doc, markdown, zoom: 'fit-width', maxZoom: 0.8, labels: L.viewer,
});
// A drag that starts or ends inside a word takes the whole word.
const snap = ({ start, end }) => {
  const a = wordRangeAt(markdown, start, { locale: config.locale });
  const b = wordRangeAt(markdown, end, { locale: config.locale });
  return { start: a && a.start < start && start < a.end ? a.start : start,
    end: b && b.start < end && end < b.end ? b.end : end };
};
let pending = null; // what the palette acts on: { range } for a new one, { id } for one saved
const offer = (range) => {
  pending = { range: snap(range) };
  view.setSelection(pending.range);
  openPalette(pending.range, null);
};
const pick = (pen) => {
  if (pending?.id) highlights = highlights.map((h) => (h.id === pending.id ? { ...h, pen } : h));
  else if (pending) highlights = [...highlights, { id: nextId(), pen, range: pending.range }];
  closePalette();
  view.setSelection(null);
  save();
  render();
};
const edit = (id) => {
  const h = highlights.find((x) => x.id === id);
  pending = { id };
  openPalette(h.range, h.pen);
};
view.on('select', ({ range }) => {
  if (!range || range.end <= range.start) return closePalette();
  const { start, end } = pending?.range ?? {};
  if (range.start !== start || range.end !== end) offer(range); // not the snapped one echoed back
});
view.on('annotationclick', ({ id }) => edit(id));
// #endregion

// #region bar: the floating palette, placed over the passage from page coordinates
const bar = $('palette');
for (const [pen, { color, name }] of Object.entries(PENS)) {
  const b = Object.assign(document.createElement('button'), { type: 'button', title: name });
  b.dataset.pen = pen;
  b.style.setProperty('--pen', color);
  b.setAttribute('aria-label', L.pen(name));
  b.addEventListener('click', () => pick(pen));
  bar.insertBefore(b, $('remove'));
}
$('remove').textContent = L.remove;
$('remove').addEventListener('click', () => {
  highlights = highlights.filter((h) => h.id !== pending?.id);
  closePalette();
  save();
  render();
});
function openPalette(range, current) {
  for (const b of bar.querySelectorAll('[data-pen]')) b.setAttribute('aria-pressed', String(b.dataset.pen === current));
  $('remove').hidden = !current;
  bar.hidden = false;
  bar.dataset.range = `${range.start}-${range.end}`;
  place();
}
function closePalette() {
  pending = null;
  bar.hidden = true;
}
// Above the passage's first line, centred on it, in the window's px.
function place() {
  if (bar.hidden) return;
  const [start, end] = bar.dataset.range.split('-').map(Number);
  const first = view.rangeRects({ start, end })[0];
  const at = first && view.pageToClient(first.pageIndex, first.rect.x + first.rect.width / 2, first.rect.y);
  if (!at) return void (bar.hidden = true);
  Object.assign(bar.style, { left: `${at.x}px`, top: `${at.y - 10}px` });
}
view.on('zoomchange', place);
view.element.addEventListener('scroll', place, { capture: true, passive: true });
addEventListener('keydown', (e) => e.key === 'Escape' && closePalette());
// #endregion

// #region list: every highlight in reading order, with its page; a press shows it
function render() {
  highlights.sort((a, b) => a.range.start - b.range.start);
  view.setAnnotations(highlights.map(({ id, pen, range }) => ({
    id, kind: 'highlight', range, color: PENS[pen].color,
  })));
  $('count').textContent = highlights.length ? L.count(highlights.length) : L.empty;
  $('list').replaceChildren(...highlights.map(({ id, pen, range }) => {
    const item = document.createElement('button');
    item.type = 'button';
    item.style.setProperty('--pen', PENS[pen].color);
    item.innerHTML = '<q></q><small></small>';
    item.querySelector('q').textContent = markdown.slice(range.start, range.end).replace(/[*_]/g, '');
    const page = view.rangeRects(range)[0]?.pageIndex;
    item.querySelector('small').textContent = `${PENS[pen].name} · ${L.page(page + 1)}`;
    item.addEventListener('click', () => view.revealAnnotation(id, { behavior: 'smooth' }));
    return item;
  }));
}
$('title').textContent = L.title;
render();
// #endregion

// The states the Cookbook photographs: a passage offered the pens, then one opened again.
kitShots({
  select: () => {
    const range = quote(t({ en: 'three words in his careful capitals',
      es: 'tres palabras en sus mayúsculas cuidadosas' }));
    view.revealRange(range);
    offer(range);
  },
  change: () => { pick('green'); view.revealAnnotation('h1'); edit('h1'); },
});

// ─── 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
-    id, kind: 'highlight', range, color: PENS[pen].color,
+    id, kind: 'underline', range, color: PENS[pen].color,
```

### Напишите заметку к выделению

Выделение с заметкой становится флажком на полях: [Тетрадь читателя: заметки к выделенным словам](https://postext.dev/ru/cookbook/reader-notebook.md) строит записную книжку на тех же якорях.

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

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

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

- [№ 213 · Выделение цветом по списку диапазонов](https://postext.dev/ru/cookbook/highlights-from-ranges.md): Записи инструмента рецензирования, каждая — диапазон в Markdown и вердикт, нарисованные на страницах выделениями трёх цветов через setAnnotations. · Уровень 1 (Базовый) · Газеты и информационные бюллетени
- [№ 212 · Выделить на странице, прочитать диапазон и текст Markdown](https://postext.dev/ru/cookbook/selection-as-markdown-range.md): postext-viewer сообщает о выделении на свёрстанных страницах как о диапазоне в Markdown, вместе с охваченным Markdown и его кусками по строкам. · Уровень 1 (Базовый) · Журналы и зины
- [№ 217 · Якоря после правки: сдвинуты, неоднозначны или потеряны](https://postext.dev/ru/cookbook/anchors-through-a-revision.md): textAnchor хранит каждую заметку с её словами и контекстом; resolveAnchor находит её в следующей редакции: на месте, сдвинутой, неоднозначной или потерянной. · Уровень 2 (Средний) · Руководства, путеводители и справочники
