# Un subrayador para el lector: pasaje y color

> Al seleccionar palabras de una novela se abren cuatro colores; el resaltado se ajusta a palabras enteras, se guarda como ancla y entra en una lista.

- Versión HTML: https://postext.dev/es/cookbook/reader-highlighter
- Receta N.º 223 · Integración con CMS · Nivel 2 (Intermedio) · Salidas: Canvas
- Géneros: Narrativa, teatro y prosa literaria
- Requiere postext ≥ 1.103.0 · probada con 1.103.1 el 2026-12-04
- Páginas: [1](https://postext.dev/cookbook/reader-highlighter/es/p01.webp?v=3e5b4f3b), [2](https://postext.dev/cookbook/reader-highlighter/es/p02.webp?v=3e5b4f3b), [3](https://postext.dev/cookbook/reader-highlighter/es/p03.webp?v=3e5b4f3b)
- ![La aplicación de lectura al abrirse: tres pasajes ya resaltados en amarillo, azul y rosa, y los mismos tres en la lista junto a las páginas, con su color y su página.](https://postext.dev/cookbook/reader-highlighter/es/s01.webp?v=3e5b4f3b)
- ![Un pasaje seleccionado en la página 1: la paleta de cuatro colores flota sobre su primera línea, colocada desde las coordenadas de la página.](https://postext.dev/cookbook/reader-highlighter/es/s02.webp?v=3e5b4f3b)
- ![El pasaje nuevo ya está en verde y en la lista por orden de lectura; al pulsar el resaltado amarillo vuelve la paleta, con su color marcado y un botón para quitarlo.](https://postext.dev/cookbook/reader-highlighter/es/s03.webp?v=3e5b4f3b)
- Última actualización: 2026-12-04
- Otros idiomas: [en](https://postext.dev/en/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)

## En pocas palabras

Una novela en una aplicación de lectura. Selecciona unas palabras y aparecen encima cuatro puntos de color; elige uno y quedan sombreadas en ese color. Los resaltados se guardan en el dispositivo y se listan junto al libro.

## Lo que vas a componer

El primer capítulo de una novela breve, *El ferri de la noche*, en una aplicación de lectura. El lector arrastra sobre una frase y aparece encima una barra oscura con cuatro puntos de color. Una pulsación y la frase queda sombreada en amarillo, verde, azul o rosa, con el arrastre ajustado a palabras enteras. Al pulsar un resaltado vuelve la barra, para cambiarle el color o quitarlo. La columna de la derecha es la lista del propio lector, por orden de lectura, cada pasaje con su color y su página. Todo se guarda en el dispositivo del lector, como anclas que siguen encontrando sus palabras cuando la editorial publica una edición corregida.

**Esta receta responde a:**

- ¿Cómo dejo que los lectores resalten pasajes del libro en sus propios colores?

## La respuesta corta

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

## Ingredientes

**Enseña**

- [Marcas de anotación](https://postext.dev/es/docs/integration-marks.md#marcas-de-anotación): Resaltados, subrayados, tachados, sustituciones, inserciones, notas y recuadros colocados sobre el texto de las páginas, pintados en un canvas o escritos como SVG sobre imágenes de página.
- [Anclas que sobreviven a las revisiones](https://postext.dev/es/docs/integration-anchors.md#anclas-y-ediciones): textAnchor guarda un rango con su cita y su contexto, de modo que resolveAnchor lo vuelve a encontrar en un texto revisado; applyEdits escribe los cambios aceptados y mapOffset traslada las demás posiciones.

**También usa**

- [Visor de páginas (postext-viewer)](https://postext.dev/es/docs/integration-viewer.md#el-visor-de-páginas)
- [Geometría del texto (rangos y puntos)](https://postext.dev/es/docs/integration-geometry.md#el-texto-en-la-página)
- [Fuentes antes de componer](https://postext.dev/es/docs/configuration-programmatic-usage.md#cargar-las-fuentes-antes-de-componer)
- [Aperturas diseñadas](https://postext.dev/es/docs/configuration-headings.md#apertura-a-toda-página-y-diseño-avanzado)
- [Cabeceras y folios](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies)
- [Márgenes simétricos](https://postext.dev/es/docs/configuration-page-layout.md#márgenes-simétricos-espejo)
- [Paleta de color semántica](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores)
- [Atributos de título](https://postext.dev/es/docs/document-format.md#atributos-de-encabezado)
- [Cabeceras según el tipo de página](https://postext.dev/es/docs/configuration-headers-footers.md#elementos-de-texto)

**La configuración de un vistazo**

- [`bodyText`](https://postext.dev/es/docs/configuration-text.md#texto-base), [`colorPalette`](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores), [`footer`](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies), [`header`](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies), [`headings`](https://postext.dev/es/docs/configuration-headings.md#encabezados), [`layout`](https://postext.dev/es/docs/configuration-page-layout.md#disposición), [`locale`](https://postext.dev/es/docs/configuration-language.md#separación-silábica), [`page`](https://postext.dev/es/docs/configuration-page-layout.md#página)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/es/docs/configuration-programmatic-usage.md#cargar-las-fuentes-antes-de-componer), `createViewer`, [`renderPageToCanvas`](https://postext.dev/es/docs/configuration-programmatic-usage.md#renderizar-una-página-como-mapa-de-bits), `resolveAnchor`, `setAnnotations`, `textAnchor`, `wordRangeAt`

**Tipografías**

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

## Elaboración

### 1 · Guarda los resaltados como anclas, no como posiciones

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

Un resaltado se guarda como un color y un ancla de `textAnchor`: el rango, las palabras que cubría y algo de texto a cada lado. Cuando la aplicación abre un libro, `resolveAnchor` encuentra cada una en el texto que tiene ahora. En la misma edición la respuesta es `exact`; tras una corrección es `moved`, con posiciones nuevas, y un pasaje que se suprimió queda `orphaned`, que la aplicación deja fuera (o muestra aparte, para que el lector decida).

### 2 · Ajusta la selección y ofrece los colores

El código es [la respuesta corta](https://postext.dev/es/cookbook/reader-highlighter.md#the-short-answer) de arriba. El visor comunica cada selección terminada como un rango del Markdown. `wordRangeAt` amplía a la palabra entera un extremo que cae dentro de una palabra, así que un arrastre descuidado nunca deja media palabra sombreada. El rango ajustado vuelve al visor con `setSelection`, y el manejador ignora ese eco, o la paleta se ofrecería sin fin.

### 3 · Coloca la paleta sobre el pasaje

```js
// script.js, líneas 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` da la primera línea del pasaje en píxeles de página y `pageToClient` la pasa a píxeles de la ventana, así que la barra queda centrada sobre las palabras con cualquier zoom. Se mueve con ellas en `zoomchange` y al desplazarse. La barra es HTML de la propia aplicación: sigue su diseño y sus botones tienen nombre para los lectores de pantalla.

### 4 · Lista lo que el lector marcó

```js
// script.js, líneas 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` pinta cada resaltado en su color; la lista son los mismos registros ordenados por posición, con la página que da `rangeRects`. Al pulsar una entrada se llama a `revealAnnotation`, que lleva sus palabras a la vista.

## La receta completa

Los archivos de abajo se componen a partir de la carpeta de la receta, con el texto de ejemplo y el kit común del Recetario ya incluidos. Para ejecutarlos como una sola página, pon el HTML en `<body>`, el CSS en un elemento `<style>` y el script en un `<script type="module">`; o pega cada uno en el panel correspondiente de un pen nuevo de CodePen (el JS como módulo). El script importa postext desde esm.sh, así que no hay nada que instalar ni compilar.

- Carpeta de la receta: 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 = 'es'; // @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: "El ferri de la noche"
author: "Ines Calder"
---

# El ferri de la noche {kicker="Capítulo uno"}

El ferri salía a las diez, hiciera el tiempo que hiciera, y casi todas las noches Agnes Lowe era la única pasajera que se quedaba en cubierta. Le gustaba el frío. Le gustaba ver cómo el pueblo se encogía detrás del barco hasta quedar en un puñado de ventanas amarillas, luego en una raya y luego en nada.

Su padre había hecho la travesía durante treinta y un años. Conocía el canal por sus ruidos: el golpe de la marea contra la boya del norte, el gemido largo de la cadena en el embarcadero, las gaviotas que solo gritaban cuando venía lluvia. Cuando ella era pequeña le había dicho que un buen marino lee el agua como un estudioso lee un libro, despacio y con un lápiz en la mano.

Entonces no lo había entendido. Lo entendía ahora, la noche en que cruzaba el agua con su cuaderno de bitácora para devolverlo a la oficina del puerto. Cada página estaba llena de marcas pequeñas. Una señal donde la luz de la punta se había encendido tarde. Una cruz donde el motor había tosido. Una vez, en el margen de una entrada de una noche tranquila de octubre, tres palabras en sus mayúsculas cuidadosas: *vimos las ballenas*.

En la oficina querrían los números, las fechas y el combustible. No querrían las ballenas. Agnes había decidido, en algún punto entre la taquilla y la barandilla, que copiaría esas tres palabras en su propio cuaderno antes de entregar nada.

El motor cambió de tono cuando el barco dobló la punta. Delante, la isla mostraba su única farola y la forma blanca de la capilla. Un hombre con un abrigo naranja esperaba en el embarcadero con un cabo enrollado al brazo, y ella supo sin verle la cara que era Tom Harker, que había sido el marinero de su padre y no había llegado tarde ni una sola vez.

—Lo has traído —dijo él, cuando bajaron la pasarela.

—Lo he traído.

No pidió ver el cuaderno. Subió a su lado la cuesta hasta la oficina del puerto, donde aún había una luz encendida, y le contó el invierno en que el hielo entró en el canal y su padre lo estuvo rompiendo con un bichero durante dos horas para que el médico pudiera cruzar. No estaba en el cuaderno. Hay cosas, dijo Tom, que un hombre solo escribe en el agua.

En la puerta de la oficina se detuvo y abrió el cuaderno por la página de octubre. Las mayúsculas eran más pequeñas de lo que recordaba, apretadas contra el papel, como si él hubiera querido que duraran. Las leyó dos veces y cerró la tapa.

Dentro, el empleado le dio las gracias y un recibo, y el cuaderno fue a parar a una caja gris con un número en el costado. Eso fue todo. Cuando salió, Tom miraba el agua oscura más allá del embarcadero, y durante un momento ninguno de los dos habló.

Entonces algo asomó allí fuera, un lomo largo y negro a la luz de la luna, y volvió a hundirse sin un ruido.
`; // 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 ───────────────────────────────────────────────────────────────────────
```

## Variantes

### Subraya con el color del lector

Hay lectores que prefieren una línea a un relleno, y la línea conserva el contraste del texto sobre cualquier papel.

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

### Escribe una nota sobre un resaltado

Un resaltado que además lleva una nota se convierte en una bandera en el margen: [Un cuaderno para el lector: notas sobre lo que elige](https://postext.dev/es/cookbook/reader-notebook.md) monta el cuaderno sobre las mismas anclas.

## Créditos

- Receta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Tipografías: Literata (OFL-1.1), Source Sans 3 (OFL-1.1)
- Código: MIT · Contenido de ejemplo: CC-BY-4.0

## Relacionadas

- [N.º 213 · Resaltados a partir de una lista de rangos](https://postext.dev/es/cookbook/highlights-from-ranges.md): Los registros de una herramienta de revisión, cada uno un rango del Markdown y un veredicto, pintados como resaltados de tres colores con setAnnotations. · Nivel 1 (Básico) · Periódicos y boletines
- [N.º 212 · Seleccionar en la página y leer el rango del Markdown](https://postext.dev/es/cookbook/selection-as-markdown-range.md): postext-viewer comunica una selección sobre las páginas compuestas como un rango del Markdown, el Markdown que abarca y sus trozos línea a línea. · Nivel 1 (Básico) · Revistas y fanzines
- [N.º 217 · Anclas tras una revisión: movidas, ambiguas o huérfanas](https://postext.dev/es/cookbook/anchors-through-a-revision.md): textAnchor guarda cada nota con sus palabras y su contexto; resolveAnchor la busca en la revisión siguiente: en su sitio, movida, ambigua o huérfana. · Nivel 2 (Intermedio) · Manuales, guías y obras de consulta
