Vai al contenuto principale
Ricetta numero 215

Ricettario · Capitolo 13 · Integrazione con un CMS

Note a margine, con un popover posto dalla pagina

Le note tingono le loro parole e le segnalano nel margine; un clic apre la nota in un popover posto sotto le parole con rangeRects e pageToClient.

In questa pagina
Genere
Cataloghi
Output
Canvas
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
Quattro note di revisione su un testo di museo: ognuna tinge le sue parole e porta una linea tratteggiata fino a una bandierina numerata nel margine largo; la nota 2 è aperta sotto le sue parole.
Quattro note di revisione su un testo di museo: ognuna tinge le sue parole e porta una linea tratteggiata fino a una bandierina numerata nel margine largo; la nota 2 è aperta sotto le sue parole.
  • Esempio in inglese: non c’è ancora un’edizione italiana
  • Formato 160 × 220 mm
  • 1 colonna
  • Alegreya 10,5/15
  • Alegreya Sans
  • 1 pagina
  • Livello
  • Postext 1.103.1
  • Impaginato in 45 ms
  • 118 righe di codice

In breve

Un testo di sala di un museo con le note di una revisora. Ogni nota ombreggia le sue parole e mette un'etichetta numerata nell'ampio margine destro, unita da una linea tratteggiata. Un clic apre la nota in un riquadro sotto le sue parole.

Che cosa comporrai

Un testo di sala di un museo sulla macchina di Anticitera, come lo vede la curatrice editoriale della mostra con le note della revisora. Ognuna delle quattro note tinge le sue parole e porta una linea tratteggiata fino a una bandierina numerata nell'ampio margine esterno. La nota 2 è aperta: un popover con il commento della revisora sta appena sotto le parole a cui si riferisce, con la punta sull'ultima. Premi un'altra bandierina, o le parole tinte, e il popover si sposta lì; scorri o ridimensiona e resta con le sue parole.

Questa ricetta risponde a

  • Come colloco una nota o un popover accanto a un passo della pagina impaginata?

La risposta breve

script.js · righe 108–130nel codice completo
const view = createViewer(document.getElementById('viewer'), {
  document: doc, markdown, zoom: 'fit-width', maxZoom: 1, labels: L.viewer,
  marks: { noteSide: 'end' }, // the flags in the outer margin, not the nearer one
  annotations: notes.map(({ id, label, range }) => ({ id, kind: 'note', range, label })),
});
let open = null; // the note the popover shows
const place = () => {
  if (!open) return;
  // Under the last piece of the noted words: page px, turned into the window's px.
  const last = rangeRects(doc, open.range).at(-1);
  const at = last && view.pageToClient(last.pageIndex, last.rect.x, last.rect.y + last.rect.height);
  pop.hidden = !at;
  if (at) Object.assign(pop.style, { left: `${at.x}px`, top: `${at.y + 8}px` });
};
const show = (id) => {
  open = notes.find((n) => n.id === id) ?? null;
  if (open) fill(open);
  place();
};
view.on('annotationclick', ({ id }) => show(id)); // a flag or the tinted words
view.on('zoomchange', place); // the pages moved under the popover
view.element.addEventListener('scroll', place, { capture: true, passive: true });
show('n2');

Ingredienti

Tipo
Alegreya, Alegreya Sans (SIL OFL 1.1)
Risorse
Nessuna: ogni immagine è disegnata nel codice

Preparazione

#1 · Lascia un margine per le bandierine

script.js · righe 29–49nel codice completo
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(160), height: mm(220), dpi: 150,
    margins: { top: mm(20), bottom: mm(24), left: mm(18), right: mm(42) } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Alegreya', fontSize: pt(10.5), lineHeight: pt(15),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'left', firstLineIndent: mm(5), indentAfterHeading: false,
    hyphenation: { enabled: true }, avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: 'Alegreya Sans', color: col('accent'), fontWeight: 700, levels: [
    { level: 1, fontSize: pt(22), lineHeight: pt(26), marginTop: pt(4), marginBottom: pt(15) },
  ] },
  header: { elements: [] },
  footer: { elements: [
    { kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Alegreya Sans',
      fontSize: pt(8.5), fontWeight: 700, color: col('accent'), align: 'left',
      placement: { anchor: { to: 'page', edge: 'bottom-left' },
        offset: { x: mm(18), y: mm(-12) } } },
  ] },
};

