# Seleccionar a la pàgina i llegir el rang del Markdown

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

- Versió HTML: https://postext.dev/ca/cookbook/selection-as-markdown-range
- Recepta Núm. 212 · Integració amb CMS · Nivell 1 (Bàsic) · Sortides: Canvas
- 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/selection-as-markdown-range/es/p01.webp?v=fb56ed31), [2](https://postext.dev/cookbook/selection-as-markdown-range/es/p02.webp?v=fb56ed31)
- ![Una cita seleccionada a la pàgina 1: el plafó mostra el seu rang al Markdown, el Markdown que abasta amb les marques d'èmfasi i les mateixes paraules a l'original.](https://postext.dev/cookbook/selection-as-markdown-range/es/s01.webp?v=fb56ed31)
- ![El paràgraf sencer seleccionat: sis línies a la pàgina 1, que continuen sent un sol rang del Markdown, i el mateix paràgraf marcat a l'original.](https://postext.dev/cookbook/selection-as-markdown-range/es/s02.webp?v=fb56ed31)
- Última actualització: 2026-12-04
- Altres idiomes: [en](https://postext.dev/en/cookbook/selection-as-markdown-range.md), [es](https://postext.dev/es/cookbook/selection-as-markdown-range.md), [de](https://postext.dev/de/cookbook/selection-as-markdown-range.md), [el](https://postext.dev/el/cookbook/selection-as-markdown-range.md), [fr](https://postext.dev/fr/cookbook/selection-as-markdown-range.md), [it](https://postext.dev/it/cookbook/selection-as-markdown-range.md), [pt](https://postext.dev/pt/cookbook/selection-as-markdown-range.md), [ru](https://postext.dev/ru/cookbook/selection-as-markdown-range.md), [zh](https://postext.dev/zh/cookbook/selection-as-markdown-range.md), [ja](https://postext.dev/ja/cookbook/selection-as-markdown-range.md), [ar](https://postext.dev/ar/cookbook/selection-as-markdown-range.md)

## En poques paraules

Un article sobre lents de far en un visor de pàgines, amb un tauler al costat. Quan algú selecciona paraules, el tauler mostra on són en el text original i què hi diu l'original, amb les marques de format.

## Què compondràs

Un article de dues pàgines sobre lents de far, mostrat en un visor de pàgines amb un tauler a la dreta, com el que una eina de revisió té al costat del passatge que es comenta. Hi ha una frase de la primera pàgina seleccionada, i el tauler la llegeix de tres maneres: el rang `{ start, end }` dins el fitxer Markdown, el Markdown que conté, on el nom francès en cursiva conserva els asteriscs, i el paràgraf sencer amb la selecció marcada. Si arrossegues per sobre d'altres paraules, el tauler les segueix mentre arrossegues.

**Aquesta recepta respon a:**

- Com obtinc el rang del Markdown i el text del que un editor selecciona a la pàgina?

## La resposta curta

```js
// script.js, línies 97–118
const view = createViewer($('viewer'), {
  document: doc,
  markdown, // with it, each selection event carries the Markdown it covers
  zoom: 'fit-page', labels: L.viewer,
});
view.on('selectionchange', ({ range, text }) => {
  $('panel').classList.toggle('empty', !range);
  if (!range) return void ($('range').textContent = L.none);
  $('range').textContent = `{ start: ${range.start}, end: ${range.end} }`;
  $('text').textContent = text; // the Markdown, emphasis marks included
  // The range is a plain value: the core API places it too, one piece per line, in page px.
  const rects = rangeRects(doc, range);
  const pages = [...new Set(rects.map((r) => r.pageIndex + 1))].join(', ');
  $('lines').textContent = L.lines(rects.length, pages);
  // The paragraph around it: offsets count in the Markdown file, front matter included.
  const from = markdown.lastIndexOf('\n\n', range.start) + 2;
  let to = markdown.indexOf('\n\n', range.end);
  if (to < 0) to = markdown.length; // the last paragraph
  const mark = Object.assign(document.createElement('mark'), { textContent: text });
  const [before, after] = [markdown.slice(from, range.start), markdown.slice(range.end, to)];
  $('source').replaceChildren(before, mark, after);
});
```

## Ingredients

**Ensenya**

- [Visor de pàgines (postext-viewer)](https://postext.dev/ca/docs/integration-viewer.md#el-visor-de-pàgines): postext-viewer mostra les pàgines d'un document compost en una columna amb desplaçament dins la pàgina d'una altra aplicació: zoom, navegació per pàgines, seleccions retornades com a rangs de Markdown i marques i capes sobre el text.
- [Geometria del text (rangs i punts)](https://postext.dev/ca/docs/integration-geometry.md#el-text-a-la-pàgina): rangeRects converteix un rang del Markdown en rectangles sobre les pàgines, i caretAt, wordAt i blockAt converteixen un punt de la pàgina en una posició, una paraula o un bloc de l'original.

**També fa servir**

- [Fonts abans de compondre](https://postext.dev/ca/docs/configuration-programmatic-usage.md#carregar-les-fonts-abans-de-compondre)

**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`, `rangeRects`, [`renderPageToCanvas`](https://postext.dev/ca/docs/configuration-programmatic-usage.md#renderitzar-una-pàgina-en-un-mapa-de-bits)

**Tipus de lletra**

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

## Elaboració

### 1 · Compon una pàgina on seleccionar

```js
// script.js, línies 29–50
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  layout: { layoutType: 'single' },
  page: { sizePreset: 'custom', width: mm(140), height: mm(210), dpi: 150,
    margins: { top: mm(20), bottom: mm(24), left: mm(22), right: mm(22) } },
  bodyText: { fontFamily: 'Newsreader', fontSize: pt(10.5), lineHeight: pt(15),
    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: 'Archivo', color: col('accent'), fontWeight: 600, levels: [
    { level: 1, fontSize: pt(22), lineHeight: pt(26), marginTop: pt(6), marginBottom: pt(15) },
    { level: 2, fontSize: pt(10), lineHeight: pt(15), marginTop: pt(15), marginBottom: pt(0) },
  ] },
  header: { elements: [] },
  footer: { elements: [
    { kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Archivo', fontSize: pt(8),
      fontWeight: 600, color: col('accent'), align: 'center',
      placement: { anchor: { to: 'page', edge: 'bottom-center' }, offset: { y: mm(-12) } } },
  ] },
};
```

Una pàgina de revista senzilla: una columna justificada en Newsreader, títols en Archivo blau de port i el foli al peu. La selecció funciona igual en qualsevol composició, també amb columnes i en pàgines de dreta a esquerra o verticals, perquè el visor pregunta a la composició on s'ha pintat cada línia.

### 2 · Llegeix la selecció com a Markdown

El codi és [la resposta curta](https://postext.dev/ca/cookbook/selection-as-markdown-range.md#la-resposta-curta) de més amunt. Passa `markdown` a `createViewer` i cada `selectionchange` porta el rang i el Markdown que abasta. El rang és un simple `{ start, end }`, així que `rangeRects`, del nucli, el situa a les pàgines sense el visor, un tros per cada línia que travessa. Els desplaçaments compten dins el fitxer Markdown, preliminars YAML inclosos, així que el paràgraf que envolta una selecció és un tros de la mateixa cadena, i un rang desat avui assenyala les mateixes paraules demà si el text no ha canviat.

### 3 · Restaura una selecció desada

```js
// script.js, línies 122–125
const quote = t({ en: 'The first *lentille à échelons* was lit in July 1823',
  es: 'La primera *lentille à échelons* se encendió en julio de 1823' });
const start = markdown.indexOf(quote);
view.setSelection({ start, end: start + quote.length });
```

`setSelection` rep un rang des del codi i llança els mateixos esdeveniments que un arrossegament, així que el tauler s'omple sol. És el que fa una eina quan reobre el passatge d'un comentari; [Àncores i edicions](https://postext.dev/ca/docs/integration-anchors.md) manté aquest rang vàlid quan el text canvia.

## 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/selection-as-markdown-range

### index.html

```html
<main id="pages">
  <div id="viewer"></div>
  <aside id="panel" aria-live="polite">
    <h2 data-en="Selection" data-es="Selección"></h2>
    <p class="label" data-en="Range in the Markdown" data-es="Rango en el Markdown"></p>
    <p id="range" class="value"></p>
    <div id="details">
    <p id="lines" class="note"></p>
    <p class="label" data-en="Text (Markdown)" data-es="Texto (Markdown)"></p>
    <pre id="text"></pre>
    <p class="label" data-en="In the source" data-es="En el original"></p>
    <pre id="source"></pre>
    </div>
  </aside>
</main>
```

### style.css

```css
/* The host's frame: the viewer on the left, the selection panel on the right.
   The viewer fills its container, so the container gets a height. */
main#pages {
  display: grid; grid-template-columns: minmax(0, 1fr) 380px; height: max(560px, 100vh);
  justify-items: stretch; gap: 0; padding: 0;
}
#viewer { min-height: 0; }
#viewer .postext-viewer {
  --pv-background: #dfe3e6;
  --pv-selection: rgb(29 92 115 / .28);
  --pv-focus: #1d5c73;
}
#panel {
  overflow: auto; padding: 20px 22px; background: #fbfbf9; border-left: 1px solid #c9cfd4;
  font: 15px/1.45 system-ui, sans-serif; color: #1b1f24;
}
#panel h2 { margin: 0 0 14px; font-size: 18px; }
#panel .label {
  margin: 18px 0 4px; font-size: 12px; font-weight: 600; letter-spacing: .06em;
  text-transform: uppercase; color: #4d5861;
}
#panel .value { margin: 0; font: 600 16px/1.4 ui-monospace, Menlo, monospace; }
#panel .note { margin: 2px 0 0; color: #4d5861; font-size: 14px; }
#panel pre {
  margin: 0; padding: 10px 12px; white-space: pre-wrap; overflow-wrap: anywhere;
  background: #fff; border: 1px solid #d5dadf; border-radius: 6px;
  font: 13.5px/1.5 ui-monospace, Menlo, monospace;
}
#panel mark { background: rgb(29 92 115 / .2); color: inherit; border-radius: 2px; }
#panel.empty #details { display: none; }
```

### script.js

```js
// ═══ Postext Cookbook · Nº 212 · Select on the page, read the Markdown range and text ═══
// https://postext.dev/en/cookbook/selection-as-markdown-range
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Newsreader, Archivo (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// An article on lighthouse lenses in postext-viewer, with a panel beside it that a review
// tool would fill from the selection: the range in the Markdown, the Markdown it covers and
// the paragraph around it. The pen selects one sentence itself; drag over the page to change it.
import { buildDocumentWithFonts, renderPageToCanvas, rangeRects } from 'https://esm.sh/postext';
import { createViewer } from 'https://esm.sh/postext-viewer';

const LANG = 'es'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'selection-as-markdown-range';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#1b1f24', // text: a cool near-black
  accent: '#1d5c73', // harbour blue: headings and folio
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion

// #region page: a magazine page, one column, a folio at the foot
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  layout: { layoutType: 'single' },
  page: { sizePreset: 'custom', width: mm(140), height: mm(210), dpi: 150,
    margins: { top: mm(20), bottom: mm(24), left: mm(22), right: mm(22) } },
  bodyText: { fontFamily: 'Newsreader', fontSize: pt(10.5), lineHeight: pt(15),
    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: 'Archivo', color: col('accent'), fontWeight: 600, levels: [
    { level: 1, fontSize: pt(22), lineHeight: pt(26), marginTop: pt(6), marginBottom: pt(15) },
    { level: 2, fontSize: pt(10), lineHeight: pt(15), marginTop: pt(15), marginBottom: pt(0) },
  ] },
  header: { elements: [] },
  footer: { elements: [
    { kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Archivo', fontSize: pt(8),
      fontWeight: 600, color: col('accent'), align: 'center',
      placement: { anchor: { to: 'page', edge: 'bottom-center' }, offset: { y: mm(-12) } } },
  ] },
};
// #endregion

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "Luces de costa"
author: "Marta Quiroga"
---

# La lente que iluminó la costa

Antes de 1823 un faro desperdiciaba casi toda su luz. Una lámpara ardía en el foco de un espejo curvo plateado, y el espejo recogía solo una parte de lo que daba la llama; el resto subía al techo de la linterna o bajaba a la torre. Con bruma la luz se perdía a pocas millas, y el patrón de un barco veía a menudo las rocas antes que la torre.

El físico Augustin Fresnel resolvió el problema cortando una lente en anillos. Una lente maciza capaz de recoger la llama de un faro habría sido demasiado gruesa para fundirla, demasiado pesada para hacerla girar y demasiado oscura en el centro, donde el vidrio era más grueso. Fresnel conservó solo la cara curva de cada zona y suprimió el vidrio de detrás, de modo que los anillos se apoyan en una placa delgada. Por encima y por debajo del tambor central añadió anillos de prismas que devuelven hacia el horizonte la luz que se escapaba.

## Cordouan, 1823

La primera *lentille à échelons* se encendió en julio de 1823 en la torre de Cordouan, sobre una roca en la desembocadura del Gironda. Su luz se veía desde mucho más lejos que la de los reflectores a los que sustituyó, con la misma cantidad de aceite. En treinta años la comisión de faros francesa había instalado lentes del nuevo tipo en toda la costa, y los servicios británico y estadounidense la siguieron.

## Los órdenes de lente

Las lentes se vendían por órdenes, según la distancia entre la llama y el vidrio. Una lente de primer orden tiene una distancia focal de 920 mm y es más alta que un hombre; estaba pensada para las luces de recalada de las costas abiertas. Una de sexto orden, de 150 mm, cabía en la punta de un muelle. Entre ellas estaban el segundo, el tercero y el cuarto orden, y más tarde un orden tres y medio para grandes lagos y estrechos.

Muchas lentes de primer orden siguen girando en sus torres, ahora alrededor de una lámpara eléctrica. Otras se han desmontado y están en museos, donde el visitante puede rodear el armazón de latón y mirar la sala a través de una pared de anillos de vidrio.
`; // content.<lang>.md, inlined by the Cookbook

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

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown }, config, kitFonts(FONTS));
kitStatus(t({ en: 'Coastal Lights · a selection', es: 'Luces de costa · una selección' }));

const L = t({
  en: { none: 'Select some words on the page.',
    lines: (n, p) => `${n} line${n > 1 ? 's' : ''} on page ${p}`, viewer: {} },
  es: { none: 'Selecciona unas palabras en la página.',
    lines: (n, p) => `${n} ${n > 1 ? 'líneas' : 'línea'} en la página ${p}`,
    viewer: { viewer: 'Páginas del artículo', page: 'Página {n} de {count}',
      selection: '{count} caracteres seleccionados', selectionCleared: 'Selección borrada' } },
});
const $ = (id) => document.getElementById(id);

// #region answer: the selection as a range of the Markdown, its source and its lines
const view = createViewer($('viewer'), {
  document: doc,
  markdown, // with it, each selection event carries the Markdown it covers
  zoom: 'fit-page', labels: L.viewer,
});
view.on('selectionchange', ({ range, text }) => {
  $('panel').classList.toggle('empty', !range);
  if (!range) return void ($('range').textContent = L.none);
  $('range').textContent = `{ start: ${range.start}, end: ${range.end} }`;
  $('text').textContent = text; // the Markdown, emphasis marks included
  // The range is a plain value: the core API places it too, one piece per line, in page px.
  const rects = rangeRects(doc, range);
  const pages = [...new Set(rects.map((r) => r.pageIndex + 1))].join(', ');
  $('lines').textContent = L.lines(rects.length, pages);
  // The paragraph around it: offsets count in the Markdown file, front matter included.
  const from = markdown.lastIndexOf('\n\n', range.start) + 2;
  let to = markdown.indexOf('\n\n', range.end);
  if (to < 0) to = markdown.length; // the last paragraph
  const mark = Object.assign(document.createElement('mark'), { textContent: text });
  const [before, after] = [markdown.slice(from, range.start), markdown.slice(range.end, to)];
  $('source').replaceChildren(before, mark, after);
});
// #endregion

// #region restore: a selection made from code, as a tool reopening a saved range does
const quote = t({ en: 'The first *lentille à échelons* was lit in July 1823',
  es: 'La primera *lentille à échelons* se encendió en julio de 1823' });
const start = markdown.indexOf(quote);
view.setSelection({ start, end: start + quote.length });
// #endregion

// The panel's captions in the edition's language.
for (const el of document.querySelectorAll('[data-en]')) el.textContent = t(el.dataset);

// The states the Cookbook photographs: the whole paragraph around the quote selected.
kitShots({ paragraph: () => {
  const from = markdown.lastIndexOf('\n\n', start) + 2;
  const to = markdown.indexOf('\n\n', start);
  view.setSelection({ start: from, end: to < 0 ? markdown.length : to });
} });

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

## Variants

### Actua només quan la selecció estigui feta

`selectionchange` es llança a cada pas de l'arrossegament; `select`, una sola vegada, en deixar anar el punter o amb un doble clic en una paraula.

```diff
-view.on('selectionchange', ({ range, text }) => {
+view.on('select', ({ range, text }) => {
```

### Llegeix-la a l'amplada de la columna

A l'amplada de la columna és més fàcil arrossegar la selecció amb precisió.

```diff
-  zoom: 'fit-page', labels: L.viewer,
+  zoom: 'fit-width', labels: L.viewer,
```

## 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. 216 · Fer clic a la pàgina per trobar l'original](https://postext.dev/ca/cookbook/click-to-markdown-source.md): sourceAt i caretAt converteixen un clic en una pàgina composta en un bloc del Markdown i una posició; el CMS mostra aquella línia de l'original, marcada. · Nivell 2 (Intermedi) · Manuals, guies i obres de consulta
- [Núm. 221 · El teu propi canvas: renderPage, rangeRects i caretAt](https://postext.dev/ca/cookbook/own-canvas-page-view.md): Una vista de pàgina escrita a mà, sense postext-viewer: renderPage pinta cada pàgina, rangeRects dibuixa la selecció i caretAt i caretRect, el cursor. · Nivell 3 (Avançat) · Narrativa, teatre i prosa literària
- [Núm. 218 · Aplicar els canvis acceptats i portar-hi les altres notes](https://postext.dev/ca/cookbook/applying-accepted-edits.md): applyEdits escriu al Markdown les correccions acceptades i hi porta l'àncora de cada nota, marcant les notes on ha caigut un canvi. · Nivell 3 (Avançat) · Revistes i fanzins
