跳到主要内容
食谱编号218

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

应用已接受的修改,并让其余批注随之移动

applyEdits 把已接受的修改写进 Markdown,并带着其余每条批注的锚点一起移动;修改落在其中的批注会被标出。

本页内容
难度
高级
Postext
已用Postext 1.103.1测试
需要≥ 1.103.0
许可证
更新于2026年12月4日
代码MIT · 文本CC BY 4.0
草稿和 applyEdits 之后的文本并排:三处修改已应用(绿色),一处被拒、仍未处理(灰色),批注 2 标成 2?,因为有修改落在它的文字里。
草稿和 applyEdits 之后的文本并排:三处修改已应用(绿色),一处被拒、仍未处理(灰色),批注 2 标成 2?,因为有修改落在它的文字里。
  • 英文样例:尚无中文版本
  • 成品尺寸130 × 190 mm
  • 1栏
  • Spectral 9.4/13.4
  • Karla
  • 2页
  • 难度
  • Postext 1.103.1
  • 排版用时4 ms
  • 153行代码

简单来说

一篇杂志文章有四处修改建议和编辑的三条批注。其中三处修改被接受并写进文本。批注随着它们的文字移动,文字被改动过的那一条会被标出,提醒再看一遍。

成品一览

Field Notes on Ice 中的一篇文章,排在 130 × 190 mm 的杂志页面上,显示两次。左边是草稿,四处修改建议画成校对符号,还有编辑的三条编号批注。右边是把三处已接受的修改写进 Markdown 并重新排版后的文本:新文字染成绿色,批注随文字移动,被拒绝的删除仍以灰色保留,批注 2 标成琥珀色,因为一处已接受的修改改动了它所在的文字。

这道食谱解答

  • 怎样把已接受的修改写进Markdown,并让其余批注随之移动?

简短回答

script.js · 第152–177行在完整代码中
const accepted = edits.filter((e) => e.accepted);
const declined = edits.filter((e) => !e.accepted);
const kept = [...notes.map((n) => n.anchor), ...declined.map((e) => textAnchor(markdown, e))];
// One call: the new Markdown, a map of old offsets to new ones, and every anchor carried.
const { markdown: next, map, anchors } = applyEdits(markdown, accepted, kept);
const after = await buildDocumentWithFonts({ markdown: next }, config, kitFonts(FONTS));
const marks = [
  // The text each accepted edit put in, where it now is.
  ...accepted.map((e, i) => {
    const start = mapOffset(map, e.start, 'before');
    return { id: `a${i}`, kind: 'highlight', range: { start, end: start + e.text.length },
      color: '#1f8a4c' };
  }),
  // The notes: a note an edit fell inside is touched, for a person to read again.
  ...notes.map((n, i) => {
    const { anchor, touched } = anchors[i];
    return { id: `n${i}`, kind: 'note', range: anchor, label: touched ? `${i + 1}?` : `${i + 1}`,
      color: touched ? '#c4720a' : undefined };
  }),
  // The declined edit stays open on the new text.
  ...declined.map((e, k) => {
    const { start, end } = anchors[notes.length + k].anchor;
    return suggestion({ ...e, start, end }, `d${k}`);
  }),
];
openPages('after', after, next, marks);

用料

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

做法

#1 · 把建议和批注保存为锚点