Un margine esterno di 42 mm accoglie le bandierine senza stringere il testo. L'opzione marks del visualizzatore passa noteSide: 'end' alla disposizione dei segni, quindi tutte le bandierine vanno nel margine destro; di norma ognuna prende il margine più vicino alla sua riga. Le bandierine alla stessa altezza si impilano lungo il margine senza sovrapporsi, e un'etichetta troppo lunga viene tagliata con i puntini.

#2 · Conserva le note come intervalli con etichetta

script.js · righe 80–96nel codice completo
// A tool stores the offsets; the pen finds them from quotes so that both editions run.
const notes = t({
  en: [['In the spring of 1901', 'The wreck was found in 1900; the mechanism came up in 1901.'],
    ['a small ball, half silver and half dark',
      'Is the ball still there? If not, say it is reconstructed.'],
    ['nineteen-year calendar', 'Name it: the Metonic cycle. Readers will look it up.'],
    ['X-ray scans', 'Give the year of the scans, 2005.']],
  es: [['En la primavera de 1901', 'El naufragio se halló en 1900; el mecanismo salió en 1901.'],
    ['una bolita, mitad plateada y mitad oscura',
      '¿Se conserva la bolita? Si no, di que es una reconstrucción.'],
    ['calendario de diecinueve años', 'Dale su nombre: el ciclo metónico. El lector lo buscará.'],
    ['radiografías', 'Pon el año de las radiografías, 2005.']],
}).map(([quote, body], i) => {
  const start = markdown.indexOf(quote);
  const range = { start, end: start + quote.length };
  return { id: `n${i + 1}`, label: String(i + 1), body, range };
});

Un segno di nota richiede un intervallo e una label breve per la bandierina, un numero o un'iniziale. Il commento, la sua autrice e la discussione restano nelle schede del sito; il segno dice solo dove vanno.

#3 · Posiziona il popover da coordinate di pagina

Il codice è la risposta breve qui sopra. rangeRects dà i pezzi delle parole annotate in px di pagina; l'angolo in basso a sinistra dell'ultimo pezzo, passato a pageToClient, torna in px della finestra, pronto per un elemento con position: fixed. Il visualizzatore comunica lo zoom iniziale al primo fotogramma, quindi ascoltare zoomchange riposiziona il popover iniziale quando le pagine sono dipinte, e un ascoltatore di scorrimento su view.element lo tiene sotto le sue parole.

La ricetta completa

// ═══ Postext Cookbook · Nº 215 · Notes in the margin, with a popover ═════════════════
// https://postext.dev/en/cookbook/margin-notes-with-popovers
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Alegreya, Alegreya Sans (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A museum's gallery text with a reviewer's notes on it: each note tints its words and
// puts a numbered flag in the outer margin. Pressing a flag opens the note in a popover,
// which the host places under the words from their page coordinates. Note 2 opens itself.
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 = 'margin-notes-with-popovers';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#211f1c', // text
  accent: '#9a4b16', // bronze: title 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 wide outer margin, where the reviewer's flags go
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(160), height: mm(220), dpi: 150,
    margins: { top: mm(20), bottom: mm(24), left: mm(18), right: mm(42) } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Alegreya', fontSize: pt(10.5), lineHeight: pt(15),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'left', firstLineIndent: mm(5), indentAfterHeading: false,
    hyphenation: { enabled: true }, avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: 'Alegreya Sans', color: col('accent'), fontWeight: 700, levels: [
    { level: 1, fontSize: pt(22), lineHeight: pt(26), marginTop: pt(4), marginBottom: pt(15) },
  ] },
  header: { elements: [] },
  footer: { elements: [
    { kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Alegreya Sans',
      fontSize: pt(8.5), fontWeight: 700, color: col('accent'), align: 'left',
      placement: { anchor: { to: 'page', edge: 'bottom-left' },
        offset: { x: mm(18), y: mm(-12) } } },
  ] },

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

#Apri una nota al passaggio del puntatore

L'evento hover porta gli id dei segni sotto il puntatore, quello in cima per primo.

 view.on('annotationclick', ({ id }) => show(id)); // a flag or the tinted words
+view.on('hover', ({ annotations }) => annotations[0] && show(annotations[0]));

#Lascia a ogni bandierina il margine più vicino

In una pagina a due colonne, le note della colonna sinistra andranno allora nel margine sinistro.

-  marks: { noteSide: 'end' }, // the flags in the outer margin, not the nearer one
+  marks: {}, // each flag in the margin nearer its words

Crediti

Testo
Testo originale, CC BY 4.0
Font
Alegreya (SIL OFL 1.1) · Alegreya Sans (SIL OFL 1.1)