跳到主要内容
食谱编号224

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

读者的笔记本:给选中的文字写笔记

在课本里选中一段文字并写下笔记:文字被着色,页边插上编号旗标,旁边的笔记本把所有笔记列出来。

本页内容
类型
教科书
输出
Canvas
难度
中级
Postext
已用Postext 1.103.1测试
需要≥ 1.103.0
许可证
更新于2026年12月4日
代码MIT · 文本CC BY 4.0
学习应用刚打开时:第 4 章有三条笔记,每段文字都着了色,外侧页边插着编号旗标,笔记本列出它们的文字和页码。
学习应用刚打开时:第 4 章有三条笔记,每段文字都着了色,外侧页边插着编号旗标,笔记本列出它们的文字和页码。
  • 英文样例:尚无中文版本
  • 成品尺寸170 × 240 mm
  • 1栏
  • Source Serif 4 10.5/15
  • Source Sans 3
  • 2页
  • 难度
  • Postext 1.103.1
  • 排版用时57 ms
  • 224行代码

简单来说

一本历史课本放在学习应用里。选中几个字,下方就打开一张卡片,可以写笔记。这些字会染上浅色,页边多出一个编号小标签。书旁列出全部笔记,点任意一条都能在页面上打开。

成品一览

学习应用里的一章历史课本,When books became cheap(《书变便宜的时候》)。学生选中一段文字,下方打开一张卡片,引出这段文字,并留出写字的框。保存后,这段文字着色,宽阔的外侧页边出现一面编号旗标。点旗标或着色的文字,笔记就在页面上打开,附有编辑和删除按钮。右边的笔记本按阅读顺序列出全部笔记,附上所涉文字和页码,正是边读边攒下的复习单。笔记以锚点的形式留在学生的设备上,所以课本出了勘误版,笔记仍落在原来的文字上。

这道食谱解答

  • 怎样让读者给选中的段落写笔记,并把笔记列出来?

简短回答

script.js · 第137–158行在完整代码中
const view = createViewer($('viewer'), {
  document: doc, markdown, zoom: 'fit-width', maxZoom: 0.85, labels: L.viewer,
  marks: { noteSide: 'end' }, // the flags in the wide outer margin
});
let card = null; // what the card over the page shows: { range } to write, { id } to read
view.on('select', ({ range }) => {
  const same = card?.range && card.range.start === range?.start && card.range.end === range?.end;
  if (range && range.end > range.start && !same) compose({ range });
});
view.on('annotationclick', ({ id }) => read(id));
function addNote(range, body) {
  notes = [...notes, { id: nextId(), body, range }];
  save();
  render();
}
function render() {
  notes.sort((a, b) => a.range.start - b.range.start);
  view.setAnnotations(notes.map(({ id, range }, i) => ({
    id, kind: 'note', range, label: String(i + 1), color: INK,
  })));
  renderNotebook();
}

用料

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

做法

#1 · 给每条笔记存一个锚点

script.js · 第112–133行在完整代码中
const KEY = `${RECIPE}:${LANG}`;
const quote = (text) => {
  const start = markdown.indexOf(text);
  return { start, end: start + text.length };
};
const seed = t({
  en: [['the skins of some two hundred calves', 'A Bible cost a herd of calves. Compare with a house today.'],
    ['used again', 'Movable type: the letters are reused, not the page.'],
    ['Printing also fixed the text.', 'Key idea for the essay: printing made every copy the same.']],
  es: [['la piel de unos doscientos terneros', 'Una Biblia costaba un rebaño de terneros. Compararlo con una casa hoy.'],
    ['se volvían a usar', 'Tipos móviles: se reutilizan las letras, no la página.'],
    ['La imprenta también fijó el texto.', 'Idea clave para el trabajo: la imprenta hizo iguales todos los ejemplares.']],
}).map(([text, body], i) => ({ id: `n${i + 1}`, body, anchor: textAnchor(markdown, quote(text)) }));
const kept = JSON.parse(localStorage.getItem(KEY) ?? 'null') ?? seed;
let notes = kept.flatMap((n) => {
  const found = resolveAnchor(markdown, n.anchor);
  return found.status === 'exact' || found.status === 'moved'
    ? [{ ...n, range: { start: found.start, end: found.end } }] : [];
});
const nextId = () => `n${1 + Math.max(0, ...notes.map((n) => Number(n.id.slice(1)) || 0))}`;
const save = () => localStorage.setItem(KEY, JSON.stringify(
  notes.map(({ id, body, range }) => ({ id, body, anchor: textAnchor(markdown, range) }))));

应用把一条笔记存成它的正文加上这段文字的锚点(textAnchor):范围、文字本身,以及两侧的一点上下文。打开时,resolveAnchor 在当前版本里找到每一段文字。出版社在前一页做了更正,位置就会偏移;锚点能重新找到这些文字,只有被删掉的段落才会丢失。

#2 · 把选区变成笔记标记

代码就是上面的简短回答。查看器把选好的文字报告为 Markdown 中的一个范围,应用为它打开卡片。保存后的笔记是一个 note 标记:给文字着色,并在页边插一面旗标;noteSide: 'end' 让所有旗标都落在外侧页边。标签是笔记按阅读顺序排的编号,所以在章节前面写一条笔记,后面的编号都会顺延,和印刷书一样。

#3 · 在文字下方打开卡片

