# Appliquer les corrections acceptées, notes comprises

> applyEdits écrit les corrections acceptées dans le Markdown et y emporte l'ancre de chaque autre note, en signalant les notes où une correction est tombée.

- Version HTML: https://postext.dev/fr/cookbook/applying-accepted-edits
- Recette Nº 218 · Intégration dans un CMS · Niveau 3 (Avancé) · Sorties: Canvas, Contrôles en direct
- Genres: Magazines et fanzines
- Nécessite postext ≥ 1.103.0 · testée avec 1.103.1 le 2026-12-04
- Pages: [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)
- ![Le brouillon et le texte après applyEdits côte à côte : trois corrections appliquées (vert), une refusée et toujours ouverte (gris), et la note 2 signalée 2? parce qu'une correction est tombée dans ses mots.](https://postext.dev/cookbook/applying-accepted-edits/en/s01.webp?v=ac54d47a)
- Dernière mise à jour: 2026-12-04
- Autres langues: [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), [de](https://postext.dev/de/cookbook/applying-accepted-edits.md), [el](https://postext.dev/el/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)

## En bref

Un article de magazine avec quatre corrections proposées et trois notes d'une éditrice. Trois corrections sont acceptées et écrites dans le texte. Les notes suivent leurs mots, et celle dont les mots ont changé est signalée pour être relue.

## Ce que vous allez composer

Un article de *Field Notes on Ice*, une page de magazine de 130 × 190 mm, montré deux fois. À gauche, le brouillon avec quatre corrections proposées dessinées en signes de correction et trois notes numérotées de l'éditrice. À droite, le texte après que les trois corrections acceptées ont été écrites dans le Markdown et remises en page : les nouveaux mots teintés de vert, les notes déplacées avec leurs mots, la suppression refusée encore ouverte en gris et la note 2 signalée en ambre, parce qu'une correction acceptée a changé les mots sur lesquels elle portait.

**Cette recette répond à:**

- Comment appliquer au Markdown les modifications acceptées et déplacer les autres notes avec elles ?

## La réponse courte

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

## Ingrédients

**Enseigne**

- [Ancres à travers les révisions](https://postext.dev/fr/docs/integration-anchors.md#ancres-et-modifications): textAnchor conserve une plage avec sa citation et son contexte, pour que resolveAnchor la retrouve dans un texte révisé ; applyEdits écrit les changements acceptés et mapOffset reporte les autres positions.
- [Marques d’annotation](https://postext.dev/fr/docs/integration-marks.md#marques-dannotation): Surlignages, soulignements, biffures, remplacements, insertions, notes et cadres placés sur le texte des pages, peints sur un canvas ou écrits en SVG par-dessus des images de pages.

**Utilise aussi**

- [Visionneuse de pages (postext-viewer)](https://postext.dev/fr/docs/integration-viewer.md#la-visionneuse-de-pages)
- [Pages sur un canvas](https://postext.dev/fr/docs/configuration-programmatic-usage.md#rendre-une-page-en-bitmap)
- [Les polices avant la mise en page](https://postext.dev/fr/docs/configuration-programmatic-usage.md#charger-les-polices-avant-la-mise-en-page)
- [Titres courants et folios](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page)
- [Marges en miroir](https://postext.dev/fr/docs/configuration-page-layout.md#marges-en-miroir)
- [Palette de couleurs sémantique](https://postext.dev/fr/docs/configuration-fonts-colors-viewers.md#palette-de-couleurs)
- [Titres courants selon le rôle de la page](https://postext.dev/fr/docs/configuration-headers-footers.md#éléments-de-texte)

**La configuration en un coup d’œil**

- [`bodyText`](https://postext.dev/fr/docs/configuration-text.md#texte-courant), [`colorPalette`](https://postext.dev/fr/docs/configuration-fonts-colors-viewers.md#palette-de-couleurs), [`footer`](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page), [`header`](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page), [`headings`](https://postext.dev/fr/docs/configuration-headings.md#titres), [`layout`](https://postext.dev/fr/docs/configuration-page-layout.md#mise-en-page), [`locale`](https://postext.dev/fr/docs/configuration-language.md#césure), [`page`](https://postext.dev/fr/docs/configuration-page-layout.md#page)

**API**

- `annotations`, `applyEdits`, [`buildDocumentWithFonts`](https://postext.dev/fr/docs/configuration-programmatic-usage.md#charger-les-polices-avant-la-mise-en-page), `createViewer`, `mapOffset`, [`renderPageToCanvas`](https://postext.dev/fr/docs/configuration-programmatic-usage.md#rendre-une-page-en-bitmap), `textAnchor`

**Caractères**

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

## Préparation

### 1 · Garder propositions et notes comme ancres

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

Le pen place chaque enregistrement sur le brouillon par ses mots, comme un CMS les lirait dans ses tables. Une proposition devient une correction `{ start, end, text }` : des bornes égales insèrent, un texte vide supprime. Une note garde un `textAnchor`, son étendue avec les mots et un peu de contexte.

### 2 · Appliquer les corrections acceptées en un appel

Le code est [la réponse courte](https://postext.dev/fr/cookbook/applying-accepted-edits.md#la-réponse-courte) plus haut. `applyEdits` prend toutes les corrections en positions du brouillon, dans n'importe quel ordre : le site n'a jamais à décaler une correction d'après une autre. Il renvoie le nouveau Markdown, une `map` pour toute autre position et chaque ancre emportée à travers les corrections : décalée de ce que les corrections précédentes ont ajouté ou retiré, et `touched` quand une correction est tombée dedans. Aucune recherche n'est nécessaire, donc une ancre ainsi emportée ne peut pas devenir ambiguë. `mapOffset` avec `'before'` place chaque nouveau texte là où il commence désormais.

### 3 · Dire ce que signifient les couleurs

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

Une note touchée reçoit un point d'interrogation dans son fanion et une autre couleur. C'est à l'éditrice de dire si la note vaut encore pour « can double » ; Postext signale seulement que les mots ont changé. Des corrections qui se chevauchent lèvent une `RangeError`, car deux corrections des mêmes mots demandent que quelqu'un choisisse.

## La recette complète

Les fichiers ci-dessous sont composés à partir du dossier de la recette, avec le texte d’exemple et le kit commun des Recettes déjà inclus. Pour les exécuter comme une seule page, placez le HTML dans `<body>`, le CSS dans un élément `<style>` et le script dans un `<script type="module">` ; ou collez chacun dans le panneau correspondant d’un nouveau pen CodePen (le JS en tant que module). Le script importe postext depuis esm.sh : il n’y a rien à installer ni à compiler.

- Dossier de la recette: 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 ───────────────────────────────────────────────────────────────────────
```

## Variantes

### Enregistrer les ancres emportées

Le site réécrit chaque ancre emportée dans sa ligne, pour que la révision suivante parte du nouveau texte.

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

## Crédits

- Recette: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Caractères: Spectral (OFL-1.1), Karla (OFL-1.1)
- Code: MIT · Contenu d’exemple: CC-BY-4.0

## Recettes liées

- [Nº 214 · Signes de correction : barrer, remplacer et insérer](https://postext.dev/fr/cookbook/proofreading-marks-on-pages.md): Les corrections d'un éditeur sur une page de nouvelle dans postext-viewer : mots barrés, remplacements écrits au-dessus et signes d'insertion. · Niveau 2 (Intermédiaire) · Fiction, théâtre et prose littéraire
- [Nº 215 · Notes en marge, avec une bulle placée depuis la page](https://postext.dev/fr/cookbook/margin-notes-with-popovers.md): Les notes teintent leurs mots et les signalent dans la marge ; un clic ouvre la note dans une bulle placée sous les mots avec rangeRects et pageToClient. · Niveau 2 (Intermédiaire) · Catalogues
- [Nº 223 · Un surligneur pour le lecteur : un passage, une couleur](https://postext.dev/fr/cookbook/reader-highlighter.md): On sélectionne des mots d'un roman et quatre couleurs s'ouvrent ; le surlignage s'étend aux mots entiers, s'enregistre comme ancre et rejoint une liste. · Niveau 2 (Intermédiaire) · Fiction, théâtre et prose littéraire
