# Resultados de búsqueda dibujados sobre las páginas

> Un buscador encuentra la consulta en el Markdown, dibuja cada coincidencia como un resaltado en las páginas compuestas y las recorre con revealAnnotation.

- Versión HTML: https://postext.dev/es/cookbook/search-results-on-pages
- Receta N.º 219 · Integración con CMS · Nivel 2 (Intermedio) · Salidas: Canvas, Controles en vivo
- Géneros: Cualquier género
- Requiere postext ≥ 1.103.0 · probada con 1.103.1 el 2026-12-04
- Páginas: [1](https://postext.dev/cookbook/search-results-on-pages/es/p01.webp?v=25fe8049), [2](https://postext.dev/cookbook/search-results-on-pages/es/p02.webp?v=25fe8049)
- ![Una búsqueda de «péndulo»: cada resultado teñido en las páginas, el actual recuadrado en rojo y el recuento junto a la casilla de búsqueda.](https://postext.dev/cookbook/search-results-on-pages/es/s01.webp?v=25fe8049)
- ![Una búsqueda nueva de «Huygens»: el segundo de cuatro resultados recuadrado en rojo, con el intertítulo y los demás resultados teñidos alrededor.](https://postext.dev/cookbook/search-results-on-pages/es/s02.webp?v=25fe8049)
- Última actualización: 2026-12-04
- Otros idiomas: [en](https://postext.dev/en/cookbook/search-results-on-pages.md), [ca](https://postext.dev/ca/cookbook/search-results-on-pages.md), [de](https://postext.dev/de/cookbook/search-results-on-pages.md), [el](https://postext.dev/el/cookbook/search-results-on-pages.md), [fr](https://postext.dev/fr/cookbook/search-results-on-pages.md), [it](https://postext.dev/it/cookbook/search-results-on-pages.md), [pt](https://postext.dev/pt/cookbook/search-results-on-pages.md), [ru](https://postext.dev/ru/cookbook/search-results-on-pages.md), [zh](https://postext.dev/zh/cookbook/search-results-on-pages.md), [ja](https://postext.dev/ja/cookbook/search-results-on-pages.md), [ar](https://postext.dev/ar/cookbook/search-results-on-pages.md)

## En pocas palabras

Un capítulo sobre la historia del reloj de péndulo, mostrado página a página, con un buscador encima. Cada sitio donde aparece la palabra buscada se resalta en las páginas, y dos botones llevan a la anterior o a la siguiente.

## Lo que vas a componer

Un capítulo de *Medir el tiempo*, una historia de la relojería en página de 135 × 205 mm, mostrado en postext-viewer bajo la barra de búsqueda del propio sitio. La consulta «péndulo» ya está escrita: sus 21 coincidencias se tiñen en las páginas, la tercera aparece recuadrada en rojo y llevada a la vista, y el contador dice «3 de 21». Al escribir, las coincidencias cambian sobre la marcha; Intro y los botones de flecha avanzan, y Mayúsculas + Intro retrocede.

**Esta receta responde a:**

- ¿Cómo muestro los resultados de una búsqueda sobre las páginas compuestas?

## La respuesta corta

```js
// script.js, líneas 113–137
let matches = [];
let current = 0;
function search(query) {
  const escaped = query.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  // A regular expression over the Markdown itself, so each match index is already an offset.
  const found = escaped ? [...markdown.matchAll(new RegExp(escaped, 'giu'))] : [];
  // A match the pages do not paint (the front matter, a link's address) has no pieces.
  matches = found.map((m) => ({ start: m.index, end: m.index + m[0].length }))
    .filter((range) => rangeRects(doc, range).length > 0);
  show(0);
}
function show(index, behavior = 'auto') {
  current = matches.length ? (index + matches.length) % matches.length : 0;
  view.setAnnotations([
    ...matches.map((range, i) => ({ id: `m${i}`, kind: 'highlight', range })),
    ...matches.slice(current, current + 1).map((range) =>
      ({ id: 'current', kind: 'box', range, color: '#c0362c' })),
  ]);
  if (matches.length) view.revealAnnotation('current', { behavior });
  $('count').textContent = matches.length
    ? t({ en: `${current + 1} of ${matches.length}`, es: `${current + 1} de ${matches.length}` })
    : t({ en: 'No matches', es: 'Sin resultados' });
}
$('prev').addEventListener('click', () => show(current - 1, 'smooth'));
$('next').addEventListener('click', () => show(current + 1, 'smooth'));
```

## Ingredientes

**Enseña**

- [Marcas de anotación](https://postext.dev/es/docs/integration-marks.md#marcas-de-anotación): Resaltados, subrayados, tachados, sustituciones, inserciones, notas y recuadros colocados sobre el texto de las páginas, pintados en un canvas o escritos como SVG sobre imágenes de página.
- [Geometría del texto (rangos y puntos)](https://postext.dev/es/docs/integration-geometry.md#el-texto-en-la-página): rangeRects convierte un rango del Markdown en rectángulos sobre las páginas, y caretAt, wordAt y blockAt convierten un punto de la página en una posición, una palabra o un bloque del original.

**También usa**

- [Visor de páginas (postext-viewer)](https://postext.dev/es/docs/integration-viewer.md#el-visor-de-páginas)
- [Páginas en un canvas](https://postext.dev/es/docs/configuration-programmatic-usage.md#renderizar-una-página-como-mapa-de-bits)
- [Fuentes antes de componer](https://postext.dev/es/docs/configuration-programmatic-usage.md#cargar-las-fuentes-antes-de-componer)
- [Cabeceras y folios](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies)
- [Márgenes simétricos](https://postext.dev/es/docs/configuration-page-layout.md#márgenes-simétricos-espejo)
- [Paleta de color semántica](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores)
- [Cabeceras según el tipo de página](https://postext.dev/es/docs/configuration-headers-footers.md#elementos-de-texto)

**La configuración de un vistazo**

- [`bodyText`](https://postext.dev/es/docs/configuration-text.md#texto-base), [`colorPalette`](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores), [`footer`](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies), [`header`](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies), [`headings`](https://postext.dev/es/docs/configuration-headings.md#encabezados), [`layout`](https://postext.dev/es/docs/configuration-page-layout.md#disposición), [`locale`](https://postext.dev/es/docs/configuration-language.md#separación-silábica), [`page`](https://postext.dev/es/docs/configuration-page-layout.md#página)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/es/docs/configuration-programmatic-usage.md#cargar-las-fuentes-antes-de-componer), `createViewer`, `rangeRects`, [`renderPageToCanvas`](https://postext.dev/es/docs/configuration-programmatic-usage.md#renderizar-una-página-como-mapa-de-bits), `setAnnotations`

**Tipografías**

- Libre Caslon Text (OFL-1.1), Libre Franklin (OFL-1.1)

## Elaboración

### 1 · Compón una página de libro

```js
// script.js, líneas 31–41
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'Libre Franklin', fontSize: pt(6.8), 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: 600, color: col('accent') };
const 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),
] };
```

El capítulo va compuesto como un libro de historia sin adornos: Libre Caslon Text a 8,8 pt, intertítulos en Libre Franklin y cabeceras que cambian de lado con la página. La búsqueda no necesita nada de la composición.

### 2 · Busca en el Markdown, dibuja en las páginas

El código es [la respuesta corta](https://postext.dev/es/cookbook/search-results-on-pages.md#la-respuesta-corta) de arriba. La búsqueda se hace sobre el Markdown, no sobre el texto pintado, así que la posición de cada coincidencia ya es la que usan las marcas: no hay que traducir del texto de la página al original. Una coincidencia que las páginas no pintan, como el título del preámbulo o la dirección de un enlace, no tiene piezas en `rangeRects` y queda fuera de la cuenta. Cada coincidencia se convierte en un `highlight`, la actual además en un `box`, y `revealAnnotation` desplaza el visor hasta ella.

### 3 · Sigue las teclas del lector

```js
// script.js, líneas 141–150
$('query').addEventListener('input', (e) => search(e.target.value));
$('query').addEventListener('keydown', (e) => {
  if (e.key !== 'Enter') return;
  e.preventDefault();
  show(current + (e.shiftKey ? -1 : 1), 'smooth');
});
// A press on a highlight makes it the current match.
view.on('annotationclick', ({ id }) => {
  if (id.startsWith('m')) show(Number(id.slice(1)), 'smooth');
});
```

La lista de marcas se rehace con cada pulsación; el visor vuelve a colocarlas sobre la misma composición, lo que en un capítulo lleva unos milisegundos. Al pulsar un resaltado, este pasa a ser la coincidencia actual, a través de `annotationclick`.

## La receta completa

Los archivos de abajo se componen a partir de la carpeta de la receta, con el texto de ejemplo y el kit común del Recetario ya incluidos. Para ejecutarlos como una sola página, pon el HTML en `<body>`, el CSS en un elemento `<style>` y el script en un `<script type="module">`; o pega cada uno en el panel correspondiente de un pen nuevo de CodePen (el JS como módulo). El script importa postext desde esm.sh, así que no hay nada que instalar ni compilar.

- Carpeta de la receta: https://github.com/drnachio/postext/tree/main/cookbook/search-results-on-pages

### index.html

```html
<main id="pages">
  <form id="tools" role="search">
    <input id="query" type="search" autocomplete="off" spellcheck="false">
    <span id="count" role="status"></span>
    <button id="prev" type="button">‹</button>
    <button id="next" type="button">›</button>
  </form>
  <div id="viewer"></div>
</main>
```

### style.css

```css
/* The host's frame: a search bar over the viewer, which fills what the window leaves. */
main#pages {
  display: flex; flex-direction: column; height: max(540px, calc(100vh - 44px));
  justify-items: normal; padding: 0;
}
#tools {
  display: flex; align-items: center; gap: 8px; padding: 8px 16px; background: #16181d;
  border-bottom: 1px solid #23262d; font: 500 14px/1.2 system-ui, sans-serif; color: #f4f1ea;
}
#query {
  flex: 0 1 320px; min-height: 44px; padding: 0 12px; border: 1px solid #4a505b;
  border-radius: 6px; background: #0e1014; color: #f4f1ea; font: inherit; font-size: 16px;
}
#query:focus-visible, #tools button:focus-visible { outline: 2px solid #e8a33d; outline-offset: 2px; }
#count { min-width: 7em; padding: 0 6px; color: #e8a33d; font-variant-numeric: tabular-nums; }
#tools button {
  min-width: 44px; min-height: 44px; border: 1px solid #4a505b; border-radius: 6px;
  background: #1f2229; color: #f4f1ea; font: inherit; font-size: 18px; cursor: pointer;
}
#tools button:hover { border-color: #e8a33d; }
#viewer { flex: 1; min-height: 0; }
#viewer .postext-viewer { --pv-background: #0e1014; --pv-focus: #e8a33d; }
```

### script.js

```js
// ═══ Postext Cookbook · Nº 219 · Search results drawn on the pages ═══════════════════
// https://postext.dev/en/cookbook/search-results-on-pages
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Libre Caslon Text, Libre Franklin (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A chapter of a history of timekeeping in postext-viewer, with a search box over it. The
// query is looked for in the Markdown, every match becomes a highlight on the pages, and the
// previous and next buttons box one match and scroll it into view with revealAnnotation.
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 = 'search-results-on-pages';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#211d1a', // text
  accent: '#7a2e2a', // oxblood: title, subheads, folios
  muted: '#6e665f', // 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.2; // pt of body leading

// #region heads: running heads that change side with the page
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'Libre Franklin', fontSize: pt(6.8), 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: 600, color: col('accent') };
const 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),
] };
// #endregion

const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(135), height: mm(205), dpi: 150,
    margins: { top: mm(19), bottom: mm(20), left: mm(17), right: mm(15), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Libre Caslon Text', fontSize: pt(8.8), 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: 'Libre Franklin', color: col('accent'), fontWeight: 600, levels: [
    { level: 1, fontFamily: 'Libre Caslon Text', fontWeight: 400, fontSize: pt(22),
      lineHeight: pt(26), marginTop: mm(16), marginBottom: pt(LEAD * 1.5) },
    { level: 2, fontSize: pt(8.6), lineHeight: pt(LEAD), letterSpacing: pt(0.3),
      marginTop: pt(LEAD), marginBottom: pt(0) },
  ] },
  header,
  footer: { elements: [] },
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "Medir el tiempo"
author: "Marta Quiroga"
---

# El reloj de péndulo

Antes de 1656, los mejores relojes de Europa adelantaban o atrasaban un cuarto de hora al día. Su marcha la regulaba un foliot con escape de paletas: una barra que oscilaba a un lado y a otro empujada por las ruedas que movía la pesa, sin un periodo propio. Cualquier cosa que cambiara el empuje, desde un aceite que se espesaba hasta un diente gastado, cambiaba la marcha. Un reloj era un objeto espléndido para el campanario de una iglesia, pero el astrónomo que medía el paso de una estrella por el meridiano seguía contando su propio pulso o las gotas de una clepsidra.

## La lámpara de Galileo

La historia de que Galileo, siendo estudiante en Pisa, cronometró una lámpara que oscilaba en la catedral con su pulso viene de su primer biógrafo y quizá esté retocada. Lo seguro es que en la década de 1630 había escrito que un péndulo de una longitud dada oscila en el mismo tiempo tanto si su arco es amplio como si es estrecho, y que ese tiempo crece con la raíz cuadrada de la longitud. Al final de su vida, ya ciego, describió a su hijo Vincenzio un reloj regulado por un péndulo. Vincenzio empezó a construirlo tras la muerte de su padre y lo dejó sin terminar.

## Huygens

El matemático neerlandés Christiaan Huygens llegó a la misma idea en 1656 y la hizo construir enseguida. En su reloj el péndulo no movía las ruedas; solo las dejaba avanzar un diente en cada oscilación, y la pesa devolvía al péndulo la poca energía que perdía por rozamiento. La marcha pertenecía ahora al péndulo, no al tren de ruedas. Los relojes de Huygens se desviaban unos diez segundos al día, cien veces menos que los relojes a los que sustituían, y en pocos años los relojeros de toda Europa adaptaban las máquinas viejas al control por péndulo.

Huygens vio además el fallo de la regla de Galileo. Un péndulo que oscila con un arco amplio tarda algo más que uno que oscila con un arco estrecho. Demostró que una lenteja que se moviera a lo largo de una cicloide, y no de un círculo, sería de verdad isócrona, y colocó junto a la suspensión unas mejillas curvas contra las que se enrollaba el hilo para llevar la lenteja por ese camino. En la práctica las mejillas daban más problemas de los que resolvían, y los relojeros posteriores se limitaron a mantener pequeño el arco.

## El péndulo largo

El escape de áncora, introducido en Londres hacia 1670, necesitaba solo unos pocos grados de oscilación. Con un arco pequeño el péndulo podía ser largo y pesado, y un péndulo de cerca de un metro bate una vez por segundo. Este péndulo de segundos, colgado en una caja alta de madera, dio lugar al reloj de caja alta que ocupó vestíbulos y salas durante dos siglos. Los observatorios usaban el mismo péndulo en reguladores de precisión, con un escape de golpe muerto que no empujaba el péndulo hacia atrás y con varillas de metales distintos dispuestas para que sus dilataciones se anularan con el calor.

## Un péndulo que pesa la Tierra

Los astrónomos no tardaron en notar que un péndulo no marcaba el mismo tiempo en todas partes. En 1672 Jean Richer llevó un reloj de París a Cayena, cerca del ecuador, y vio que tenía que acortar su péndulo para que no atrasara. Newton explicó por qué: la Tierra se ensancha en el ecuador, así que allí la gravedad es algo más débil y el péndulo oscila más despacio. Durante los doscientos años siguientes, las expediciones llevaron péndulos invariables por todo el mundo y los cronometraron con las estrellas, midiendo la forma de la Tierra estación a estación.

El reloj de péndulo siguió siendo el más exacto hasta la década de 1920, cuando el reloj Shortt, con un péndulo que oscilaba libre en un tanque de vacío y otro que hacía el trabajo, llegó a un segundo al año. En menos de diez años el cristal de cuarzo lo había superado.
`; // content.<lang>.md, inlined by the Cookbook

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = {
  'Libre Caslon Text': ['400'],
  'Libre Franklin': ['500', '600'],
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown }, config, kitFonts(FONTS));
kitStatus(t({ en: 'Search the chapter', es: 'Busca en el capítulo' }));
const view = createViewer(document.getElementById('viewer'), { document: doc, markdown,
  zoom: 'fit-width', maxZoom: 1, gap: 20,
  labels: t({ en: { kinds: { highlight: 'Match', box: 'Current match' } },
    es: { viewer: 'Páginas del libro', page: 'Página {n} de {count}',
      kinds: { highlight: 'Resultado', box: 'Resultado actual' } } }) });
const $ = (id) => document.getElementById(id);

// #region answer: every match of the query as a mark, one of them boxed and in view
let matches = [];
let current = 0;
function search(query) {
  const escaped = query.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  // A regular expression over the Markdown itself, so each match index is already an offset.
  const found = escaped ? [...markdown.matchAll(new RegExp(escaped, 'giu'))] : [];
  // A match the pages do not paint (the front matter, a link's address) has no pieces.
  matches = found.map((m) => ({ start: m.index, end: m.index + m[0].length }))
    .filter((range) => rangeRects(doc, range).length > 0);
  show(0);
}
function show(index, behavior = 'auto') {
  current = matches.length ? (index + matches.length) % matches.length : 0;
  view.setAnnotations([
    ...matches.map((range, i) => ({ id: `m${i}`, kind: 'highlight', range })),
    ...matches.slice(current, current + 1).map((range) =>
      ({ id: 'current', kind: 'box', range, color: '#c0362c' })),
  ]);
  if (matches.length) view.revealAnnotation('current', { behavior });
  $('count').textContent = matches.length
    ? t({ en: `${current + 1} of ${matches.length}`, es: `${current + 1} de ${matches.length}` })
    : t({ en: 'No matches', es: 'Sin resultados' });
}
$('prev').addEventListener('click', () => show(current - 1, 'smooth'));
$('next').addEventListener('click', () => show(current + 1, 'smooth'));
// #endregion

// #region keys: type to search, Enter for the next match, Shift + Enter for the previous one
$('query').addEventListener('input', (e) => search(e.target.value));
$('query').addEventListener('keydown', (e) => {
  if (e.key !== 'Enter') return;
  e.preventDefault();
  show(current + (e.shiftKey ? -1 : 1), 'smooth');
});
// A press on a highlight makes it the current match.
view.on('annotationclick', ({ id }) => {
  if (id.startsWith('m')) show(Number(id.slice(1)), 'smooth');
});
// #endregion

// The labels in the edition's language, and the query the card shows.
const labels = t({ en: ['Search', 'Previous match', 'Next match'],
  es: ['Buscar', 'Resultado anterior', 'Resultado siguiente'] });
['query', 'prev', 'next'].forEach((id, i) => $(id).setAttribute('aria-label', labels[i]));
$('query').placeholder = labels[0];
$('query').value = t({ en: 'pendulum', es: 'péndulo' });
search($('query').value);
show(2); // the third match, half way down the first page

// The states the Cookbook photographs: another search.
kitShots({ other: () => { $('query').value = 'Huygens'; search('Huygens'); show(1); } });

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

## Variantes

### Busca palabras enteras

Los límites de palabra dejan fuera «péndulos» al buscar «péndulo», en texto latino.

```diff
-  const found = escaped ? [...markdown.matchAll(new RegExp(escaped, 'giu'))] : [];
+  const found = escaped ? [...markdown.matchAll(new RegExp(`\\b${escaped}\\b`, 'giu'))] : [];
```

### Distingue mayúsculas

Sin la bandera `i`, «Péndulo» a principio de frase ya no coincide.

```diff
-  const found = escaped ? [...markdown.matchAll(new RegExp(escaped, 'giu'))] : [];
+  const found = escaped ? [...markdown.matchAll(new RegExp(escaped, 'gu'))] : [];
```

## Créditos

- Receta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Tipografías: Libre Caslon Text (OFL-1.1), Libre Franklin (OFL-1.1)
- Código: MIT · Contenido de ejemplo: CC-BY-4.0

## Relacionadas

- [N.º 213 · Resaltados a partir de una lista de rangos](https://postext.dev/es/cookbook/highlights-from-ranges.md): Los registros de una herramienta de revisión, cada uno un rango del Markdown y un veredicto, pintados como resaltados de tres colores con setAnnotations. · Nivel 1 (Básico) · Periódicos y boletines
- [N.º 212 · Seleccionar en la página y leer el rango del Markdown](https://postext.dev/es/cookbook/selection-as-markdown-range.md): postext-viewer comunica una selección sobre las páginas compuestas como un rango del Markdown, el Markdown que abarca y sus trozos línea a línea. · Nivel 1 (Básico) · Revistas y fanzines
- [N.º 216 · Hacer clic en la página para encontrar el original](https://postext.dev/es/cookbook/click-to-markdown-source.md): sourceAt y caretAt convierten un clic en una página compuesta en un bloque del Markdown y una posición; el CMS muestra esa línea del original, marcada. · Nivel 2 (Intermedio) · Manuales, guías y obras de consulta
