# Àncores després d'una revisió: mogudes, ambigües o òrfenes

> textAnchor desa cada nota amb les seves paraules i el context; resolveAnchor la cerca a la revisió següent: al seu lloc, moguda, ambigua o òrfena.

- Versió HTML: https://postext.dev/ca/cookbook/anchors-through-a-revision
- Recepta Núm. 217 · Integració amb CMS · Nivell 2 (Intermedi) · Sortides: Canvas, Controls en viu
- Gèneres: Manuals, guies i obres de consulta
- Requereix postext ≥ 1.103.0 · provada amb 1.103.1 el 2026-12-04
- Pàgines: [1](https://postext.dev/cookbook/anchors-through-a-revision/es/p01.webp?v=112a97be), [2](https://postext.dev/cookbook/anchors-through-a-revision/es/p02.webp?v=112a97be)
- ![Cinc notes fetes sobre l'esborrany, buscades a la revisió: al seu lloc (verd), moguda (ambre), ambigua, amb un requadre a cada candidat (morat), i una òrfena, perquè les seves paraules ja no hi són.](https://postext.dev/cookbook/anchors-through-a-revision/es/s01.webp?v=112a97be)
- Última actualització: 2026-12-04
- Altres idiomes: [en](https://postext.dev/en/cookbook/anchors-through-a-revision.md), [es](https://postext.dev/es/cookbook/anchors-through-a-revision.md), [de](https://postext.dev/de/cookbook/anchors-through-a-revision.md), [el](https://postext.dev/el/cookbook/anchors-through-a-revision.md), [fr](https://postext.dev/fr/cookbook/anchors-through-a-revision.md), [it](https://postext.dev/it/cookbook/anchors-through-a-revision.md), [pt](https://postext.dev/pt/cookbook/anchors-through-a-revision.md), [ru](https://postext.dev/ru/cookbook/anchors-through-a-revision.md), [zh](https://postext.dev/zh/cookbook/anchors-through-a-revision.md), [ja](https://postext.dev/ja/cookbook/anchors-through-a-revision.md), [ar](https://postext.dev/ar/cookbook/anchors-through-a-revision.md)

## En poques paraules

Una editora va deixar cinc notes a l'esborrany d'una guia de passejades i l'autor el va retocar. La pàgina cerca les paraules de cada nota al text nou. Unes són on eren, d'altres s'han mogut, una encaixa en tres i una ja no hi és.

## Què compondràs

Una passejada de *Paseos desde la estación del valle*, una guia en pàgina de 135 × 200 mm. Una editora va deixar cinc notes al primer esborrany; després l'autor hi va afegir una frase, en va reescriure una altra i en va treure una tercera. El pen cerca cada nota al text revisat i mostra la resposta en dos llocs. La llista de la dreta dona a cada nota el seu estat: una al seu lloc, dues mogudes, una ambigua entre tres escales i una òrfena. Les pàgines de l'esquerra porten les notes que sobreviuen, numerades al marge, i requadren els tres llocs als quals es podria referir l'ambigua.

**Aquesta recepta respon a:**

- Com mantinc els comentaris units al seu passatge quan es revisa el text?

## La resposta curta

```js
// script.js, línies 163–179
const COLOR = { exact: '#1f7a45', moved: '#b0640a', ambiguous: '#7b4cc4' };
const found = NOTES.map((note) => resolveAnchor(markdown, note.anchor));
const marks = NOTES.flatMap((note, i) => {
  const at = found[i];
  const label = String(i + 1);
  // In place or moved: one range, the note's mark with its number in the margin.
  if (at.status === 'exact' || at.status === 'moved') {
    return [{ id: note.id, kind: 'note', range: at, label, color: COLOR[at.status] }];
  }
  // Ambiguous: every place the words fit, boxed, for a person to choose.
  if (at.status === 'ambiguous') {
    return at.candidates.map((range, k) => ({ id: `${note.id}.${k}`, kind: 'box', range,
      color: COLOR.ambiguous }));
  }
  return []; // orphaned: the words are gone, the note stays in the thread
});
view.setAnnotations(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.

**També fa servir**

- [Marques d'anotació](https://postext.dev/ca/docs/integration-marks.md#marques-danotació)
- [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**

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

**Tipus de lletra**

- Newsreader (OFL-1.1), Archivo (OFL-1.1)

## Elaboració

### 1 · Desa una àncora, no una posició

```js
// script.js, línies 121–144
// [the words to find in the draft, the words noted, the note]. A CMS reads the anchors from
// its database; here they are made on the draft so the pen runs on its own.
const NOTES = t({
  en: [
    ['follow the wall up the field', 'the wall', 'Rebuilt last winter: does it reach the top?'],
    ['a cairn that walkers have built', 'a cairn', 'A photograph of the cairn would help here.'],
    ['Cross the stile at', 'the stile', 'Which way does this stile face?'],
    ['the bog on either side is deeper', 'the bog on either side is deeper',
      'Rangers say knee-deep at most. Too alarming?'],
    ['The stepping stones at the ford', 'The stepping stones', 'Give the detour in minutes.'],
  ],
  es: [
    ['sigue el muro prado arriba', 'el muro', '¿Lo rehicieron este invierno? ¿Sigue hasta arriba?'],
    ['un hito de piedras que los caminantes', 'un hito de piedras', 'Aquí iría bien una foto.'],
    ['Salta la escalera del', 'la escalera', '¿Hacia dónde da esta escalera?'],
    ['la turbera de los lados es más honda', 'la turbera de los lados es más honda',
      'Los guardas dicen que no pasa de la rodilla.'],
    ['Las piedras del vado resbalan', 'Las piedras del vado', 'Da el rodeo en minutos.'],
  ],
}).map(([around, words, body], i) => {
  const start = earlier.indexOf(around) + around.indexOf(words);
  const anchor = textAnchor(earlier, { start, end: start + words.length }); // 32 chars a side
  return { id: `n${i + 1}`, body, anchor };
});
```

`textAnchor` desa el rang, les paraules que cobria i 32 caràcters a cada costat. És JSON i prou, pensat per a una fila de la base de dades al costat de la nota. Un CMS la desa quan s'escriu la nota; el pen crea les àncores sobre l'esborrany per funcionar pel seu compte.

### 2 · Cerca cada àncora al text nou

El codi és [la resposta curta](https://postext.dev/ca/cookbook/anchors-through-a-revision.md#la-resposta-curta) de més amunt. `resolveAnchor` prova primer les posicions desades, després les paraules amb tot el context a qualsevol lloc del fitxer, després amb menys context i finalment les paraules soles, i s'atura al primer pas que dona una resposta. Mai no tria entre dos llocs: la nota sobre «la escalera» va perdre el context quan es va reescriure la frase, i les paraules soles encaixen en tres escales, així que la resposta és `ambiguous` amb els tres candidats. Què cal dibuixar per a cada estat ho decideix el lloc web.

### 3 · Explica què li ha passat a cada nota

```js
// script.js, línies 183–211
const STATUS = t({
  en: { exact: 'In place', moved: 'Moved', ambiguous: 'Ambiguous', orphaned: 'Orphaned' },
  es: { exact: 'En su sitio', moved: 'Movida', ambiguous: 'Ambigua', orphaned: 'Huérfana' },
});
const detail = (note, at) => ({
  exact: () => `${at.start}`,
  moved: () => `${note.anchor.start} → ${at.start}`,
  ambiguous: () => at.candidates.map((c) => c.start).join(' · '),
  orphaned: () => t({ en: 'the words are gone', es: 'las palabras ya no están' }),
})[at.status]();
document.getElementById('notes').replaceChildren(...NOTES.map((note, i) => {
  const at = found[i];
  const li = document.createElement('li');
  li.className = at.status;
  li.innerHTML = '<button type="button"><b></b><span class="status"></span><q></q>'
    + '<span class="body"></span><small></small></button>';
  const [n, status, quote, body, small] = li.querySelectorAll('b, .status, q, .body, small');
  n.textContent = String(i + 1);
  status.textContent = STATUS[at.status];
  quote.textContent = note.anchor.text;
  body.textContent = note.body;
  small.textContent = detail(note, at);
  const id = at.status === 'ambiguous' ? `${note.id}.0` : note.id;
  li.firstChild.addEventListener('click', () => view.revealAnnotation(id, { behavior: 'smooth' }));
  li.firstChild.disabled = at.status === 'orphaned';
  return li;
}));
document.getElementById('title').textContent = t({ en: 'Notes on the draft',
  es: 'Notas del borrador' });
```

Una nota moguda ensenya la posició antiga i la nova; una ambigua, els candidats; l'òrfena conserva les paraules ratllades perquè l'editora sàpiga de què tractava. Quan es prem una nota, el visor es desplaça a la seva marca amb `revealAnnotation`.

## 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/anchors-through-a-revision

### index.html

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

### style.css

```css
/* The host's frame: the revised pages on the left, the notes on the right. */
main#pages {
  display: grid; grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr);
  height: max(560px, calc(100vh - 44px)); gap: 0; padding: 0; justify-items: stretch;
}
#viewer { min-height: 0; }
#viewer .postext-viewer { --pv-background: #0e1014; --pv-focus: #e0a43a; }
#panel { min-height: 0; overflow: auto; background: #15181d; border-left: 1px solid #23262d;
  font: 14px/1.45 system-ui, sans-serif; color: #c9ccd3; }
#panel h2 { margin: 0; padding: 16px 18px 10px; font: 600 13px/1.3 system-ui, sans-serif;
  letter-spacing: .08em; text-transform: uppercase; color: #f4f1ea; }
#notes { list-style: none; margin: 0; padding: 0 12px 24px; display: grid; gap: 10px; }
#notes button { display: grid; grid-template-columns: 2em 1fr auto; gap: 2px 8px; width: 100%;
  min-height: 44px; padding: 10px 12px; text-align: left; font: inherit; color: inherit;
  background: #1c2027; border: 1px solid #2c313a; border-left: 4px solid var(--c);
  border-radius: 6px; cursor: pointer; }
