Vai al contenuto principale
Ricetta numero 219

Ricettario · Capitolo 13 · Integrazione con un CMS

Risultati di ricerca disegnati sulle pagine

Un campo di ricerca trova la query nel Markdown, disegna ogni occorrenza come evidenziazione sulle pagine impaginate e le scorre con revealAnnotation.

In questa pagina
Livello
Intermedio
Postext
Provata con Postext 1.103.1
Richiede ≥ 1.103.0
Licenza
Aggiornata il 4 dic 2026
Codice MIT · Testo CC BY 4.0
Una ricerca di «pendulum»: ogni risultato tinto sulle pagine, quello corrente riquadrato in rosso e il conteggio accanto alla casella di ricerca.
Una ricerca di «pendulum»: ogni risultato tinto sulle pagine, quello corrente riquadrato in rosso e il conteggio accanto alla casella di ricerca.
  • Esempio in inglese: non c’è ancora un’edizione italiana
  • Formato 135 × 205 mm
  • 1 colonna
  • Libre Caslon Text 8,8/13,2
  • Libre Franklin
  • 2 pagine
  • Livello
  • Postext 1.103.1
  • Impaginato in 68 ms
  • 123 righe di codice

In breve

Un capitolo sulla storia dell'orologio a pendolo, mostrato pagina per pagina, con un campo di ricerca sopra. Ogni punto in cui compare la parola cercata è evidenziato sulle pagine, e due pulsanti portano alla precedente o alla successiva.

Che cosa comporrai

Un capitolo di Keeping Time, una storia della misura del tempo su pagina da 135 × 205 mm, mostrato in postext-viewer sotto la barra di ricerca del sito stesso. La query «pendulum» è già scritta: le sue 21 occorrenze sono colorate sulle pagine, la terza è riquadrata in rosso e portata in vista, e il contatore indica la sua posizione fra le 21. Digitando, le occorrenze cambiano man mano; Invio e i pulsanti a freccia vanno avanti, Maiusc + Invio torna indietro.

Questa ricetta risponde a

  • Come mostro i risultati di una ricerca sulle pagine impaginate?

La risposta breve

script.js · righe 113–137nel codice completo
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'));

Ingredienti

Tipo
Libre Caslon Text, Libre Franklin (SIL OFL 1.1)
Risorse
Nessuna: ogni immagine è disegnata nel codice

Preparazione

#1 · Componi una pagina di libro

script.js · righe 31–41nel codice completo
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),
] };

Il capitolo è composto come un libro di storia senza fronzoli: Libre Caslon Text a 8,8 pt, sottotitoli in Libre Franklin e testatine che cambiano lato con la pagina. Alla ricerca non serve nulla dell'impaginazione.

#2 · Cerca nel Markdown, disegna sulle pagine

Il codice è la risposta breve qui sopra. La ricerca avviene sul Markdown, non sul testo dipinto, quindi l'indice di ogni occorrenza è già la posizione che usano i segni: non c'è da tradurre dal testo della pagina al sorgente. Un'occorrenza che le pagine non dipingono mai, come il titolo nel front matter o l'indirizzo di un link, non ha pezzi in rangeRects e resta fuori dal conteggio. Ogni occorrenza diventa un highlight, quella corrente anche un box, e revealAnnotation fa scorrere il visualizzatore fino a lei.

#3 · Segui i tasti del lettore

script.js · righe 141–150nel codice completo
$('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');
});

L'elenco dei segni si rifà a ogni tasto; il visualizzatore li ricolloca sulla stessa impaginazione, il che su un capitolo richiede pochi millisecondi. Premendo un'evidenziazione, questa diventa l'occorrenza corrente, tramite annotationclick.

La ricetta completa

// ═══ 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 = 'en'; // @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 } },

Lo script.js composto funziona così com’è: incollalo nello script modulo di qualsiasi pagina, oppure apri la ricetta su CodePen. Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)

Varianti

#Cerca parole intere

I confini di parola lasciano fuori «pendulums» da una ricerca di «pendulum», per i testi in alfabeto latino.

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

#Distingui le maiuscole

Senza il flag i, «Pendulum» a inizio frase non corrisponde più.

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

Crediti

Testo
Testo originale, CC BY 4.0
Font
Libre Caslon Text (SIL OFL 1.1) · Libre Franklin (SIL OFL 1.1)