En poques paraules
Una novel·la en una aplicació de lectura. Selecciona unes paraules i a sobre apareixen quatre punts de color; tria'n un i queden ombrejades d'aquell color. Els subratllats es desen al dispositiu i es llisten al costat del llibre.
Què compondràs
El primer capítol d'una novel·la breu, The Night Ferry («El ferri de la nit»), en una aplicació de lectura. El lector arrossega per sobre d'una frase i hi apareix una barra fosca amb quatre punts de color. Un toc i la frase queda ombrejada de groc, verd, blau o rosa, amb l'arrossegament ajustat a paraules senceres. En prémer un destacat torna la barra, per canviar-li el color o treure'l. La columna de la dreta és la llista del mateix lector, per ordre de lectura, cada passatge amb el seu color i la seva pàgina. Tot es desa al dispositiu del lector, com a ancoratges que continuen trobant les seves paraules quan l'editorial publica una edició corregida.
Aquesta recepta respon a
- Com deixo que els lectors ressaltin passatges del llibre amb els seus propis colors?
La resposta curta
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
- Funcions
- Marques d'anotacióÀncores que sobreviuen a les revisionsVisor de pàgines (postext-viewer)Geometria del text (rangs i punts)Fonts abans de compondreObertures dissenyadesCapçaleres i folisMarges simètricsPaleta de color semàntica
- També fa servir
- Atributs de títolCapçaleres segons el tipus de pàgina
- Tipografia
- Literata, Source Sans 3 (SIL OFL 1.1)
- Recursos
- Cap: totes les imatges es dibuixen en codi
Elaboració
#1 · Desa els destacats com a ancoratges, no com a posicions
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 destacat es desa com un color i un ancoratge de textAnchor: el rang, les paraules que cobria i una mica de text a cada costat. Quan l'aplicació obre un llibre, resolveAnchor troba cadascun al text que té ara. A la mateixa edició la resposta és exact; després d'una correcció és moved, amb posicions noves, i un passatge que s'ha suprimit queda orphaned, que l'aplicació deixa fora (o mostra a part, perquè el lector decideixi).
#2 · Ajusta la selecció i ofereix els colors
El codi és la resposta curta de més amunt. El visor comunica cada selecció acabada com un rang del Markdown. wordRangeAt amplia a la paraula sencera un extrem que cau dins d'una paraula, de manera que un arrossegament descuidat mai no deixa mitja paraula ombrejada. El rang ajustat torna al visor amb setSelection, i el gestor ignora aquest eco; si no, la paleta s'oferiria sense fi.
#3 · Col·loca la paleta sobre el passatge
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 dona la primera línia del passatge en píxels de pàgina i pageToClient la passa a píxels de la finestra, així que la barra queda centrada sobre les paraules amb qualsevol zoom. Es mou amb elles a zoomchange i en desplaçar-se. La barra és HTML de la mateixa aplicació: segueix el seu disseny i els seus botons tenen nom per als lectors de pantalla.
#4 · Llista el que el lector ha marcat
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 destacat del seu color; la llista són els mateixos registres ordenats per posició, amb la pàgina que dona rangeRects. En prémer una entrada es crida revealAnnotation, que porta les seves paraules a la vista.
La recepta 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 = '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) } } },
] },
};
<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>
/* 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;
}
L'script.js compost funciona tal com és: enganxa'l com a script de mòdul en qualsevol pàgina o obre la recepta a CodePen. Carpeta de la recepta a GitHub ↗ (s'obre en una pestanya nova)
Variants
#Subratlla amb el color del lector
Hi ha lectors que prefereixen una línia a un farciment, i la línia conserva el contrast del text sobre qualsevol paper.
- id, kind: 'highlight', range, color: PENS[pen].color,
+ id, kind: 'underline', range, color: PENS[pen].color,#Escriu una nota sobre un destacat
Un destacat que a més porta una nota es converteix en una bandera al marge: Un quadern del lector: notes sobre el que selecciona munta el quadern sobre els mateixos ancoratges.
Crèdits
- Recepta
- Ignacio Ferro
- Text
- Text original, CC BY 4.0
- Fonts
- Literata (SIL OFL 1.1) · Source Sans 3 (SIL OFL 1.1)
- Codi
- MIT, com Postext
Editar aquest text ↗ (s'obre en una pestanya nova)Carpeta de la recepta a GitHub ↗ (s'obre en una pestanya nova)