#notes button:disabled { cursor: default; opacity: .8; }
#notes button:focus-visible { outline: 2px solid #e0a43a; outline-offset: 2px; }
#notes li { --c: #6c7079; }
#notes .exact { --c: #3fb070; }
#notes .moved { --c: #e0913a; }
#notes .ambiguous { --c: #a77de8; }
#notes b { grid-row: span 3; color: var(--c); font-size: 16px; }
#notes .status { grid-column: 3; grid-row: 1; font-size: 12px; font-weight: 600; color: var(--c);
  text-transform: uppercase; letter-spacing: .06em; }
#notes q { grid-column: 2; grid-row: 1; color: #f4f1ea; font-style: italic; }
#notes .body { grid-column: 2 / 4; }
#notes small { grid-column: 2 / 4; color: #8a909b; font-variant-numeric: tabular-nums; }
#notes .orphaned q { text-decoration: line-through; color: #9aa0aa; }
```

### script.js

```js
// ═══ Postext Cookbook · Nº 217 · Anchors through a revision ═══════════════════════════
// https://postext.dev/en/cookbook/anchors-through-a-revision
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Newsreader, Archivo (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// An editor left five notes on the first draft of a walking guide; the author then revised the
// text. Each note was stored as an anchor (its words and some context), and each is looked for
// in the new revision: found in place, moved, ambiguous between several places, or orphaned.
// The notes that survive are drawn on the new pages, the others wait in the list for a person.
import { buildDocumentWithFonts, renderPageToCanvas } from 'https://esm.sh/postext';
import { textAnchor, resolveAnchor } 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 = 'anchors-through-a-revision';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#202421', // text
  accent: '#3d6b45', // moorland green: headings, folios
  muted: '#6b7068', // 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.6; // pt of body leading

const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'Archivo', fontSize: pt(7), fontWeight: 500, letterSpacing: pt(0.8),
  textTransform: 'uppercase', color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(10) } }, ...extra });
