かんたんな説明
雑誌の記事に、4つの修正案と編集者のメモが3つ付いています。修正のうち3つを承認してテキストに書き込みます。メモはそれぞれの語句と一緒に移り、語句が変わったメモには見直しの印が付きます。
できあがり
Field Notes on Ice の記事を 130 × 190 mm の雑誌ページに組み、2回表示します。左は下書きで、4つの修正案が校正記号として描かれ、編集者の番号付きメモが3つあります。右は承認した3つの変更を Markdown に書き込み、組み直したあとのテキストです。新しい語句は緑で、メモはそれぞれの語句と一緒に移り、却下した削除は灰色のまま残り、メモ2は承認した変更がその語句を変えたので琥珀色の印が付きます。
このレシピが答える質問
- 承認した変更をMarkdownに反映し、ほかのメモもそれに合わせて移すには?
手短な答え
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 · 修正案とメモをアンカーとして持つ
// 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)) }));
ペンは各レコードを語句で下書きの上に置きます。CMS が自分のテーブルから読むのと同じです。修正案は { start, end, text } の変更になります。両端が同じなら挿入、テキストが空なら削除です。メモは textAnchor、つまり範囲と語句と少しの文脈を持ちます。
#2 · 承認した変更を1回の呼び出しで反映する
コードは上の手短な答えです。applyEdits はすべての変更を下書きの位置のまま、順不同で受け取ります。サイト側がほかの変更に合わせて位置をずらす必要はありません。返ってくるのは新しい Markdown、ほかの位置を変換する map、そして変更をくぐって移った各アンカーです。前にある変更が足したり削ったりした分だけずれ、内側に変更が入ったものは touched になります。検索をしないので、こうして移ったアンカーがあいまいになることはありません。mapOffset に 'before' を渡すと、新しい各テキストが今どこから始まるかがわかります。
#3 · 色の意味を示す
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 になります。同じ語句への2つの修正は、人が選ぶ必要があるからです。
レシピの全体
// ═══ 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 },
<main id="pages">
<section>
<header><h2></h2><p></p></header>
<div id="before" class="pane"></div>
</section>
<section>
<header><h2></h2><p></p></header>
<div id="after" class="pane"></div>
</section>
</main>
/* The host's frame: the draft and the new text side by side, each viewer under a legend. */
main#pages {
display: grid; grid-template-columns: 1fr 1fr; height: max(560px, calc(100vh - 44px));
gap: 0; padding: 0; justify-items: stretch;
}
#pages section { display: flex; flex-direction: column; min-height: 0; min-width: 0; }
#pages section + section { border-left: 1px solid #23262d; }
#pages header { padding: 12px 16px 10px; background: #15181d; border-bottom: 1px solid #23262d; }
#pages h2 { margin: 0; font: 600 13px/1.3 system-ui, sans-serif; letter-spacing: .08em;
text-transform: uppercase; color: #f4f1ea; }
#pages header p { margin: 4px 0 0; font: 13px/1.4 system-ui, sans-serif; color: #a9aeb8; }
.pane { flex: 1; min-height: 0; }
.pane .postext-viewer { --pv-background: #0e1014; --pv-focus: #e0a43a; }
組み立てた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)



