Vai al contenuto principale
Ricetta numero 223

Ricettario · Capitolo 13 · Integrazione con un CMS

Un evidenziatore per chi legge: un passo e un colore

Selezionando parole di un romanzo si aprono quattro colori; l'evidenziazione si allarga a parole intere, si salva come ancora ed entra in un elenco.

In questa pagina
Output
Canvas
Livello
Intermedio
Postext
Provata con Postext 1.103.1
Richiede ≥ 1.103.0
Licenza
Aggiornata il 4 dic 2026
Codice MIT · Testo CC BY 4.0
L'app di lettura all'apertura: tre passi già evidenziati in giallo, blu e rosa, e gli stessi tre nell'elenco accanto alle pagine, con colore e pagina.
L'app di lettura all'apertura: tre passi già evidenziati in giallo, blu e rosa, e gli stessi tre nell'elenco accanto alle pagine, con colore e pagina.
  • Esempio in inglese: non c’è ancora un’edizione italiana
  • Formato 129 × 198 mm
  • 1 colonna
  • Literata 10/14,5
  • Source Sans 3
  • 3 pagine
  • Livello
  • Postext 1.103.1
  • Impaginato in 61 ms
  • 242 righe di codice

In breve

Un romanzo in un'app di lettura. Seleziona qualche parola e sopra compaiono quattro pallini colorati; scegline uno e le parole si colorano. Le evidenziazioni restano su questo dispositivo, elencate accanto al libro.

Che cosa comporrai

Il primo capitolo di un breve romanzo, The Night Ferry («Il traghetto della notte»), in un'app di lettura. Il lettore trascina su una frase e sopra compare una barra scura con quattro pallini colorati. Un tocco e la frase si colora di giallo, verde, blu o rosa, con il trascinamento allargato a parole intere. Un tocco su un'evidenziazione riporta la barra, per cambiarne il colore o toglierla. La colonna a destra è l'elenco del lettore, in ordine di lettura, ogni passo con il suo colore e la sua pagina. Tutto resta sul dispositivo del lettore, come ancore che ritrovano le loro parole anche quando l'editore pubblica un'edizione corretta.

Questa ricetta risponde a

  • Come permetto ai lettori di evidenziare passi del libro nei colori che scelgono?

La risposta breve

script.js · righe 172–206nel codice completo
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));

Ingredienti

Tipo
Literata, Source Sans 3 (SIL OFL 1.1)
Risorse
Nessuna: ogni immagine è disegnata nel codice

Preparazione

#1 · Salva le evidenziazioni come ancore, non come posizioni

script.js · righe 146–168nel codice completo
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'evidenziazione si salva come un colore e un'ancora di textAnchor: l'intervallo, le parole che copriva e un po' di testo da ogni lato. Quando l'app apre un libro, resolveAnchor ritrova ognuna nel testo attuale. Nella stessa edizione la risposta è exact; dopo una correzione è moved, con posizioni nuove, e un passo tagliato diventa orphaned, che l'app lascia fuori (o mostra a parte, perché il lettore decida).

#2 · Allinea la selezione e offri i colori

Il codice è la risposta breve qui sopra. Il visualizzatore comunica ogni selezione conclusa come un intervallo del Markdown. wordRangeAt allarga alla parola intera un estremo che cade dentro una parola, così un trascinamento distratto non lascia mai mezza parola colorata. L'intervallo allineato torna al visualizzatore con setSelection, e il gestore ignora quell'eco, altrimenti offrirebbe la tavolozza all'infinito.

#3 · Metti la tavolozza sopra il passo

script.js · righe 210–248nel codice completo
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 dà la prima riga del passo in pixel di pagina e pageToClient la converte in pixel della finestra, così la barra resta centrata sulle parole a qualsiasi zoom. Si sposta con loro su zoomchange e durante lo scorrimento. La barra è HTML dell'app stessa: ne segue il design e i suoi pulsanti hanno un nome per i lettori di schermo.

#4 · Elenca ciò che il lettore ha segnato

script.js · righe 252–271nel codice completo
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 dipinge ogni evidenziazione nel suo colore; l'elenco sono gli stessi record ordinati per posizione, con la pagina data da rangeRects. Un tocco su una voce chiama revealAnnotation, che porta in vista le sue parole.

La ricetta completa

// ═══ 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) } } },
  ] },
};

Lo script.js composto funziona così com’è: incollalo nello script modulo di qualsiasi pagina, oppure apri la ricetta su CodePen. Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)

Varianti

#Sottolinea col colore del lettore

Alcuni lettori preferiscono una linea a un riempimento, e la linea conserva il contrasto del testo su qualsiasi carta.

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

#Scrivi una nota su un'evidenziazione

Un'evidenziazione che porta anche una nota diventa una bandierina a margine: Il quaderno del lettore: note su ciò che seleziona costruisce il quaderno sulle stesse ancore.

Crediti

Testo
Testo originale, CC BY 4.0
Font
Literata (SIL OFL 1.1) · Source Sans 3 (SIL OFL 1.1)