本文へスキップ
レシピ番号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行

かんたんな説明

編集者がハイキングガイドの下書きに5つのメモを残し、その後で著者が一部を書き直しました。ページは新しいテキストから各メモの語句を探します。元の場所にあるもの、移ったもの、3か所に当てはまるもの、消えたものがあります。見つかったメモは新しいページに描かれます。

できあがり

Walks from the Valley Station というガイドブックの1コースを、135 × 200 mm のページに組みます。編集者が最初の下書きに5つのメモを残し、その後で著者が1文を足し、1文を書き直し、1文を削りました。ペンは改稿後のテキストから各メモを探し、結果を2か所に示します。右の一覧は各メモの状態です。元の場所に1つ、移動が2つ、3つの踏み越し段のどれとも取れるあいまいなものが1つ、孤立が1つ。左のページには残ったメモが余白の番号とともに載り、あいまいなメモが指しうる3か所が囲まれます。

このレシピが答える質問

  • テキストを改稿しても、コメントを元の箇所に付けたままにするには?

手短な答え

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 ではメモを書いたときに保存します。このペンは単独で動くように、下書きの上でアンカーを作っています。

#2 · 新しいテキストで各アンカーを探す

コードは上の手短な答えです。resolveAnchor はまず保存した位置を確かめ、次に語句を文脈全体ごとファイルのどこかで探し、さらに文脈を短くし、最後に語句だけで探して、答えが出た最初の段階で止まります。2か所のどちらかを選ぶことはしません。「the stile」へのメモは文が書き直されて文脈を失い、語句だけでは3つの踏み越し段に当てはまるので、答えは3つの候補を持つ 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 }));

クレジット

レシピ
Ignacio Ferro
本文
書き下ろしの文章, CC BY 4.0
フォント
Newsreader (SIL OFL 1.1) · Archivo (SIL OFL 1.1)