跳到主要内容
食谱编号217

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

跨修订的锚点:原位、移动、歧义或孤立

textAnchor 把每条批注连同它的文字和上下文一起保存;resolveAnchor 在下一版中找到它:原位、移动、歧义或孤立。

本页内容
难度
中级
Postext
已用Postext 1.103.1测试
需要≥ 1.103.0
许可证
更新于2026年12月4日
代码MIT · 文本CC BY 4.0
在草稿上做的五条批注到修订稿中查找:原处(绿色)、移动(琥珀色)、歧义并给每个候选位置加框(紫色),还有一条成了孤儿,它的文字已经不在。
在草稿上做的五条批注到修订稿中查找:原处(绿色)、移动(琥珀色)、歧义并给每个候选位置加框(紫色),还有一条成了孤儿,它的文字已经不在。
  • 英文样例:尚无中文版本
  • 成品尺寸135 × 200 mm
  • 1栏
  • Newsreader 10/13.6
  • Archivo
  • 2页
  • 难度
  • Postext 1.103.1
  • 排版用时60 ms
  • 148行代码

简单来说

一位编辑在一本徒步指南的草稿上留了五条批注,之后作者改写了其中几处。页面在新文本里查找每条批注的文字。有的还在原处,有的移了位置,有一条能对上三个地方,还有一条已经不见了。找到的批注画在新页面上。

成品一览

徒步指南 Walks from the Valley Station 中的一条路线,排在 135 × 200 mm 的页面上。一位编辑在初稿上留了五条批注;之后作者加了一句、改写了一句、删掉了一句。这个 pen 在修订后的文本里查找每条批注,并在两处显示结果。右边的清单给出每条批注的状态:一条原位,两条移动,一条在三个跨栏阶梯之间有歧义,一条孤立。左边的页面画出保留下来的批注,在页边编号,并用方框标出歧义批注可能指向的三个位置。

这道食谱解答

  • 文本修订后,怎样让批注仍然附在原来那段文字上?

简短回答

script.js · 第163–179行在完整代码中
const COLOR = { exact: '#1f7a45', moved: '#b0640a', ambiguous: '#7b4cc4' };
const found = NOTES.map((note) => resolveAnchor(markdown, note.anchor));
const marks = NOTES.flatMap((note, i) => {
  const at = found[i];
  const label = String(i + 1);
  // In place or moved: one range, the note's mark with its number in the margin.
  if (at.status === 'exact' || at.status === 'moved') {
    return [{ id: note.id, kind: 'note', range: at, label, color: COLOR[at.status] }];
  }
  // Ambiguous: every place the words fit, boxed, for a person to choose.
  if (at.status === 'ambiguous') {
    return at.candidates.map((range, k) => ({ id: `${note.id}.${k}`, kind: 'box', range,
      color: COLOR.ambiguous }));
  }
  return []; // orphaned: the words are gone, the note stays in the thread
});
view.setAnnotations(marks);

用料

类型
Newsreader, Archivo(SIL OFL 1.1)
素材
无:所有图片都用代码绘制

做法

#1 · 保存锚点,而不是位置

script.js · 第121–144行在完整代码中
// [the words to find in the draft, the words noted, the note]. A CMS reads the anchors from
// its database; here they are made on the draft so the pen runs on its own.
const NOTES = t({
  en: [
    ['follow the wall up the field', 'the wall', 'Rebuilt last winter: does it reach the top?'],
    ['a cairn that walkers have built', 'a cairn', 'A photograph of the cairn would help here.'],
    ['Cross the stile at', 'the stile', 'Which way does this stile face?'],
    ['the bog on either side is deeper', 'the bog on either side is deeper',
      'Rangers say knee-deep at most. Too alarming?'],
    ['The stepping stones at the ford', 'The stepping stones', 'Give the detour in minutes.'],
  ],
  es: [
    ['sigue el muro prado arriba', 'el muro', '¿Lo rehicieron este invierno? ¿Sigue hasta arriba?'],
    ['un hito de piedras que los caminantes', 'un hito de piedras', 'Aquí iría bien una foto.'],
    ['Salta la escalera del', 'la escalera', '¿Hacia dónde da esta escalera?'],
    ['la turbera de los lados es más honda', 'la turbera de los lados es más honda',
      'Los guardas dicen que no pasa de la rodilla.'],
    ['Las piedras del vado resbalan', 'Las piedras del vado', 'Da el rodeo en minutos.'],
  ],
}).map(([around, words, body], i) => {
  const start = earlier.indexOf(around) + around.indexOf(words);
  const anchor = textAnchor(earlier, { start, end: start + words.length }); // 32 chars a side
  return { id: `n${i + 1}`, body, anchor };
});

