# Aplicar els canvis acceptats i portar-hi les altres notes

> applyEdits escriu al Markdown les correccions acceptades i hi porta l'àncora de cada nota, marcant les notes on ha caigut un canvi.

- Versió HTML: https://postext.dev/ca/cookbook/applying-accepted-edits
- Recepta Núm. 218 · Integració amb CMS · Nivell 3 (Avançat) · Sortides: Canvas, Controls en viu
- Gèneres: Revistes i fanzins
- Requereix postext ≥ 1.103.0 · provada amb 1.103.1 el 2026-12-04
- Pàgines: [1](https://postext.dev/cookbook/applying-accepted-edits/es/p01.webp?v=8242b702), [2](https://postext.dev/cookbook/applying-accepted-edits/es/p02.webp?v=8242b702)
- ![L'esborrany i el text després d'applyEdits, l'un al costat de l'altre: tres canvis aplicats (verd), un de rebutjat i encara obert (gris), i la nota 2 marcada 2? perquè un canvi va caure dins les seves paraules.](https://postext.dev/cookbook/applying-accepted-edits/es/s01.webp?v=8242b702)
- Última actualització: 2026-12-04
- Altres idiomes: [en](https://postext.dev/en/cookbook/applying-accepted-edits.md), [es](https://postext.dev/es/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), [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)

## En poques paraules

Un article de revista amb quatre correccions proposades i tres notes d'una editora. S'accepten tres correccions i s'escriuen al text. Les notes es mouen amb les seves paraules, i la que ha vist canviar les seves queda marcada per tornar-hi.

## Què compondràs

Un reportatge de *Cuaderno de campo del hielo*, una pàgina de revista de 130 × 190 mm, mostrat dues vegades. A l'esquerra, l'esborrany amb quatre canvis proposats dibuixats com a signes de correcció i tres notes numerades de l'editora. A la dreta, el text després d'escriure al Markdown els tres canvis acceptats i compondre'l de nou: les paraules noves tenyides de verd, les notes mogudes amb les seves paraules, la supressió rebutjada encara oberta en gris i la nota 2 marcada en ambre, perquè un canvi acceptat va alterar les paraules on era.

**Aquesta recepta respon a:**

- Com aplico al Markdown els canvis acceptats i desplaço amb ells les altres notes?

## La resposta curta

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

## Ingredients

**Ensenya**

- [Àncores que sobreviuen a les revisions](https://postext.dev/ca/docs/integration-anchors.md#àncores-i-edicions): textAnchor desa un rang amb la seva cita i el seu context, de manera que resolveAnchor el torna a trobar en un text revisat; applyEdits escriu els canvis acceptats i mapOffset trasllada les altres posicions.
- [Marques d'anotació](https://postext.dev/ca/docs/integration-marks.md#marques-danotació): Ressaltats, subratllats, ratllats, substitucions, insercions, notes i requadres col·locats sobre el text de les pàgines, pintats en un canvas o escrits com a SVG sobre imatges de pàgina.

**També fa servir**

- [Visor de pàgines (postext-viewer)](https://postext.dev/ca/docs/integration-viewer.md#el-visor-de-pàgines)
- [Pàgines en un canvas](https://postext.dev/ca/docs/configuration-programmatic-usage.md#renderitzar-una-pàgina-en-un-mapa-de-bits)
- [Fonts abans de compondre](https://postext.dev/ca/docs/configuration-programmatic-usage.md#carregar-les-fonts-abans-de-compondre)
- [Capçaleres i folis](https://postext.dev/ca/docs/configuration-headers-footers.md#capçaleres-i-peus)
- [Marges simètrics](https://postext.dev/ca/docs/configuration-page-layout.md#marges-simètrics)
- [Paleta de color semàntica](https://postext.dev/ca/docs/configuration-fonts-colors-viewers.md#paleta-de-colors)
- [Capçaleres segons el tipus de pàgina](https://postext.dev/ca/docs/configuration-headers-footers.md#elements-de-text)

**La configuració d'un cop d'ull**

- [`bodyText`](https://postext.dev/ca/docs/configuration-text.md#text-de-cos), [`colorPalette`](https://postext.dev/ca/docs/configuration-fonts-colors-viewers.md#paleta-de-colors), [`footer`](https://postext.dev/ca/docs/configuration-headers-footers.md#capçaleres-i-peus), [`header`](https://postext.dev/ca/docs/configuration-headers-footers.md#capçaleres-i-peus), [`headings`](https://postext.dev/ca/docs/configuration-headings.md#encapçalaments), [`layout`](https://postext.dev/ca/docs/configuration-page-layout.md#disposició), [`locale`](https://postext.dev/ca/docs/configuration-language.md#partició-de-mots), [`page`](https://postext.dev/ca/docs/configuration-page-layout.md#pàgina)

**API**

- `annotations`, `applyEdits`, [`buildDocumentWithFonts`](https://postext.dev/ca/docs/configuration-programmatic-usage.md#carregar-les-fonts-abans-de-compondre), `createViewer`, `mapOffset`, [`renderPageToCanvas`](https://postext.dev/ca/docs/configuration-programmatic-usage.md#renderitzar-una-pàgina-en-un-mapa-de-bits), `textAnchor`

**Tipus de lletra**

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

## Elaboració

### 1 · Desa propostes i notes com a àncores

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

El pen col·loca cada registre sobre l'esborrany per les seves paraules, com un CMS els llegiria de les seves taules. Una proposta es converteix en un canvi, `{ start, end, text }`: amb els extrems iguals insereix, amb el text buit suprimeix. Una nota desa un `textAnchor`, el seu rang amb les paraules i una mica de context.

### 2 · Aplica els canvis acceptats d'un sol cop

El codi és [la resposta curta](https://postext.dev/ca/cookbook/applying-accepted-edits.md#la-resposta-curta) de més amunt. `applyEdits` rep tots els canvis en posicions de l'esborrany, en qualsevol ordre, així que el lloc web mai no ha de desplaçar un canvi per un altre. Retorna el Markdown nou, un `map` per a qualsevol altra posició i cada àncora portada a través dels canvis: desplaçada el que van afegir o treure els canvis anteriors, i `touched` quan un canvi hi va caure a dins. No cal cercar, així que una àncora portada així no pot quedar ambigua. `mapOffset` amb `'before'` col·loca cada text nou on ara comença.

### 3 · Explica què vol dir cada color

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

Una nota tocada porta un signe d'interrogació a la bandera i un altre color. Si la nota encara val per a «puede duplicarse» ho decideix l'editora; Postext només avisa que les paraules han canviat. Dos canvis que se superposen llancen un `RangeError`, perquè dues correccions a les mateixes paraules necessiten que algú triï.

## La recepta completa

Els fitxers d'aquí sota es componen a partir de la carpeta de la recepta, amb el text d'exemple i el kit comú del Receptari ja inclosos. Per executar-los com una sola pàgina, posa l'HTML a `<body>`, el CSS en un element `<style>` i l'script en un `<script type="module">`; o enganxa cadascun al tauler corresponent d'un pen nou de CodePen (el JS com a mòdul). L'script importa postext des d'esm.sh, així que no cal instal·lar ni compilar res.

- Carpeta de la recepta: 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 = 'es'; // @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: "Cuaderno de campo del hielo"
author: "Ingrid Solberg"
---

# Cómo se mueve un glaciar

Un glaciar parece tan quieto como la roca que lo rodea, pero está siempre en movimiento. La nieve que cae en su cuenca alta queda enterrada por la del invierno siguiente, se aprieta en granos que se llaman neviza y al cabo de unas décadas se convierte en hielo azul y denso. Ese hielo fluye cuesta abajo, demasiado despacio para que nadie lo vea, pero lo bastante rápido para que una estaca clavada en la superficie esté en otro sitio un mes después.

## El hielo que se dobla

El hielo es quebradizo en la cubitera y en la capa de arriba de un glaciar, donde se raja en grietas. Más abajo, bajo el peso del hielo que tiene encima, se comporta de otro modo. Cuando un glaciar alcanza unos 50 metros de espesor, los cristales cercanos al lecho empiezan a deslizarse por sus propias capas internas, y el hielo se deforma como un líquido muy rígido. La superficie avanza más deprisa y el lecho más despacio, y el centro del glaciar va más rápido que los bordes, donde las paredes del valle lo frenan.

## El hielo que resbala

En el lecho hay un segundo movimiento. Donde la base del glaciar está en el punto de fusión, una película fina de agua separa el hielo de la roca, y el glaciar entero resbala sobre ella. En verano, el agua de deshielo de la superficie baja por grietas y por pozos que se llaman molinos, y sube la presión del agua en el lecho. En algunos glaciares alpinos la velocidad se duplica durante unos días después de un periodo de calor, y luego baja cuando los canales bajo el hielo se abren y se llevan el agua.

## Medir el flujo

Las primeras mediciones se hicieron con filas de estacas a través del hielo, medidas año tras año desde puntos fijos en las laderas del valle. Hoy los satélites comparan dos imágenes de radar tomadas con pocos días de diferencia y trazan el movimiento de toda la superficie a la vez. Un glaciar de valle típico de los Alpes avanza entre 30 y 200 metros al año. Los glaciares de desagüe más rápidos de Groenlandia han llegado a más de 40 metros al día.

## Por qué retrocede el frente

El hielo sigue fluyendo aunque el glaciar mengüe. Su frente retrocede cuando cada verano se funde allí más hielo del que el flujo trae desde arriba. Un glaciar puede, por tanto, avanzar y perder terreno a la vez, como quien baja por una escalera mecánica que sube un poco más deprisa.

El agua de deshielo cuenta lo mismo. Un torrente que sale de un glaciar en retroceso lleva más agua en un agosto caluroso que hace un siglo, porque desagua hielo que no se repone. Su caudal crece durante décadas mientras el glaciar adelgaza, toca techo y luego decae a medida que se acaba el hielo que lo alimenta. Varios valles de los Alpes ya han pasado ese techo.
`; // 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 ───────────────────────────────────────────────────────────────────────
```

## Variants

### Desa les àncores portades

El lloc web escriu cada àncora portada a la seva fila, perquè la revisió següent parteixi del text nou.

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

- Recepta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Tipus de lletra: Spectral (OFL-1.1), Karla (OFL-1.1)
- Codi: MIT · Contingut d'exemple: CC-BY-4.0

## Relacionades

- [Núm. 214 · Marques de correcció: ratllar, substituir i inserir](https://postext.dev/ca/cookbook/proofreading-marks-on-pages.md): Les correccions d'un editor sobre una pàgina de conte a postext-viewer: paraules ratllades, substitucions escrites a sobre i signes d'inserció. · Nivell 2 (Intermedi) · Narrativa, teatre i prosa literària
- [Núm. 215 · Notes al marge, amb una finestra col·locada des de la pàgina](https://postext.dev/ca/cookbook/margin-notes-with-popovers.md): Les notes tenyeixen les paraules i les assenyalen al marge; en prémer-les, s'obren en una finestra col·locada sota les paraules amb rangeRects i pageToClient. · Nivell 2 (Intermedi) · Catàlegs
- [Núm. 223 · Un subratllador per al lector: un passatge i un color](https://postext.dev/ca/cookbook/reader-highlighter.md): En seleccionar paraules d'una novel·la s'obren quatre colors; el subratllat s'ajusta a paraules senceres, es desa com a ancoratge i entra en una llista. · Nivell 2 (Intermedi) · Narrativa, teatre i prosa literària