script.js · 第94–125行在完整代码中
// A suggestion: [words that place it, the words it changes ('' inserts after them), the new
// text ('' deletes), accepted?]. A note: [the words it is on, what the editor wrote].
const [EDITS, NOTES] = t({
  en: [[
    ['always on the move', 'on the move', 'moving', true],
    ['slides on it', '', ' (basal sliding)', true],
    ['the speed doubles', 'doubles', 'can double', true],
    ['like a very stiff', 'very ', '', false],
  ], [
    ['a stake hammered into the surface', 'A photograph of a survey stake?'],
    ['the speed doubles for a few days', 'Which glaciers? Give a source.'],
    ['between 30 and 200 metres a year', 'Name one glacier as an example.'],
  ]],
  es: [[
    ['siempre en movimiento', 'en movimiento', 'moviéndose', true],
    ['resbala sobre ella', '', ' (deslizamiento basal)', true],
    ['la velocidad se duplica', 'se duplica', 'puede duplicarse', true],
    ['líquido muy rígido', 'muy ', '', false],
  ], [
    ['una estaca clavada en la superficie', '¿Una foto de una estaca de medición?'],
    ['la velocidad se duplica durante unos días', '¿En qué glaciares? Falta la fuente.'],
    ['entre 30 y 200 metros al año', 'Pon un glaciar concreto como ejemplo.'],
  ]],
});
const place = (around, words) => {
  const at = markdown.indexOf(around) + (words ? around.indexOf(words) : around.length);
  return { start: at, end: at + words.length };
};
const edits = EDITS.map(([around, words, text, accepted]) =>
  ({ ...place(around, words), text, accepted }));
const notes = NOTES.map(([words, body]) =>
  ({ body, anchor: textAnchor(markdown, place(words, words)) }));

pen 按文字把每条记录放到草稿上,就像 CMS 从数据表里读出它们一样。一条建议变成一处修改 { start, end, text }:两端相同是插入,文字为空是删除。一条批注保存一个 textAnchor,即它的范围、文字和少量上下文。

#2 · 一次调用应用已接受的修改

代码就是上面的简短回答。applyEdits 接收所有以草稿位置表示的修改,顺序不限,所以网站从不需要因为一处修改去挪动另一处。它返回新的 Markdown、一个可换算任意其他位置的 map,以及穿过这些修改的每个锚点:按前面修改增删的长度移动,修改落在其中的标为 touched。整个过程不需要查找,所以这样移动的锚点不会变得有歧义。mapOffset 加上 'before' 就能把每段新文字放到它现在开始的位置。

#3 · 说明颜色的含义

script.js · 第181–190行在完整代码中
const legend = t({
  en: [['Draft', '3 edits accepted, 1 declined (grey) · notes 1–3'],
    ['After applyEdits', 'green: applied · 2?: an edit fell inside note 2 · grey: still open']],
  es: [['Borrador', '3 cambios aceptados, 1 rechazado (gris) · notas 1–3'],
    ['Tras applyEdits', 'verde: aplicado · 2?: un cambio dentro de la nota 2 · gris: pendiente']],
});
for (const [i, [title, text]] of legend.entries()) {
  document.querySelectorAll('#pages h2')[i].textContent = title;
  document.querySelectorAll('#pages p')[i].textContent = text;
}

被触及的批注在小旗上加一个问号,并换一种颜色。批注是否仍适用于“can double”由编辑决定;Postext 只报告文字变了。相互重叠的修改会抛出 RangeError,因为对同一段文字的两处修改需要有人来选择。

完整食谱

// ═══ Postext Cookbook · Nº 218 · Applying accepted edits ═════════════════════════════
// https://postext.dev/en/cookbook/applying-accepted-edits
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Spectral, Karla (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A magazine piece with four suggested edits and three editor's notes. Three edits are
// accepted and written into the Markdown with applyEdits; the notes and the declined edit are
// carried through as anchors, without a search, and a note an edit fell inside comes back
// flagged as touched. The draft and the new text are laid out side by side, each with its marks.
import { buildDocumentWithFonts, renderPageToCanvas } from 'https://esm.sh/postext';
import { textAnchor, applyEdits, mapOffset } 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 = 'applying-accepted-edits';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#1c1f24', // text
  accent: '#2b5f8a', // glacier blue: title, subheads, folios
  muted: '#677080', // 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.4; // pt of body leading

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

const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(130), height: mm(190), dpi: 150,
    margins: { top: mm(18), bottom: mm(18), left: mm(16), right: mm(14), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Spectral', fontSize: pt(9.4), lineHeight: pt(LEAD),
    color: col('ink'), boldColor: col('ink'), 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 { markdown: next, map, anchors } = applyEdits(markdown, accepted, kept);
+notes.forEach((n, i) => { n.anchor = anchors[i].anchor; }); // write these back to the rows

致谢

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