# Angenommene Änderungen anwenden und die Notizen mitnehmen

> applyEdits schreibt die angenommenen Korrekturen ins Markdown und trägt den Anker jeder anderen Notiz mit; Notizen, in die eine Änderung fiel, werden markiert.

- HTML-Fassung: https://postext.dev/de/cookbook/applying-accepted-edits
- Rezept Nº 218 · CMS-Integration · Stufe 3 (Fortgeschritten) · Ausgaben: Canvas, Live-Steuerung
- Gattungen: Magazine und Zines
- Benötigt postext ≥ 1.103.0 · getestet mit 1.103.1 am 2026-12-04
- Seiten: [1](https://postext.dev/cookbook/applying-accepted-edits/en/p01.webp?v=ac54d47a), [2](https://postext.dev/cookbook/applying-accepted-edits/en/p02.webp?v=ac54d47a)
- ![Der Entwurf und der Text nach applyEdits nebeneinander: drei Änderungen übernommen (grün), eine abgelehnt und noch offen (grau), und Notiz 2 mit 2? markiert, weil eine Änderung in ihre Wörter fiel.](https://postext.dev/cookbook/applying-accepted-edits/en/s01.webp?v=ac54d47a)
- Zuletzt aktualisiert: 2026-12-04
- Andere Sprachen: [en](https://postext.dev/en/cookbook/applying-accepted-edits.md), [es](https://postext.dev/es/cookbook/applying-accepted-edits.md), [ca](https://postext.dev/ca/cookbook/applying-accepted-edits.md), [el](https://postext.dev/el/cookbook/applying-accepted-edits.md), [fr](https://postext.dev/fr/cookbook/applying-accepted-edits.md), [it](https://postext.dev/it/cookbook/applying-accepted-edits.md), [pt](https://postext.dev/pt/cookbook/applying-accepted-edits.md), [ru](https://postext.dev/ru/cookbook/applying-accepted-edits.md), [zh](https://postext.dev/zh/cookbook/applying-accepted-edits.md), [ja](https://postext.dev/ja/cookbook/applying-accepted-edits.md), [ar](https://postext.dev/ar/cookbook/applying-accepted-edits.md)

## Kurz gesagt

Ein Zeitschriftenartikel mit vier vorgeschlagenen Korrekturen und drei Notizen einer Lektorin. Drei Korrekturen werden angenommen und in den Text geschrieben. Die Notizen wandern mit ihren Wörtern, die mit geänderten Wörtern wird markiert.

## Was Sie setzen

Ein Beitrag aus *Field Notes on Ice*, eine Zeitschriftenseite von 130 × 190 mm, zweimal gezeigt. Links der Entwurf mit vier vorgeschlagenen Änderungen als Korrekturzeichen und drei nummerierten Notizen der Lektorin. Rechts der Text, nachdem die drei angenommenen Änderungen ins Markdown geschrieben und neu gesetzt wurden: die neuen Wörter grün getönt, die Notizen mit ihren Wörtern gewandert, die abgelehnte Streichung weiter offen in Grau und Notiz 2 bernsteinfarben markiert, weil eine angenommene Änderung ihre Wörter verändert hat.

**Dieses Rezept beantwortet:**

- Wie übernehme ich angenommene Änderungen ins Markdown und verschiebe die übrigen Notizen mit?

## Die kurze Antwort

```js
// script.js, Zeilen 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);
```

## Zutaten

**Zeigt**

- [Anker über Überarbeitungen hinweg](https://postext.dev/de/docs/integration-anchors.md#anker-und-änderungen): textAnchor hält einen Bereich mit seinem Zitat und seinem Kontext fest, damit resolveAnchor ihn in einem überarbeiteten Text wiederfindet; applyEdits schreibt angenommene Änderungen, mapOffset trägt die übrigen Stellen mit.
- [Anmerkungszeichen](https://postext.dev/de/docs/integration-marks.md#anmerkungszeichen): Hervorhebungen, Unterstreichungen, Streichungen, Ersetzungen, Einfügungen, Notizen und Rahmen, auf den Text der Seiten gelegt, auf ein Canvas gemalt oder als SVG über Seitenbilder geschrieben.

**Verwendet außerdem**

- [Seitenbetrachter (postext-viewer)](https://postext.dev/de/docs/integration-viewer.md#der-seitenbetrachter)
- [Seiten auf einem Canvas](https://postext.dev/de/docs/configuration-programmatic-usage.md#eine-seite-als-bitmap-rendern)
- [Schriften vor dem Layout](https://postext.dev/de/docs/configuration-programmatic-usage.md#schriften-vor-dem-layout-laden)
- [Kolumnentitel und Seitenzahlen](https://postext.dev/de/docs/configuration-headers-footers.md#kopf--und-fußzeilen)
- [Gespiegelte Ränder](https://postext.dev/de/docs/configuration-page-layout.md#gespiegelte-ränder)
- [Semantische Farbpalette](https://postext.dev/de/docs/configuration-fonts-colors-viewers.md#farbpalette)
- [Kopfzeilen nach Seitenrolle](https://postext.dev/de/docs/configuration-headers-footers.md#textelemente)

**Die Konfiguration auf einen Blick**

- [`bodyText`](https://postext.dev/de/docs/configuration-text.md#fließtext), [`colorPalette`](https://postext.dev/de/docs/configuration-fonts-colors-viewers.md#farbpalette), [`footer`](https://postext.dev/de/docs/configuration-headers-footers.md#kopf--und-fußzeilen), [`header`](https://postext.dev/de/docs/configuration-headers-footers.md#kopf--und-fußzeilen), [`headings`](https://postext.dev/de/docs/configuration-headings.md#überschriften), [`layout`](https://postext.dev/de/docs/configuration-page-layout.md#layout), [`locale`](https://postext.dev/de/docs/configuration-language.md#silbentrennung), [`page`](https://postext.dev/de/docs/configuration-page-layout.md#seite)

**APIs**

- `annotations`, `applyEdits`, [`buildDocumentWithFonts`](https://postext.dev/de/docs/configuration-programmatic-usage.md#schriften-vor-dem-layout-laden), `createViewer`, `mapOffset`, [`renderPageToCanvas`](https://postext.dev/de/docs/configuration-programmatic-usage.md#eine-seite-als-bitmap-rendern), `textAnchor`

**Schriften**

- Spectral (OFL-1.1), Karla (OFL-1.1)

## Zubereitung

### 1 · Vorschläge und Notizen als Anker halten

```js
// script.js, Zeilen 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)) }));
```

Der Pen setzt jeden Datensatz über seine Wörter auf den Entwurf, so wie ein CMS ihn aus seinen Tabellen liest. Ein Vorschlag wird zur Änderung `{ start, end, text }`: gleiche Enden fügen ein, ein leerer Text streicht. Eine Notiz behält einen `textAnchor`, ihren Bereich mit den Wörtern und etwas Kontext.

### 2 · Die angenommenen Änderungen in einem Aufruf anwenden

Der Code steht in [der kurzen Antwort](https://postext.dev/de/cookbook/applying-accepted-edits.md#die-kurze-antwort) oben. `applyEdits` nimmt alle Änderungen in Positionen des Entwurfs, in beliebiger Reihenfolge, die Website muss also nie eine Änderung um eine andere verschieben. Zurück kommen das neue Markdown, eine `map` für jede andere Position und jeder Anker durch die Änderungen getragen: verschoben um das, was die Änderungen davor hinzufügten oder entfernten, und `touched`, wenn eine Änderung in ihn fiel. Eine Suche ist nicht nötig, ein so getragener Anker kann also nicht mehrdeutig werden. `mapOffset` mit `'before'` setzt jeden neuen Text dorthin, wo er jetzt beginnt.

### 3 · Sagen, was die Farben bedeuten

```js
// script.js, Zeilen 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;
}
```

Eine berührte Notiz bekommt ein Fragezeichen im Fähnchen und eine andere Farbe. Ob die Notiz noch zu „can double“ passt, entscheidet die Lektorin; Postext meldet nur, dass sich die Wörter geändert haben. Überlappende Änderungen werfen einen `RangeError`, denn zwei Korrekturen an denselben Wörtern braucht jemanden, der wählt.

## Das ganze Rezept

Die folgenden Dateien sind aus dem Ordner des Rezepts zusammengesetzt, mit dem Beispieltext und dem gemeinsamen Baukasten der Rezepte bereits eingebettet. Um sie als eine Seite auszuführen, setzen Sie das HTML in `<body>`, das CSS in ein `<style>`-Element und das Skript in ein `<script type="module">`; oder fügen Sie jede Datei in das passende Feld eines neuen CodePen-Pens ein (JS als Modul). Das Skript importiert postext von esm.sh, es gibt also nichts zu installieren oder zu bauen.

- Quellordner: https://github.com/drnachio/postext/tree/main/cookbook/applying-accepted-edits

### index.html

```html
<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>
```

### style.css

```css
/* 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

```js
// ═══ 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 },
  headings: { fontFamily: 'Karla', color: col('accent'), fontWeight: 700, levels: [
    { level: 1, fontFamily: 'Spectral', fontWeight: 600, fontSize: pt(21), lineHeight: pt(25),
      marginTop: mm(12), marginBottom: pt(LEAD) },
    { level: 2, fontSize: pt(8.5), lineHeight: pt(LEAD), letterSpacing: pt(0.5),
      textTransform: 'uppercase', marginTop: pt(LEAD), marginBottom: pt(0) },
  ] },
  header: { elements: [
    head('verso-folio', '{pageNumber}', 'even', 'top-left', 14, folio),
    head('verso-title', '{title}', 'even', 'top-left', 21),
    head('recto-chapter', '{chapterTitle}', 'odd', 'top-right', -21),
    head('recto-folio', '{pageNumber}', 'odd', 'top-right', -14, folio),
  ] },
  footer: { elements: [] },
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "Field Notes on Ice"
author: "Ingrid Solberg"
---

# How a glacier moves

A glacier looks as still as the rock around it, but it is always on the move. Snow that falls on its upper basin is buried by the next winter’s snow, pressed into grains called firn, and after some decades turned into dense blue ice. That ice flows downhill, too slowly for anyone to see, but fast enough that a stake hammered into the surface stands somewhere else a month later.

## Ice that bends

Ice is brittle in a freezer tray and in the top layer of a glacier, where it cracks into crevasses. Deeper down, under the weight of the ice above, it behaves differently. Once a glacier is about 50 metres thick, the crystals near its bed start to slip along their own internal layers, and the ice deforms like a very stiff liquid. The surface moves fastest and the bed slowest, and the middle of the glacier moves faster than its edges, where the valley walls hold it back.

## Ice that slides

A second motion happens at the bed. Where the base of the glacier is at the melting point, a thin film of water lies between ice and rock, and the whole glacier slides on it. In summer, meltwater from the surface drains down through cracks and through shafts called moulins, and raises the water pressure at the bed. On some Alpine glaciers the speed doubles for a few days after warm weather, then falls back when the channels under the ice open up and carry the water away.

## Measuring the flow

The first measurements were made with lines of stakes across the ice, surveyed year after year from fixed points on the valley sides. Today satellites compare two radar images taken a few days apart and map the movement of the whole surface at once. A typical valley glacier in the Alps moves between 30 and 200 metres a year. The fastest outlet glaciers of Greenland have been measured at more than 40 metres a day.

## Why the front retreats

The ice keeps flowing even while a glacier shrinks. Its front retreats when more ice melts there each summer than the flow brings down from above. A glacier can therefore move forward and lose ground at the same time, like a person walking down an escalator that runs upward a little faster.

The meltwater tells the same story. A stream that leaves a retreating glacier carries more water in a hot August than it did a century ago, because it drains ice that is not being replaced. Its flow rises for decades as the glacier thins, peaks, and then falls away as the ice that feeds it runs out. Several valleys in the Alps have already passed that peak.
`; // content.<lang>.md, the draft

// #region records: the host's suggestions and notes, each kept as an anchor on the draft
// 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)) }));
// #endregion

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = {
  Spectral: ['400', '600'],
  Karla: ['500', '700'],
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const before = await buildDocumentWithFonts({ markdown }, config, kitFonts(FONTS));
kitStatus(t({ en: 'Three edits accepted, the notes carried', es: 'Tres cambios aceptados' }));

const GREY = '#8a8f98';
const suggestion = (e, id) => ({ id, range: e, color: e.accepted ? undefined : GREY,
  ...(e.start === e.end ? { kind: 'insert', text: e.text }
    : e.text ? { kind: 'replace', text: e.text } : { kind: 'strike' }) });
const openPages = (id, doc, md, annotations) => createViewer(document.getElementById(id), {
  document: doc, markdown: md, annotations, zoom: 'fit-width', maxZoom: 1.2, gap: 18,
  marks: { fontFamily: 'Karla' },
  labels: t({ en: {}, es: { page: 'Página {n} de {count}', kinds: { note: 'Nota',
    replace: 'Sustitución', insert: 'Inserción', strike: 'Supresión',
    highlight: 'Cambio aplicado' } } }) });
openPages('before', before, markdown, [...edits.map((e, i) => suggestion(e, `e${i}`)),
  ...notes.map((n, i) => ({ id: `n${i}`, kind: 'note', range: n.anchor, label: `${i + 1}` }))]);

// #region answer: write the accepted edits and carry everything else through them
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);
// #endregion

// #region legends: what each column shows, in the edition's language
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;
}
// #endregion

// ─── 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 ───────────────────────────────────────────────────────────────────────
```

## Varianten

### Die getragenen Anker speichern

Die Website schreibt jeden getragenen Anker in seine Zeile zurück, damit die nächste Fassung vom neuen Text ausgeht.

```diff
 const { markdown: next, map, anchors } = applyEdits(markdown, accepted, kept);
+notes.forEach((n, i) => { n.anchor = anchors[i].anchor; }); // write these back to the rows
```

## Nachweise

- Rezept: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Schrift: Spectral (OFL-1.1), Karla (OFL-1.1)
- Code: MIT · Beispielinhalt: CC-BY-4.0

## Verwandte Rezepte

- [Nº 214 · Korrekturzeichen: streichen, ersetzen und einfügen](https://postext.dev/de/cookbook/proofreading-marks-on-pages.md): Die Korrekturen eines Lektors auf einer gesetzten Erzählungsseite in postext-viewer: gestrichene Wörter, darübergeschriebener Ersatz und Einfügezeichen. · Stufe 2 (Mittel) · Belletristik, Drama und Prosa
- [Nº 215 · Randnotizen, mit einem Popover aus Seitenkoordinaten](https://postext.dev/de/cookbook/margin-notes-with-popovers.md): Notizmarken tönen ihre Wörter und setzen eine Fahne an den Rand; ein Klick öffnet die Notiz in einem Popover unter den Wörtern, gesetzt mit pageToClient. · Stufe 2 (Mittel) · Kataloge
- [Nº 223 · Ein Textmarker für Leser: eine Passage, eine Farbe](https://postext.dev/de/cookbook/reader-highlighter.md): Wer Wörter eines Romans auswählt, bekommt vier Farben; die Markierung rastet an ganzen Wörtern ein, wird als Anker gespeichert und landet in einer Liste. · Stufe 2 (Mittel) · Belletristik, Drama und Prosa