const folio = { fontWeight: 600, color: col('accent') };

const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(135), height: mm(200), dpi: 150,
    margins: { top: mm(19), bottom: mm(20), left: mm(17), right: mm(15), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Newsreader', fontSize: pt(10), lineHeight: pt(LEAD),
    color: col('ink'), boldColor: col('accent'), 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: 'Archivo', color: col('ink'), fontWeight: 600, levels: [
    { level: 1, fontSize: pt(20), lineHeight: pt(24), color: col('accent'),
      marginTop: mm(14), marginBottom: pt(LEAD) },
    { level: 2, fontSize: pt(9), lineHeight: pt(LEAD), letterSpacing: pt(0.4),
      marginTop: pt(LEAD), marginBottom: pt(0) },
  ] },
  header: { elements: [
    head('verso-folio', '{pageNumber}', 'even', 'top-left', 15, folio),
    head('verso-title', '{title}', 'even', 'top-left', 22),
    head('recto-chapter', '{chapterTitle}', 'odd', 'top-right', -22),
    head('recto-folio', '{pageNumber}', 'odd', 'top-right', -15, folio),
  ] },
  footer: { elements: [] },
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "Paseos desde la estación del valle"
author: "Ruth Ellery"
---

# El cordal de Wenlow y el acebal

**11 km · 380 m de subida · unas cuatro horas.** El paseo sale del aparcamiento de la estación del valle, donde un panel marca la ruta en verde. Cruza la carretera y toma el camino que sube junto a la ermita. A los diez minutos el camino acaba en una portilla; pásala y sigue el muro prado arriba hasta la escalera de la esquina de arriba.

