跳到主要内容
食谱编号223

排版食谱 · 第13章 · CMS集成

读者的荧光笔:一段文字,一种颜色

在小说页面上选中文字,上方弹出四种颜色;高亮自动扩到整词,以锚点保存,并列入页面旁的清单。

本页内容
输出
Canvas
难度
中级
Postext
已用Postext 1.103.1测试
需要≥ 1.103.0
许可证
更新于2026年12月4日
代码MIT · 文本CC BY 4.0
阅读应用刚打开时:三段文字已用黄、蓝、粉高亮,页面旁的清单里列着同样三段,各带颜色和页码。
阅读应用刚打开时:三段文字已用黄、蓝、粉高亮,页面旁的清单里列着同样三段,各带颜色和页码。
  • 英文样例:尚无中文版本
  • 成品尺寸129 × 198 mm
  • 1栏
  • Literata 10/14.5
  • Source Sans 3
  • 3页
  • 难度
  • Postext 1.103.1
  • 排版用时61 ms
  • 242行代码

简单来说

阅读应用里的一部小说。选中几个词,上方出现四个彩色圆点;点其中一个,这些词就涂上那种颜色。高亮保存在本设备上,并在书旁列出。

成品一览

阅读应用中一部短篇小说 The Night Ferry(《夜渡》)的第一章。读者在一句话上拖过,上方出现一条深色工具条,带四个彩色圆点。点一下,这句话就涂上黄、绿、蓝或粉色,拖选的范围也自动扩到整词。点一下已有的高亮,工具条再次出现,可以换颜色或删除。右侧一栏是读者自己的清单,按阅读顺序排列,每段都标出颜色和页码。这一切都保存在读者的设备上,以锚点的形式存放;出版方发布勘误版之后,锚点照样能找到原来的文字。

这道食谱解答

  • 怎样让读者用自己选的颜色标亮书中的段落?

简短回答

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

用料

类型
Literata, Source Sans 3(SIL OFL 1.1)
素材
无:所有图片都用代码绘制

做法

#1 · 用锚点而不是偏移量保存高亮

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

一条高亮保存为一种颜色加一个来自 textAnchor 的锚点:范围、它覆盖的文字,以及两侧的少量上下文。应用打开一本书时,resolveAnchor 在当前文本中逐一找回它们。同一版本中结果是 exact;上游改动后是 moved,带有新的偏移量;被删掉的段落则是 orphaned,应用会把它略去(或另行列出,由读者决定去留)。

#2 · 把选区扩到整词并给出颜色

代码就是上面的简短回答。查看器把每次完成的选区报告为 Markdown 中的一个范围。wordRangeAt 把落在词中间的一端扩到整个词,因此手指拖得再随意,也不会只涂半个词。扩好的范围用 setSelection 交回查看器,处理函数要忽略这次回声,否则调色板会没完没了地弹出。

#3 · 把调色板放在段落上方

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

rangeRects 以页面像素给出段落的第一行,pageToClient 把它换算成窗口像素,所以无论缩放多少,工具条都居中停在文字上方。在 zoomchange 和滚动时,它都跟着文字移动。工具条是应用自己的 HTML,因此沿用应用的设计,按钮也带有供屏幕阅读器读出的名称。

#4 · 列出读者标记的内容

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

setAnnotations 用各自的颜色画出每条高亮;清单就是同一批记录按偏移量排序,页码取自 rangeRects。点一下某个条目会调用 revealAnnotation,把它的文字滚到视野中。

完整食谱

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

组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)

变化

#用读者的颜色画下划线

有些读者更喜欢线条而不是底色,而且线条在任何纸色上都不影响文字的对比度。

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

#在高亮上写批注

带批注的高亮会变成页边的小旗:读者的笔记本:给选中的文字写笔记 在同样的锚点上做出一本笔记。

致谢

文本
原创文字, CC BY 4.0
字体
Literata (SIL OFL 1.1) · Source Sans 3 (SIL OFL 1.1)