script.js · 第162–215行在完整代码中
function compose({ range, id }) {
  card = { range, id };
  $('card').dataset.mode = 'write';
  $('quote').textContent = plain(range);
  $('body').value = id ? notes.find((n) => n.id === id).body : '';
  show();
  $('body').focus({ preventScroll: true });
}
function read(id) {
  const note = notes.find((n) => n.id === id);
  card = { id, range: note.range };
  $('card').dataset.mode = 'read';
  $('number').textContent = `${L.note} ${notes.indexOf(note) + 1}`;
  $('quote').textContent = plain(note.range);
  $('text').textContent = note.body;
  show();
}
function show() {
  $('card').hidden = false;
  place();
  for (const item of $('list').children) item.setAttribute('aria-current', String(item.dataset.id === card.id));
}
function hide() {
  card = null;
  $('card').hidden = true;
  view.setSelection(null);
  for (const item of $('list').children) item.removeAttribute('aria-current');
}
// Under the last line of the words: page px turned into the window's px.
function place() {
  if (!card) return;
  const last = view.rangeRects(card.range).at(-1);
  const at = last && view.pageToClient(last.pageIndex, last.rect.x, last.rect.y + last.rect.height);
  if (at) Object.assign($('card').style, { left: `${at.x}px`, top: `${at.y + 10}px` });
}
$('save').addEventListener('click', () => {
  const body = $('body').value.trim();
  if (body && card.id) notes = notes.map((n) => (n.id === card.id ? { ...n, body } : n));
  else if (body) return void (addNote(card.range, body), hide());
  save();
  render();
  hide();
});
$('cancel').addEventListener('click', hide);
$('edit').addEventListener('click', () => compose(card));
$('remove').addEventListener('click', () => {
  notes = notes.filter((n) => n.id !== card.id);
  save();
  render();
  hide();
});
view.on('zoomchange', place);
view.element.addEventListener('scroll', place, { capture: true, passive: true });
addEventListener('keydown', (e) => e.key === 'Escape' && hide());

一张卡片兼顾两种用途:写的时候,有引出的文字、文本框和保存按钮;读的时候,有笔记和编辑、删除按钮。rangeRects 以页面像素给出这段文字的最后一行,pageToClient 把它换算成窗口像素,于是卡片在任何缩放下都待在文字下方,滚动时也跟着走。

#4 · 让笔记本留在页面旁边

script.js · 第219–233行在完整代码中
function renderNotebook() {
  $('count').textContent = L.count(notes.length);
  $('list').replaceChildren(...notes.map(({ id, body, range }, i) => {
    const item = document.createElement('button');
    item.type = 'button';
    item.dataset.id = id;
    item.innerHTML = '<span class="n"></span><q></q><p></p><small></small>';
    item.querySelector('.n').textContent = i + 1;
    item.querySelector('q').textContent = plain(range);
    item.querySelector('p').textContent = body;
    item.querySelector('small').textContent = L.page(view.rangeRects(range)[0].pageIndex + 1);
    item.addEventListener('click', () => { view.revealAnnotation(id); read(id); });
    return item;
  }));
}

笔记本就是按阅读顺序排列的同一批记录。点一条条目,revealAnnotation 把它的文字滚到眼前,并打开它的卡片;卡片开着时,这条条目一直标亮。

完整食谱

// ═══ Postext Cookbook · Nº 224 · A reader's notebook ═════════════════════════════════
// https://postext.dev/en/cookbook/reader-notebook
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Source Serif 4, Source Sans 3 (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A history textbook in a study app. Select a passage and write a note on it: the passage
// is tinted and a numbered flag goes in the margin. A flag opens its note over the page,
// and the notebook beside the pages lists every note with the words it is about. The notes
// are kept on this device as anchors, so a corrected edition of the book keeps them.
import { buildDocumentWithFonts, renderPageToCanvas } 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-notebook';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#1f2328', // text
  accent: '#24527a', // ink blue: chapter number, headings, folio
  muted: '#68707a', // running head
};
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 textbook page with a wide outer margin, where the reader's flags go
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(170), height: mm(240), dpi: 150,
    margins: { top: mm(22), bottom: mm(24), left: mm(20), right: mm(48) } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Source Serif 4', fontSize: pt(10.5), lineHeight: pt(15),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'left', firstLineIndent: mm(5), indentAfterHeading: false,
    hyphenation: { enabled: true }, avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: 'Source Sans 3', color: col('accent'), fontWeight: 700, levels: [
    { level: 1, fontSize: pt(22), lineHeight: pt(26), marginTop: pt(0), marginBottom: pt(15) },
    { level: 2, fontSize: pt(11), lineHeight: pt(15), marginTop: pt(15), marginBottom: pt(4) },
  ] },
  header: { elements: [
    { kind: 'text', id: 'head', content: '{title}', fontFamily: 'Source Sans 3', fontSize: pt(7.5),
      fontWeight: 700, letterSpacing: pt(1.2), textTransform: 'uppercase', color: col('muted'),

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

变化

#先划线,后写字

许多读者先标出一段,过后再回来看。读者的荧光笔:一段文字,一种颜色 在同样的锚点上保存彩色划线;一条笔记可以从划线开始。

#把笔记本导出为 Markdown

锚点里存着每段文字,所以几行代码就能把笔记本写成一张复习单。

const sheet = notes.map(({ range, body }) => `> ${plain(range)}\n\n${body}`).join('\n\n');

致谢

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