## Subida al cordal

Pasada la escalera, la senda se empina y sube en zetas entre helechos. A finales de verano los helechos son más altos que un niño, así que lleva a los pequeños cerca. Desde aquí hasta el collado no hay cobertura de móvil. La senda sale al cordal abierto junto a un hito de piedras que los caminantes han ido levantando durante muchos años. Desde aquí se ve todo el valle, con el embalse al norte y la línea del tren a lo largo del río.

Gira a la izquierda por el cordal. El suelo es turba, blanda después de llover, y en los peores tramos han puesto losas de piedra. Con niebla, las losas son además la guía más segura por lo alto, y llevan derechas al collado.

## El acebal

A los tres kilómetros el cordal baja a un collado donde cuatro sendas se juntan en un poste indicador. Toma la que señala el acebal, un bosque de acebos y robles viejos en la ladera de abajo. En el borde del bosque, salta la escalera y sigue el arroyo cuesta abajo bajo los árboles. Las piedras del vado resbalan cuando baja mucha agua; hay una pasarela 200 m río arriba.

## Vuelta a la estación

El arroyo lleva a una pista de la granja. Gira a la derecha, pasa la granja y sus perros, y salva la última escalera para salir al camino. La cafetería de la estación abre hasta las cinco, y el último tren valle abajo sale a las 18:40.

## Más corto y más largo

Con niños pequeños, deja el cordal: el camino de la ermita sube derecho al collado en cuarenta minutos, y el paseo se queda en 6 km. Quien vaya más fuerte puede seguir por el cordal más allá del collado hasta el vértice geodésico de Hollin Knowe, 2 km más allá, y bajar por su loma norte hasta la presa del embalse. Desde la presa, una pista llana vuelve a la estación por la antigua vía del tren, lo que suma 5 km y una hora y media más o menos. Una tarde de invierno, mira la hora en el collado: bajo el cordal la luz se va pronto, y en el bosque oscurece mucho antes que en el camino.
`; // the revised text: content.<lang>.md
const earlier = String.raw`---
title: "Paseos desde la estación del valle"
author: "Ruth Ellery"
---

# El cordal de Wenlow y el acebal

**11 km · 380 m de subida · unas cuatro horas.** El paseo sale del aparcamiento de la estación del valle, donde un panel marca la ruta en verde. Cruza la carretera y toma el camino que sube junto a la ermita. A los diez minutos el camino acaba en una portilla; pásala y sigue el muro prado arriba hasta la escalera de la esquina de arriba.

## Subida al cordal