textAnchor 保存范围、范围内的文字以及两边各 32 个字符。它只是普通的 JSON,适合放在批注旁边的数据库行里。CMS 在批注写下时保存它;这个 pen 为了能独立运行,在草稿上生成锚点。

#2 · 在新文本中查找每个锚点

代码就是上面的简短回答。resolveAnchor 先检查保存的位置,再在整个文件中查找带完整上下文的文字,然后缩短上下文,最后只找文字本身,在第一个得出答案的步骤停下。它从不在两个位置之间做选择:关于“the stile”的批注在句子改写后失去了上下文,单凭文字能对上三个跨栏阶梯,所以答案是带三个候选的 ambiguous。每种状态画什么,由网站自己决定。

#3 · 说明每条批注的去向

script.js · 第183–211行在完整代码中
const STATUS = t({
  en: { exact: 'In place', moved: 'Moved', ambiguous: 'Ambiguous', orphaned: 'Orphaned' },
  es: { exact: 'En su sitio', moved: 'Movida', ambiguous: 'Ambigua', orphaned: 'Huérfana' },
});
const detail = (note, at) => ({
  exact: () => `${at.start}`,
  moved: () => `${note.anchor.start} → ${at.start}`,
  ambiguous: () => at.candidates.map((c) => c.start).join(' · '),
  orphaned: () => t({ en: 'the words are gone', es: 'las palabras ya no están' }),
})[at.status]();
document.getElementById('notes').replaceChildren(...NOTES.map((note, i) => {
  const at = found[i];
  const li = document.createElement('li');
  li.className = at.status;
  li.innerHTML = '<button type="button"><b></b><span class="status"></span><q></q>'
    + '<span class="body"></span><small></small></button>';
  const [n, status, quote, body, small] = li.querySelectorAll('b, .status, q, .body, small');
  n.textContent = String(i + 1);
  status.textContent = STATUS[at.status];
  quote.textContent = note.anchor.text;
  body.textContent = note.body;
  small.textContent = detail(note, at);
  const id = at.status === 'ambiguous' ? `${note.id}.0` : note.id;
  li.firstChild.addEventListener('click', () => view.revealAnnotation(id, { behavior: 'smooth' }));
  li.firstChild.disabled = at.status === 'orphaned';
  return li;
}));
document.getElementById('title').textContent = t({ en: 'Notes on the draft',
  es: 'Notas del borrador' });

移动的批注显示旧位置和新位置,歧义的显示候选位置,孤立的批注把文字加上删除线保留下来,让编辑仍然知道它说的是什么。点一下批注,查看器就用 revealAnnotation 滚动到它的标记。

完整食谱

// ═══ Postext Cookbook · Nº 217 · Anchors through a revision ═══════════════════════════
// https://postext.dev/en/cookbook/anchors-through-a-revision
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Newsreader, Archivo (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// An editor left five notes on the first draft of a walking guide; the author then revised the
// text. Each note was stored as an anchor (its words and some context), and each is looked for
// in the new revision: found in place, moved, ambiguous between several places, or orphaned.
// The notes that survive are drawn on the new pages, the others wait in the list for a person.
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 = 'anchors-through-a-revision';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#202421', // text
  accent: '#3d6b45', // moorland green: headings, folios
  muted: '#6b7068', // 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
const LEAD = 13.6; // pt of body leading

const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'Archivo', fontSize: pt(7), fontWeight: 500, letterSpacing: pt(0.8),
  textTransform: 'uppercase', color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(10) } }, ...extra });
const folio = { fontWeight: 600, color: col('accent') };

const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(135), height: mm(200), dpi: 150,
    margins: { top: mm(19), bottom: mm(20), left: mm(17), right: mm(15), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Newsreader', fontSize: pt(10), lineHeight: pt(LEAD),
    color: col('ink'), boldColor: col('accent'), italicColor: col('ink'),
    referenceColor: col('ink'), textAlign: 'justify', firstLineIndent: mm(4),
    indentAfterHeading: false, hyphenation: { enabled: true }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },

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

变化

#保留更多上下文

更长的上下文能区分重复相同文字的段落,但批注周围的文字被改写时会更早失效。

-  const anchor = textAnchor(earlier, { start, end: start + words.length }); // 32 chars a side
+  const anchor = textAnchor(earlier, { start, end: start + words.length }, { context: 64 });

#不退到只找文字

minContext 设为 8 时,批注两边各需要 8 个没有变化的字符,短批注会变成 orphaned,而不是碰上别处的常见词。

-  const found = NOTES.map((note) => resolveAnchor(markdown, note.anchor));
+  const found = NOTES.map((note) => resolveAnchor(markdown, note.anchor, { minContext: 8 }));

致谢

文本
原创文字, CC BY 4.0
字体
Newsreader (SIL OFL 1.1) · Archivo (SIL OFL 1.1)