# A reader's highlighter: a passage and a colour

> Select words on a novel's pages and four colours open over them; the highlight snaps to whole words, is saved as an anchor and joins a list beside the pages.

- HTML version: https://postext.dev/en/cookbook/reader-highlighter
- Recipe Nº 223 · CMS integration · Level 2 (Intermediate) · Outputs: Canvas
- Genres: Fiction, drama & literary prose
- Requires postext ≥ 1.103.0 · tested with 1.103.1 on 2026-12-04
- Pages: [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)
- ![The reading app as it opens: three passages already highlighted in yellow, blue and pink, and the same three listed beside the pages with their colour and page.](https://postext.dev/cookbook/reader-highlighter/en/s01.webp?v=4cd29c98)
- ![A passage selected on page 1: the palette of four colours floats above its first line, placed from page coordinates.](https://postext.dev/cookbook/reader-highlighter/en/s02.webp?v=4cd29c98)
- ![The new passage is now green and listed in reading order; pressing the yellow highlight opens the palette again, its colour ringed and a button to remove it.](https://postext.dev/cookbook/reader-highlighter/en/s03.webp?v=4cd29c98)
- Last updated: 2026-12-04
- Other languages: [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), [ru](https://postext.dev/ru/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)

## In short

The first chapter of a novel in a reading app. Select some words and four coloured dots appear above them; pick one and the words are shaded in that colour. Your highlights are kept on this device and listed beside the book.

## What you'll build

The first chapter of a short novel, *The Night Ferry*, in a reading app. The reader drags across a sentence and a dark bar with four coloured dots appears over it. One press and the sentence is shaded yellow, green, blue or pink, the drag snapped out to whole words. A press on a highlight brings the bar back to change its colour or remove it. The column on the right is the reader's own list, in reading order, each passage with its colour and its page. It is all kept on the reader's device, as anchors that still find their words when the publisher ships a corrected edition.

**This recipe answers:**

- How do I let readers highlight passages of the book in colours of their own?

## The short answer

A selection, snapped to whole words, offered the four pens.

```js
// script.js, lines 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));
```

## Ingredients

**Teaches**

- [Annotation marks](https://postext.dev/en/docs/integration-marks.md#annotation-marks): Highlights, underlines, strikes, replacements, insertions, notes and boxes laid out on the text of the pages, painted on a canvas or written as SVG over page images.
- [Anchors through revisions](https://postext.dev/en/docs/integration-anchors.md#anchors-and-edits): textAnchor keeps a range with its quote and context, so resolveAnchor finds it again in a revised text; applyEdits writes accepted changes and mapOffset carries the other positions across them.

**Also uses**

- [Page viewer (postext-viewer)](https://postext.dev/en/docs/integration-viewer.md#the-page-viewer)
- [Text geometry (ranges and points)](https://postext.dev/en/docs/integration-geometry.md#text-on-the-page)
- [Fonts before layout](https://postext.dev/en/docs/configuration-programmatic-usage.md#loading-fonts-before-layout)
- [Designed openers](https://postext.dev/en/docs/configuration-headings.md#span-and-advanced-design)
- [Running heads and folios](https://postext.dev/en/docs/configuration-headers-footers.md#headers--footers)
- [Mirrored margins](https://postext.dev/en/docs/configuration-page-layout.md#mirrored-margins)
- [Semantic colour palette](https://postext.dev/en/docs/configuration-fonts-colors-viewers.md#color-palette)
- [Heading attributes](https://postext.dev/en/docs/document-format.md#heading-attributes)
- [Heads by page role](https://postext.dev/en/docs/configuration-headers-footers.md#text-elements)

**Config at a glance**

- [`bodyText`](https://postext.dev/en/docs/configuration-text.md#body-text), [`colorPalette`](https://postext.dev/en/docs/configuration-fonts-colors-viewers.md#color-palette), [`footer`](https://postext.dev/en/docs/configuration-headers-footers.md#headers--footers), [`header`](https://postext.dev/en/docs/configuration-headers-footers.md#headers--footers), [`headings`](https://postext.dev/en/docs/configuration-headings.md#headings), [`layout`](https://postext.dev/en/docs/configuration-page-layout.md#layout), [`locale`](https://postext.dev/en/docs/configuration-language.md#hyphenation), [`page`](https://postext.dev/en/docs/configuration-page-layout.md#page)

**APIs**

- [`buildDocumentWithFonts`](https://postext.dev/en/docs/configuration-programmatic-usage.md#loading-fonts-before-layout), `createViewer`, [`renderPageToCanvas`](https://postext.dev/en/docs/configuration-programmatic-usage.md#rendering-a-page-to-a-bitmap), `resolveAnchor`, `setAnnotations`, `textAnchor`, `wordRangeAt`

**Typefaces**

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

## Method

### 1 · Keep highlights as anchors, not offsets

```js
// script.js, lines 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) }))));
```

A highlight is stored as a colour and an anchor from `textAnchor`: the range, the words it covered and some text on each side. When the app opens a book, `resolveAnchor` finds each one in the text it has now. In the same edition the answer is `exact`; after a correction upstream it is `moved` with new offsets, and a passage that was cut is `orphaned`, which the app leaves out (or shows apart, so the reader can let it go).

### 2 · Snap the selection and offer the colours

The code is [the short answer](https://postext.dev/en/cookbook/reader-highlighter.md#the-short-answer) above. The viewer reports each finished selection as a range of the Markdown. `wordRangeAt` widens an end that falls inside a word to the whole word, so a careless drag never leaves half a word shaded. The snapped range goes back to the viewer with `setSelection`, and the handler ignores that echo, or it would offer the palette forever.

### 3 · Place the palette over the passage

```js
// script.js, lines 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` gives the passage's first line in page pixels and `pageToClient` turns it into window pixels, so the bar sits centred over the words at any zoom. It moves with them on `zoomchange` and on scroll. The bar is the host's own HTML, so it follows the app's design and its buttons carry names for screen readers.

### 4 · List what the reader marked

```js
// script.js, lines 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` paints every highlight in its colour; the list is the same records sorted by offset, with the page from `rangeRects`. A press on an entry calls `revealAnnotation`, which scrolls its words into view.

## The whole recipe

The files below are composed from the recipe's folder, with the sample text and the Cookbook's shared kit inlined. To run them as one page, put the HTML in `<body>`, the CSS in a `<style>` element and the script in a `<script type="module">`; or paste each into the matching panel of a new CodePen (JS as a module). The script imports postext from esm.sh, so there is nothing to install or build.

- Source folder: 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 ───────────────────────────────────────────────────────────────────────
```

## Variations

### Underline in the reader's colour

Some readers prefer a line to a fill, and a line keeps the text's contrast on any paper.

```diff
-    id, kind: 'highlight', range, color: PENS[pen].color,
+    id, kind: 'underline', range, color: PENS[pen].color,
```

### Write a note on a highlight

A highlight that also carries a note becomes a margin flag: [A reader's notebook: notes on what they select](https://postext.dev/en/cookbook/reader-notebook.md) builds the notebook on the same anchors.

## Credits

- Recipe: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Type: Literata (OFL-1.1), Source Sans 3 (OFL-1.1)
- Code: MIT · Sample content: CC-BY-4.0

## Related

- [Nº 213 · Highlights from a list of ranges](https://postext.dev/en/cookbook/highlights-from-ranges.md): A review tool's records, each a range of the Markdown and a verdict, painted over the laid-out pages as highlights in three colours with setAnnotations. · Level 1 (Basic) · Newspapers & newsletters
- [Nº 212 · Select on the page, read the Markdown range and text](https://postext.dev/en/cookbook/selection-as-markdown-range.md): postext-viewer reports a selection on the laid-out pages as a range of the Markdown, the Markdown it covers and its pieces line by line. · Level 1 (Basic) · Magazines & zines
- [Nº 217 · Anchors through a revision: moved, ambiguous, orphaned](https://postext.dev/en/cookbook/anchors-through-a-revision.md): textAnchor stores each note with its words and context; resolveAnchor finds it in the next revision as exact, moved, ambiguous or orphaned. · Level 2 (Intermediate) · Manuals, guides & reference