Pasada la escalera, la senda se empina y sube en zetas entre helechos. A finales de verano los helechos son más altos que un niño, así que lleva a los pequeños cerca. La senda sale al cordal abierto junto a un hito de piedras que los caminantes han ido levantando durante muchos años. Desde aquí se ve todo el valle, con el embalse al norte y la línea del tren a lo largo del río.

Gira a la izquierda por el cordal. El suelo es turba, blanda después de llover, y en los peores tramos han puesto losas de piedra. No te salgas de las losas: la turbera de los lados es más honda de lo que parece. Con niebla, las losas son además la guía más segura por lo alto.

## El acebal

A los tres kilómetros el cordal baja a un collado donde cuatro sendas se juntan en un poste indicador. Toma la que señala el acebal, un bosque de acebos y robles viejos en la ladera de abajo. Salta la escalera del borde del bosque y sigue el arroyo cuesta abajo bajo los árboles. Las piedras del vado resbalan cuando baja mucha agua; hay una pasarela 200 m río arriba.

## Vuelta a la estación

El arroyo lleva a una pista de la granja. Gira a la derecha, pasa la granja y sus perros, y salva la última escalera para salir al camino. La cafetería de la estación abre hasta las cinco, y el último tren valle abajo sale a las 18:40.

## Más corto y más largo

