# 校正記号：削除・置換・挿入

> 編集者の赤字を postext-viewer で組んだ小説のページに描く。削除線、上に書いた差し替え、挿入の記号を Markdown の範囲から置く。

- HTML版: https://postext.dev/ja/cookbook/proofreading-marks-on-pages
- レシピ No. 214 · CMSへの組み込み · 難易度 2 (中級) · 出力: Canvas
- ジャンル: 小説・戯曲・文芸
- 必要なもの postext ≥ 1.103.0 · テスト環境 1.103.1 ／テスト日 2026-12-04
- ページ: [1](https://postext.dev/cookbook/proofreading-marks-on-pages/en/p01.webp?v=3d63c734)
- ![初校のページ上に五つの訂正を描いたもの：消した語、行の上に書いた差し替え、挿入記号。それぞれ横の一覧に名前が出る。](https://postext.dev/cookbook/proofreading-marks-on-pages/en/s01.webp?v=3d63c734)
- ![一覧で最後の訂正を選んだところ：「the dark」の前に「in」を入れる指示で、行間に挿入記号がある。](https://postext.dev/cookbook/proofreading-marks-on-pages/en/s02.webp?v=3d63c734)
- 最終更新: 2026-12-04
- 他の言語: [en](https://postext.dev/en/cookbook/proofreading-marks-on-pages.md), [es](https://postext.dev/es/cookbook/proofreading-marks-on-pages.md), [ca](https://postext.dev/ca/cookbook/proofreading-marks-on-pages.md), [de](https://postext.dev/de/cookbook/proofreading-marks-on-pages.md), [el](https://postext.dev/el/cookbook/proofreading-marks-on-pages.md), [fr](https://postext.dev/fr/cookbook/proofreading-marks-on-pages.md), [it](https://postext.dev/it/cookbook/proofreading-marks-on-pages.md), [pt](https://postext.dev/pt/cookbook/proofreading-marks-on-pages.md), [ru](https://postext.dev/ru/cookbook/proofreading-marks-on-pages.md), [zh](https://postext.dev/zh/cookbook/proofreading-marks-on-pages.md), [ar](https://postext.dev/ar/cookbook/proofreading-marks-on-pages.md)

## かんたんな説明

短編小説の1ページ目に編集者の赤字を入れ、校正ツールのように表示します。消した語、古い語の上に書いた新しい語、語が抜けているところの小さな記号です。横のリストが各修正を並べます。

## できあがり

短編小説 *Platform Two* の冒頭ページに、原稿整理者が初校で入れた赤字を描きます。重複した語と余分な *very* は赤い線で消してあり、*lain* と *recieved* は消したうえで正しい語をすぐ上の小さなラベルに書いてあります。行の下の緑の記号は *in* が抜けている場所を示します。右のリストには同じ五つの修正が並び、それぞれ今の語句と差し替える語句を示します。ページ上の印を押すか、Tab キーで移って Enter を押すと、その項目が選ばれます。

**このレシピが答える問い:**

- 組版したページの上に、削除・置換・挿入の校正記号を表示するには？

## 手短な答え

```js
// script.js, 行 107–116
const view = createViewer(document.getElementById('viewer'), {
  document: doc, markdown, zoom: 'fit-width', labels: L.viewer,
  annotations: edits, // strike, replace (text over the struck words) and insert (a caret)
});
const entries = new Map(edits.map((e) => [e.id, entry(e)]));
const pick = (id) => {
  for (const [key, li] of entries) li.classList.toggle('active', key === id);
};
view.on('annotationclick', ({ id }) => pick(id)); // pointer, Enter or Space
pick('e2');
```

## 材料

**学べること**

- [注釈の印](https://postext.dev/ja/docs/integration-marks.md#注釈のマーク): ハイライト、下線、取り消し線、置換、挿入、メモ、囲みを、ページのテキストに合わせて配置し、canvasに描くか、ページ画像に重ねるSVGとして書き出します。

**ほかに使うもの**

- [ページビューアー（postext-viewer）](https://postext.dev/ja/docs/integration-viewer.md#ページビューアー)
- [レイアウト前のフォント読み込み](https://postext.dev/ja/docs/configuration-programmatic-usage.md#レイアウトの前にフォントを読み込む)

**設定の一覧**

- [`bodyText`](https://postext.dev/ja/docs/configuration-text.md#本文), [`colorPalette`](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット), [`footer`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`header`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`headings`](https://postext.dev/ja/docs/configuration-headings.md#見出し), [`layout`](https://postext.dev/ja/docs/configuration-page-layout.md#レイアウト), [`locale`](https://postext.dev/ja/docs/configuration-language.md#ハイフネーション), [`page`](https://postext.dev/ja/docs/configuration-page-layout.md#ページ)

**API**

- `annotations`, [`buildDocumentWithFonts`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#レイアウトの前にフォントを読み込む), `createViewer`, [`renderPageToCanvas`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#ページをビットマップに描画する)

**書体**

- Libre Caslon Text (OFL-1.1)

## 作り方

### 1 · 行の間に余白を取る

```js
// script.js, 行 30–51
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(130), height: mm(200), dpi: 150,
    margins: { top: mm(22), bottom: mm(24), left: mm(18), right: mm(18) } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Libre Caslon Text', fontSize: pt(10), lineHeight: pt(16),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'justify', firstLineIndent: mm(5), indentAfterHeading: false,
    hyphenation: { enabled: true }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: 'Libre Caslon Text', color: col('accent'), fontWeight: 400, levels: [
    { level: 1, fontSize: pt(22), lineHeight: pt(28), italic: true,
      marginTop: pt(16), marginBottom: pt(24) },
  ] },
  header: { elements: [] },
  footer: { elements: [
    { kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Libre Caslon Text',
      fontSize: pt(9), color: col('accent'), align: 'center',
      placement: { anchor: { to: 'page', edge: 'bottom-center' }, offset: { y: mm(-12) } } },
  ] },
};
```

置換と挿入のラベルは本文の 0.62 em の大きさで、直す行のすぐ上、行間に立ちます。10 pt の文字に 16 pt の行送りなら余裕があり、ラベルが上の行を隠す部分はわずかです。行送りが詰まっていても、ラベルには紙の色の下地が敷かれるので両方とも読めます。

### 2 · 各修正を範囲として保存する

```js
// script.js, 行 81–95
// [kind, a quote that finds the place, the words marked in it, the new text]
// A tool stores the offsets; the pen finds them from quotes so that both editions run.
const edits = t({
  en: [['strike', 'for for forty', 'for '], ['replace', 'had lain her', 'lain', 'laid'],
    ['strike', 'the very last', 'very '], ['replace', 'had recieved a', 'recieved', 'received'],
    ['insert', 'nothing the dark', 'the dark', 'in ']],
  es: [['replace', 'habían dos faroles', 'habían', 'había'],
    ['replace', 'había recivido', 'recivido', 'recibido'], ['insert', 'segura que', 'que', 'de '],
    ['strike', 'todo el el valle', 'el '], ['strike', 'subió arriba', ' arriba']],
}).map(([kind, quote, words, text], i) => {
  const start = markdown.indexOf(quote) + quote.indexOf(words);
  // An insertion marks a point: the range is empty, before the words that follow it.
  const end = kind === 'insert' ? start : start + words.length;
  return { id: `e${i + 1}`, kind, range: { start, end }, text };
});
```

削除と置換は変える語句に印を付け、置換はさらに新しい `text` を持ちます。挿入は一点を示すので範囲は空（`start === end`）で、記号はそのオフセットの行の下に付きます。修正を受け入れるときに `applyEdits` が受け取るのも、これと同じ記録です。

### 3 · 描いて、押されたことを聞く

コードは上の[手短な答え](https://postext.dev/ja/cookbook/proofreading-marks-on-pages.md#手短な答え)です。ビューアーは各行の向きに沿って印を置くので、削除線は文字の中ほどを横切り、置換は語句の上に立ちます。右から左のページや縦組のページでも同じです。`annotationclick` はポインターで押したときにも、印の上で Enter や Space を押したときにも出ます。各印は「Replacement: laid」という名前のキーボード用ボタンだからです。

## レシピの全体

下のファイルはレシピのフォルダーから合成したもので、サンプルのテキストとレシピ集の共通キットを埋め込んであります。1つのページとして動かすには、HTMLを`<body>`に、CSSを`<style>`要素に、スクリプトを`<script type="module">`に入れます。新しいCodePenのpenの各パネルに貼り付けてもかまいません（JSはモジュールとして）。スクリプトはesm.shからpostextを読み込むので、インストールもビルドも要りません。

- レシピのフォルダー: https://github.com/drnachio/postext/tree/main/cookbook/proofreading-marks-on-pages

### index.html

```html
<main id="pages">
  <div id="viewer"></div>
  <aside id="panel">
    <h2 id="heading"></h2>
    <ol id="edits"></ol>
  </aside>
</main>
```

### style.css

```css
/* The host's frame: the viewer on the left, the list of corrections on the right.
   The viewer fills its container, so the container gets a height. */
main#pages {
  display: grid; grid-template-columns: minmax(0, 1fr) 320px; height: max(560px, 100vh);
  justify-items: stretch; gap: 0; padding: 0;
}
#viewer { min-height: 0; }
#viewer .postext-viewer { --pv-background: #e7e4ec; --pv-focus: #5b4a8a; }
#panel {
  overflow: auto; padding: 20px 18px; background: #fbfafc; border-left: 1px solid #d3cfdb;
  font: 15px/1.4 system-ui, sans-serif; color: #1d1b19;
}
#panel h2 { margin: 0 0 12px; font-size: 18px; }
#edits { display: grid; gap: 8px; margin: 0; padding: 0; list-style: none; }
#edits button {
  display: block; width: 100%; min-height: 44px; padding: 9px 12px; text-align: left;
  background: #fff; border: 1px solid #dcd8e3; border-radius: 6px;
  font: inherit; color: inherit; cursor: pointer;
}
#edits button:focus-visible { outline: 2px solid #5b4a8a; outline-offset: 2px; }
#edits li.active button { border-color: #5b4a8a; box-shadow: inset 4px 0 0 #5b4a8a; }
#edits b {
  display: block; font-size: 12px; letter-spacing: .05em; text-transform: uppercase;
  color: #5e5a66;
}
#edits del { color: #b3261e; }
#edits ins { color: #17733f; text-decoration: none; font-weight: 600; }
#edits del:empty, #edits ins:empty { display: none; }
```

### script.js

```js
// ═══ Postext Cookbook · Nº 214 · Proofreading marks: strike, replace and insert ══════
// https://postext.dev/en/cookbook/proofreading-marks-on-pages
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Libre Caslon Text (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// The first page of a short story with an editor's corrections drawn on it, as a proofing
// tool shows them: struck words, a replacement written over the words it replaces, and a
// caret where a word goes in. The list beside the page is the same corrections; pressing a
// mark, with the pointer or the keyboard, picks its entry.
import { buildDocumentWithFonts, renderPageToCanvas } from 'https://esm.sh/postext';
import { createViewer } from 'https://esm.sh/postext-viewer';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'proofreading-marks-on-pages';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#1d1b19', // text
  accent: '#5b4a8a', // a dusk violet: the story's title and the folios
};
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 short-story page with generous leading, room for the marks between lines
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(130), height: mm(200), dpi: 150,
    margins: { top: mm(22), bottom: mm(24), left: mm(18), right: mm(18) } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Libre Caslon Text', fontSize: pt(10), lineHeight: pt(16),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'justify', firstLineIndent: mm(5), indentAfterHeading: false,
    hyphenation: { enabled: true }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: 'Libre Caslon Text', color: col('accent'), fontWeight: 400, levels: [
    { level: 1, fontSize: pt(22), lineHeight: pt(28), italic: true,
      marginTop: pt(16), marginBottom: pt(24) },
  ] },
  header: { elements: [] },
  footer: { elements: [
    { kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Libre Caslon Text',
      fontSize: pt(9), color: col('accent'), align: 'center',
      placement: { anchor: { to: 'page', edge: 'bottom-center' }, offset: { y: mm(-12) } } },
  ] },
};
// #endregion

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "Night Service"
author: "Ruth Calder"
---

# Platform Two

The station at Kilbrae had one platform, one bench and one porter, and by half past eleven only the porter was still awake. Nell sat on the bench with her case between her feet and watched the signal at the end of the line, which had shown red for for forty minutes. She had lain her ticket on the bench beside her, as if someone might come and ask to see it.

The porter came out of his hut with a lamp. He said the very last train had been held at Dunmore, where a cow had got onto the line, and that he had recieved a telephone call to say so. He did not say when it would come. Nell thanked him. She could see nothing the dark beyond the signal, only the line of the hills against a sky that was a shade lighter than they were.

At ten to midnight the signal dropped to green with a clank that carried down the whole valley. The porter put down his tea. Somewhere to the south a whistle sounded, thin and far off, and then the rails began to hum under the platform, a sound Nell felt in her shoes before she heard it.

She picked up her case. She did not pick up the ticket, and she did not notice it until the train was moving, when she saw it through the window, a pale square on the dark bench, and the porter walking towards it with his lamp.
`; // content.<lang>.md, inlined by the Cookbook

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = {
  'Libre Caslon Text': ['400', '400i'],
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown }, config, kitFonts(FONTS));
kitStatus(t({ en: 'Night Service · first proof', es: 'Servicio nocturno · primeras pruebas' }));

// #region corrections: the editor's corrections, as a proofing tool stores them
// [kind, a quote that finds the place, the words marked in it, the new text]
// A tool stores the offsets; the pen finds them from quotes so that both editions run.
const edits = t({
  en: [['strike', 'for for forty', 'for '], ['replace', 'had lain her', 'lain', 'laid'],
    ['strike', 'the very last', 'very '], ['replace', 'had recieved a', 'recieved', 'received'],
    ['insert', 'nothing the dark', 'the dark', 'in ']],
  es: [['replace', 'habían dos faroles', 'habían', 'había'],
    ['replace', 'había recivido', 'recivido', 'recibido'], ['insert', 'segura que', 'que', 'de '],
    ['strike', 'todo el el valle', 'el '], ['strike', 'subió arriba', ' arriba']],
}).map(([kind, quote, words, text], i) => {
  const start = markdown.indexOf(quote) + quote.indexOf(words);
  // An insertion marks a point: the range is empty, before the words that follow it.
  const end = kind === 'insert' ? start : start + words.length;
  return { id: `e${i + 1}`, kind, range: { start, end }, text };
});
// #endregion

const L = t({
  en: { title: 'Corrections', strike: 'Delete', replace: 'Replace', insert: 'Insert',
    viewer: {} },
  es: { title: 'Correcciones', strike: 'Suprimir', replace: 'Sustituir', insert: 'Insertar',
    viewer: { viewer: 'Páginas del cuento', page: 'Página {n} de {count}',
      kinds: { strike: 'Supresión', replace: 'Sustitución', insert: 'Inserción' } } },
});

// #region answer: the corrections drawn on the page, and a press on one picks its entry
const view = createViewer(document.getElementById('viewer'), {
  document: doc, markdown, zoom: 'fit-width', labels: L.viewer,
  annotations: edits, // strike, replace (text over the struck words) and insert (a caret)
});
const entries = new Map(edits.map((e) => [e.id, entry(e)]));
const pick = (id) => {
  for (const [key, li] of entries) li.classList.toggle('active', key === id);
};
view.on('annotationclick', ({ id }) => pick(id)); // pointer, Enter or Space
pick('e2');
// #endregion

// One row of the list: the kind, the words as they stand and what replaces them.
function entry({ id, kind, range, text }) {
  const li = document.createElement('li');
  li.innerHTML = '<button type="button"><b></b> <del></del> <ins></ins></button>';
  li.querySelector('b').textContent = L[kind];
  li.querySelector('del').textContent = markdown.slice(range.start, range.end).trim();
  li.querySelector('ins').textContent = text?.trim() ?? '';
  li.firstChild.addEventListener('click', () => { pick(id); view.revealAnnotation(id); });
  document.getElementById('edits').append(li);
  return li;
}
document.getElementById('heading').textContent = L.title;

// The states the Cookbook photographs: the last correction picked from the list.
kitShots({ last: () => { pick('e5'); view.revealAnnotation('e5'); } });

// ─── Kit ── helpers shared by every Cookbook recipe · postext.dev/cookbook ─────

// ─── Kit · core v1 ── the same in every recipe · postext.dev/cookbook
function mm(value) { return { value, unit: 'mm' }; }
function pt(value) { return { value, unit: 'pt' }; }
function em(value) { return { value, unit: 'em' }; }
/** The sample language's string: t({ en: 'Figure', es: 'Figura' }). */
function t(strings) { return strings[LANG] ?? Object.values(strings)[0]; }
/** A file in this recipe's assets folder, served from the Postext repo by jsDelivr. */
function asset(file) { return `https://cdn.jsdelivr.net/gh/drnachio/postext@main/cookbook/${RECIPE}/assets/${file}`; }

// ─── Kit · fonts v3 ── the same in every recipe · postext.dev/cookbook
// Postext loads the faces a config asks for before layout and asks the kit
// for Fontsource's files, the ones the PDF embeds too.

/** buildDocumentWithFonts' options: the resolver, and FONTS' faces loaded
 *  with the config's. FONTS = { 'Family Name': ['400', '400i', '700'] }. */
function kitFonts(FONTS = {}) {
  const faces = Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) =>
    ({ family, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' })));
  return { resolve: fontsourceResolver, faces };
}

/** A face's files with their ranges: latin, then latin-ext and greek when
 *  `text` needs them (kitSubsetsFor). Null for a face Fontsource lacks. */
async function fontsourceResolver(family, weight, style, { text = '' } = {}) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  if (meta && !(await fontsourceWeights(family, style)).includes(weight)) return null;
  kitStatus('Loading fonts…');
  const at = await fontsourceAt(id);
  return ['latin', ...kitSubsetsFor(text, meta)].map((subset) => ({
    source: `${at}files/${id}-${subset}-${weight}-${style}.woff2`,
    unicodeRange: kitRanges()[subset],
  }));
}

/** Each file's unicode-range (a function: the kit runs after the pen's code). */
function kitRanges() {
  return {
    latin: 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,'
      + 'U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD',
    'latin-ext': 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,'
      + 'U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF',
    greek: 'U+0370-03FF',
  };
}

/** For the cjk, arabic and comics blocks: loads `faces` (as FONTS) for the
 *  sample `text`; `optional` skips a face Fontsource lacks. Files are added in
 *  the order asked, the last winning a shared character. Resolves to the count. */
async function loadFonts(faces, text = '', { optional = false } = {}) {
  kitStatus('Loading fonts…');
  const ranges = kitRanges();
  const jobs = [];
  for (const [family, specs] of Object.entries(faces)) {
    const id = fontsourceId(family);
    const todo = [...new Set(specs)].map((spec) => [parseInt(spec, 10), spec.endsWith('i') ? 'italic' : 'normal'])
      .filter(([weight, style]) => !hasFace(family, weight, style)); // before any await
    const at = fontsourceAt(id);
    const meta = optional || /[^\0-ÿ]/u.test(text) ? await fontsourceMeta(family) : null;
    const subsets = ['latin', ...kitSubsetsFor(text, meta)];
    for (const [weight, style] of todo) {
      if (optional && !(meta && (await fontsourceWeights(family, style)).includes(weight))) continue;
      for (const subset of subsets) {
        const url = `${await at}files/${id}-${subset}-${weight}-${style}.woff2`;
        const face = new FontFace(family, `url(${url}) format('woff2')`,
          { weight: String(weight), style, unicodeRange: ranges[subset] });
        jobs.push(face.load().catch(() => {
          if (subset === 'latin' && !optional) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
        }));
      }
    }
  }
  const ready = await Promise.all(jobs).catch((error) => { kitFail(error); throw error; });
  return ready.filter((face) => face && document.fonts.add(face)).length;
}

/** A loaded FontFace covers this face (fonts.check() says yes to any family). */
function hasFace(family, weight, style) {
  for (const face of document.fonts) {
    if (face.status !== 'loaded' || face.style !== style) continue;
    if (face.family.replace(/^["']|["']$/g, '') !== family) continue;
    const [low, high = low] = face.weight.split(' ').map(Number);
    if (weight >= low && weight <= high) return true;
  }
  return false;
}

/** The files beyond latin `text` needs that `meta`'s family ships. */
function kitSubsetsFor(text, meta) {
  return [[/[Ā-˿ᴀ-ᶿḀ-ỿ†ℓⱠ-Ɀ꜠-ꟿ]/u, 'latin-ext'], [/[Ͱ-Ͽ]/u, 'greek']]
    .filter(([re, x]) => re.test(text) && meta?.subsets?.includes(x)).map(([, x]) => x);
}

/** Fontsource's id for a family: 'Source Serif 4' → 'source-serif-4'. */
function fontsourceId(family) { return family.toLowerCase().replace(/\s+/g, '-'); }

/** A package's folder at the one version @5 names now (#766). */
function fontsourceAt(id, u = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@`) {
  return (fontsourceAt.c ??= {})[id] ??= fetch(u + '5/package.json').then((r) => r.json())
    .then((p) => p.version || 5, () => 5).then((v) => `${u}${v}/`);
}

/** The family's Fontsource metadata (weights, styles, subsets), or null. */
function fontsourceMeta(family, id = fontsourceId(family)) {
  return (fontsourceMeta.c ??= {})[id] ??= fetch(`https://api.fontsource.org/v1/fonts/${id}`)
    .then((res) => (res.ok ? res.json() : null), () => null);
}

/** The weights the package ships in `style`: the API pairs none (no Libre
 *  Caslon 700 italic file), so italics are read from latin-italic.css. */
function fontsourceWeights(family, style, id = fontsourceId(family)) {
  return (fontsourceWeights.c ??= {})[id + style] ??= fontsourceMeta(family).then(async (m) => {
    if (!m?.styles.includes(style)) return m ? [] : [400, 700];
    const css = style === 'italic' ? await fetch(`${await fontsourceAt(id)}latin-italic.css`).then((r) => (r.ok ? r.text() : ''), () => '') : '';
    const w = [...css.matchAll(/weight: (\d+)/g)].map((x) => +x[1]);
    return w.length ? w : m.weights;
  });
}

// ─── Kit · viewer v2 ── the same in every recipe · postext.dev/cookbook
/** The pages as spreads on a dark desk, page 1 alone, then verso | recto,
 *  each painted when it scrolls near. Other options go to renderPageToCanvas. */
function showPages(docs, { title, width = 460, ...render } = {}) {
  const root = viewer(title);
  const pages = [docs].flat().flatMap((doc) =>
    doc.pages.map((page) => ({ doc, page, n: (doc.pageIndexOffset ?? 0) + page.index })));
  const spreads = [];
  let verso = null;
  for (const p of pages) {
    if (p.n % 2 === 1) { if (verso) spreads.push([verso, null]); verso = p; }
    else { spreads.push([verso, p]); verso = null; }
  }
  if (verso) spreads.push([verso, null]);
  const density = Math.min(window.devicePixelRatio || 1, 2);
  showPages.painter?.disconnect();
  const painter = new IntersectionObserver((entries) => {
    for (const { isIntersecting, target } of entries) {
      if (!isIntersecting) continue;
      painter.unobserve(target);
      const { doc, page } = target.postext;
      renderPageToCanvas(page, doc, target, { ...render, scale: (width * density) / page.width });
    }
  }, { rootMargin: '800px' });
  showPages.painter = painter;
  root.replaceChildren(...spreads.map((pair) => {
    const spread = document.createElement('div');
    spread.className = 'pt-spread';
    for (const p of pair) {
      const figure = document.createElement('figure');
      if (p) {
        const label = p.page.pageLabel || String(p.n + 1);
        const canvas = document.createElement('canvas');
        canvas.postext = p;
        canvas.style.aspectRatio = `${p.page.width} / ${p.page.height}`;
        canvas.setAttribute('role', 'img');
        canvas.setAttribute('aria-label', `Page ${label}`);
        const folio = document.createElement('figcaption');
        folio.textContent = label;
        figure.append(canvas, folio);
        painter.observe(canvas);
      } else figure.className = 'pt-blank';
      spread.append(figure);
    }
    return spread;
  }));
  kitStatus(`${pages.length} ${pages.length === 1 ? 'page' : 'pages'}`);
  document.documentElement.dataset.postext = 'ready';
  return pages.length;
}

/** The desk, the bar and the error reporting, created once. */
function viewer(title) {
  if (!document.getElementById('pt-kit')) {
    document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit">
      :root { color-scheme: dark; }
      body { margin: 0; background: #0e1014; color: #b9bcc4; font: 13px/1.45 system-ui, sans-serif; }
      #pt-bar { position: sticky; top: 0; z-index: 1; display: flex; flex-wrap: wrap; align-items: center;
        gap: 6px 16px; padding: 10px 16px; background: rgb(14 16 20 / .92); backdrop-filter: blur(6px);
        border-bottom: 1px solid #23262d; }
      #pt-bar strong { color: #f4f1ea; font-weight: 600; }
      #pt-actions { display: flex; gap: 12px; margin-left: auto; }
      #pt-actions a, #pt-actions button { color: #d8a21a; font: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
      #pages { display: grid; justify-items: center; gap: 48px; padding: 32px 16px 72px; }
      .pt-spread { display: flex; }
      .pt-spread figure { margin: 0; width: min(460px, 44vw); }
      .pt-spread canvas { display: block; width: 100%; background: #fff;
        box-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figure:first-child canvas { box-shadow: inset -14px 0 14px -14px rgb(0 0 0 / .18), 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figcaption { margin-top: 10px; text-align: center; font: 600 10px/1 system-ui, sans-serif;
        letter-spacing: .18em; text-transform: uppercase; color: #6c7079; }
      .pt-blank { visibility: hidden; }
      @media (max-width: 760px) {
        .pt-spread { flex-direction: column; gap: 32px; }
        .pt-spread figure { width: min(460px, 92vw); }
        .pt-blank { display: none; }
      }
    </style>`);
    document.body.insertAdjacentHTML('afterbegin',
      '<header id="pt-bar"><strong id="pt-title"></strong><span id="pt-status" role="status"></span><span id="pt-actions"></span></header>');
    document.getElementById('pt-title').textContent = document.title || 'Postext';
    addEventListener('error', (event) => kitFail(event.error ?? event.message));
    addEventListener('unhandledrejection', (event) => kitFail(event.reason));
  }
  if (title) document.getElementById('pt-title').textContent = title;
  return document.getElementById('pages')
    ?? document.body.appendChild(Object.assign(document.createElement('main'), { id: 'pages' }));
}

function kitStatus(text) {
  viewer();
  document.getElementById('pt-status').textContent = text;
}

function kitFail(error) {
  document.documentElement.dataset.postext = 'error';
  kitStatus(`Error: ${error?.message ?? error}`);
}

// ─── Kit · shots v1 ── developer recipes, photographed while they run
/** The states the Cookbook photographs the pen in, in order, after its first
 *  view: each an async function that puts the page in that state (a passage
 *  selected, a note open). The recipe page shows these pictures in place of
 *  the bare pages. Your own app leaves this call out. */
function kitShots(states) {
  window.__cbShots = states;
}

// ─── /Kit ───────────────────────────────────────────────────────────────────────
```

## アレンジ

### 修正をすべて受け入れる

`https://esm.sh/postext/annotate` から `applyEdits` を読み込み、修正を Markdown に書き込んで新しい組版を表示します。

```diff
 view.on('annotationclick', ({ id }) => pick(id)); // pointer, Enter or Space
+const { markdown: fixed } = applyEdits(markdown, edits.map((e) => ({ ...e.range, text: e.text ?? '' })));
+view.setDocument(await buildDocumentWithFonts({ markdown: fixed }, config, kitFonts(FONTS)), fixed);
+view.setAnnotations([]);
```

### ラベルを本の書体で組む

印が自分で組む文字は、指定がなければ `system-ui` です。

```diff
   document: doc, markdown, zoom: 'fit-width', labels: L.viewer,
+  marks: { fontFamily: 'Libre Caslon Text' },
```

## クレジット

- レシピ: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- 書体: Libre Caslon Text (OFL-1.1)
- コード: MIT · サンプルの内容: CC-BY-4.0

## 関連レシピ

- [No. 218 · 承認した変更を反映し、ほかのメモも一緒に移す](https://postext.dev/ja/cookbook/applying-accepted-edits.md): applyEdits で承認した修正を Markdown に書き込み、ほかのメモのアンカーも一緒に移す。修正が内側に入ったメモには印が付く。 · 難易度 3 (上級) · 雑誌とジン
- [No. 220 · ページ画像に重ねる SVG の注釈：報告書のために](https://postext.dev/ja/cookbook/marks-as-svg-over-pages.md): layoutAnnotations と annotationsSvg で、校正者の印をビューアーなしでページ画像に重ねる。CMS がメールで送ったり印刷したりできる校正報告書。 · 難易度 2 (中級) · 新聞とニュースレター
- [No. 223 · 読者のための蛍光ペン：一節に一色](https://postext.dev/ja/cookbook/reader-highlighter.md): 小説のページで語句を選ぶと四つの色が開く。ハイライトは語の単位にそろえ、アンカーとして保存し、ページ横の一覧に加える。 · 難易度 2 (中級) · 小説・戯曲・文芸