Con niños pequeños, deja el cordal: el camino de la ermita sube derecho al collado en cuarenta minutos, y el paseo se queda en 6 km. Quien vaya más fuerte puede seguir por el cordal más allá del collado hasta el vértice geodésico de Hollin Knowe, 2 km más allá, y bajar por su loma norte hasta la presa del embalse. Desde la presa, una pista llana vuelve a la estación por la antigua vía del tren, lo que suma 5 km y una hora y media más o menos. Una tarde de invierno, mira la hora en el collado: bajo el cordal la luz se va pronto, y en el bosque oscurece mucho antes que en el camino.
`; // the draft the notes were made on

// #region notes: the host's records, each with the anchor it stored on the draft
// [the words to find in the draft, the words noted, the note]. A CMS reads the anchors from
// its database; here they are made on the draft so the pen runs on its own.
const NOTES = t({
  en: [
    ['follow the wall up the field', 'the wall', 'Rebuilt last winter: does it reach the top?'],
    ['a cairn that walkers have built', 'a cairn', 'A photograph of the cairn would help here.'],
    ['Cross the stile at', 'the stile', 'Which way does this stile face?'],
    ['the bog on either side is deeper', 'the bog on either side is deeper',
      'Rangers say knee-deep at most. Too alarming?'],
    ['The stepping stones at the ford', 'The stepping stones', 'Give the detour in minutes.'],
  ],
  es: [
    ['sigue el muro prado arriba', 'el muro', '¿Lo rehicieron este invierno? ¿Sigue hasta arriba?'],
    ['un hito de piedras que los caminantes', 'un hito de piedras', 'Aquí iría bien una foto.'],
    ['Salta la escalera del', 'la escalera', '¿Hacia dónde da esta escalera?'],
    ['la turbera de los lados es más honda', 'la turbera de los lados es más honda',
      'Los guardas dicen que no pasa de la rodilla.'],
    ['Las piedras del vado resbalan', 'Las piedras del vado', 'Da el rodeo en minutos.'],
  ],
}).map(([around, words, body], i) => {
  const start = earlier.indexOf(around) + around.indexOf(words);
  const anchor = textAnchor(earlier, { start, end: start + words.length }); // 32 chars a side
  return { id: `n${i + 1}`, body, anchor };
});
// #endregion

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

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown }, config, kitFonts(FONTS));
kitStatus(t({ en: 'Five notes on the draft, looked for in the revision',
  es: 'Cinco notas del borrador, buscadas en la revisión' }));
const view = createViewer(document.getElementById('viewer'), { document: doc, markdown,
  zoom: 'fit-width', maxZoom: 1.3, gap: 20,
  marks: { fontFamily: 'Archivo' }, labels: t({ en: {}, es: { viewer: 'Páginas de la guía',
    page: 'Página {n} de {count}', kinds: { note: 'Nota', box: 'Lugar posible' } } }) });

// #region answer: find every stored anchor in the new text and draw the ones that survive
const COLOR = { exact: '#1f7a45', moved: '#b0640a', ambiguous: '#7b4cc4' };
const found = NOTES.map((note) => resolveAnchor(markdown, note.anchor));
const marks = NOTES.flatMap((note, i) => {
  const at = found[i];
  const label = String(i + 1);
  // In place or moved: one range, the note's mark with its number in the margin.
  if (at.status === 'exact' || at.status === 'moved') {
    return [{ id: note.id, kind: 'note', range: at, label, color: COLOR[at.status] }];
  }
  // Ambiguous: every place the words fit, boxed, for a person to choose.
  if (at.status === 'ambiguous') {
    return at.candidates.map((range, k) => ({ id: `${note.id}.${k}`, kind: 'box', range,
      color: COLOR.ambiguous }));
  }
  return []; // orphaned: the words are gone, the note stays in the thread
});
view.setAnnotations(marks);
// #endregion

// #region list: each note with what the search found
const STATUS = t({
  en: { exact: 'In place', moved: 'Moved', ambiguous: 'Ambiguous', orphaned: 'Orphaned' },
  es: { exact: 'En su sitio', moved: 'Movida', ambiguous: 'Ambigua', orphaned: 'Huérfana' },
});
const detail = (note, at) => ({
  exact: () => `${at.start}`,
  moved: () => `${note.anchor.start} → ${at.start}`,
  ambiguous: () => at.candidates.map((c) => c.start).join(' · '),
  orphaned: () => t({ en: 'the words are gone', es: 'las palabras ya no están' }),
})[at.status]();
document.getElementById('notes').replaceChildren(...NOTES.map((note, i) => {
  const at = found[i];
  const li = document.createElement('li');
  li.className = at.status;
  li.innerHTML = '<button type="button"><b></b><span class="status"></span><q></q>'
    + '<span class="body"></span><small></small></button>';
  const [n, status, quote, body, small] = li.querySelectorAll('b, .status, q, .body, small');
  n.textContent = String(i + 1);
  status.textContent = STATUS[at.status];
  quote.textContent = note.anchor.text;
  body.textContent = note.body;
  small.textContent = detail(note, at);
  const id = at.status === 'ambiguous' ? `${note.id}.0` : note.id;
  li.firstChild.addEventListener('click', () => view.revealAnnotation(id, { behavior: 'smooth' }));
  li.firstChild.disabled = at.status === 'orphaned';
  return li;
}));
document.getElementById('title').textContent = t({ en: 'Notes on the draft',
  es: 'Notas del borrador' });
// #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 més context

Un context més llarg distingeix passatges que repeteixen les mateixes paraules, a canvi de fallar abans quan es reescriu el text que envolta la nota.

```diff
-  const anchor = textAnchor(earlier, { start, end: start + words.length }); // 32 chars a side
+  const anchor = textAnchor(earlier, { start, end: start + words.length }, { context: 64 });
```

### No arribis a les paraules soles

Amb un `minContext` de 8, una nota necessita 8 caràcters sense canvis a cada costat, de manera que les notes curtes passen a `orphaned` en lloc de coincidir amb paraules corrents d'un altre lloc.

```diff
-  const found = NOTES.map((note) => resolveAnchor(markdown, note.anchor));
+  const found = NOTES.map((note) => resolveAnchor(markdown, note.anchor, { minContext: 8 }));
```

## Crèdits

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

## Relacionades

- [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. 213 · Ressaltats a partir d'una llista de rangs](https://postext.dev/ca/cookbook/highlights-from-ranges.md): Els registres d'una eina de revisió, cadascun un rang del Markdown i un veredicte, pintats com a ressaltats de tres colors amb setAnnotations. · Nivell 1 (Bàsic) · Diaris i butlletins
- [Núm. 212 · Seleccionar a la pàgina i llegir el rang del Markdown](https://postext.dev/ca/cookbook/selection-as-markdown-range.md): postext-viewer comunica una selecció sobre les pàgines compostes com un rang del Markdown, el Markdown que abasta i els seus trossos línia a línia. · Nivell 1 (Bàsic) · Revistes i fanzins
