In breve
Un articolo sui platani di Londra come lo vede chi verifica i fatti: le affermazioni esaminate sono ombreggiate in giallo, blu o rosa secondo il verdetto, e un elenco accanto le nomina. Un clic su una voce porta alle sue parole.
Che cosa comporrai
Un articolo di newsletter sul platano di Londra, come lo vede la redazione che verifica i fatti in uno strumento di revisione. Cinque affermazioni hanno un verdetto: giallo se verificata, blu se l'autore deve ancora una fonte, rosa per una domanda all'autore. Le evidenziazioni stanno sulla pagina impaginata, spezzate dove la frase va a capo, e l'elenco a destra contiene le stesse cinque schede in ordine di lettura. Fai clic su una voce e il visualizzatore porta in vista le sue parole.
Questa ricetta risponde a
- Come disegno evidenziazioni sulle pagine a partire da un elenco di intervalli del Markdown?
La risposta breve
const view = createViewer(document.getElementById('viewer'), {
document: doc, markdown, zoom: 'fit-page', labels,
});
view.setAnnotations(claims.map(({ id, verdict, range }) => ({
id, kind: 'highlight', range, color: VERDICTS[verdict].color, // 35 % over the text
})));
// The list beside the page: an entry brings its words into view.
const list = document.getElementById('claims');
for (const { id, verdict, range } of claims) {
const item = document.createElement('button');
item.style.setProperty('--tag', VERDICTS[verdict].color);
item.innerHTML = '<b></b><span></span>';
item.querySelector('b').textContent = VERDICTS[verdict].name;
item.querySelector('span').textContent = markdown.slice(range.start, range.end);
item.addEventListener('click', () => view.revealAnnotation(id, { behavior: 'smooth' }));
list.append(item);
}
Ingredienti
- Funzionalità
- Segni di annotazioneVisualizzatore di pagine (postext-viewer)I font prima dell’impaginazione
- Tipo
- Source Serif 4, Source Sans 3 (SIL OFL 1.1)
- Risorse
- Nessuna: ogni immagine è disegnata nel codice
Preparazione
#1 · Conserva le schede come intervalli
// A CMS stores the offsets; the pen finds them from quotes so that both editions run.
const VERDICTS = {
checked: { color: '#d39b00', name: t({ en: 'Checked', es: 'Comprobado' }) },
source: { color: '#2f7fd6', name: t({ en: 'Needs a source', es: 'Falta la fuente' }) },
query: { color: '#d64c86', name: t({ en: 'Query the author', es: 'Preguntar al autor' }) },
};
const claims = t({
en: [['source', 'reached England from Virginia'],
['query', 'perhaps in Spain, perhaps in an English garden'], ['checked', 'set out in 1789'],
['source', 'it became the commonest street tree'],
['checked', 'first recorded in London in 2008']],
es: [['source', 'llegó a Inglaterra desde Virginia'],
['query', 'quizá en España, quizá en un jardín inglés'], ['checked', 'plantados en 1789'],
['source', 'llegó a ser el árbol de calle más común'],
['checked', 'registrada por primera vez en Londres en 2008']],
}).map(([verdict, quote], i) => {
const start = markdown.indexOf(quote);
return { id: `c${i + 1}`, verdict, range: { start, end: start + quote.length } };
});
Una scheda è ciò che lo strumento già salva: un intervallo { start, end } nel Markdown del capitolo e il verdetto di chi rivede. I segni non sanno nulla dei verdetti; il sito trasforma ciascuno in un colore. Qui gli offset vengono da una citazione del testo, perché funzionino sia l'edizione inglese sia quella spagnola; un sistema di contenuti li leggerebbe dal suo database.
#2 · Dipingile come evidenziazioni
Il codice è la risposta breve qui sopra. setAnnotations sostituisce i segni mostrati dal visualizzatore; ogni evidenziazione è un riempimento traslucido su ogni pezzo del suo intervallo, al 35 % del suo color, quindi il testo sotto resta nero. Richiamala con il nuovo elenco quando le schede cambiano, e il visualizzatore ridipinge solo le pagine in vista. L'elenco a destra sono le stesse schede: revealAnnotation porta in vista un segno tramite l'id che il sito gli ha dato.
#3 · Dai un nome ai segni nella lingua del lettore
const labels = t({ en: {}, es: { viewer: 'Páginas del boletín', page: 'Página {n} de {count}',
kinds: { highlight: 'Resaltado' } } });
Il visualizzatore fa di ogni segno un pulsante per la tastiera, con un nome preso da labels.kinds e dal testo segnato, così un lettore di schermo annuncia «Highlight: set out in 1789». L'edizione spagnola passa i suoi nomi; quella inglese non ne ha bisogno.
La ricetta completa
// ═══ Postext Cookbook · Nº 213 · Highlights from a list of ranges ═══════════════════
// https://postext.dev/en/cookbook/highlights-from-ranges
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Source Serif 4, Source Sans 3 (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A newsletter article on the London plane, as a fact-checker sees it in a review tool: the
// claims the desk has looked at are highlighted in three colours, one per verdict, and the
// list beside the page is the same records. A click on an entry brings its words into view.
import { buildDocumentWithFonts, renderPageToCanvas } 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 = 'highlights-from-ranges';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
ink: '#22201c', // text
accent: '#3d6b35', // leaf green: 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 newsletter page, one wide column
const config = {
locale: t({ en: 'en-gb', es: 'es' }),
colorPalette,
page: { sizePreset: 'custom', width: mm(160), height: mm(230), dpi: 150,
margins: { top: mm(20), bottom: mm(24), left: mm(24), right: mm(24) } },
layout: { layoutType: 'single' },
bodyText: { fontFamily: 'Source Serif 4', fontSize: pt(10.5), lineHeight: pt(15),
color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
textAlign: 'justify', firstLineIndent: mm(4.5), indentAfterHeading: false,
hyphenation: { enabled: true }, optimalLineBreaking: true,
avoidWidows: true, avoidOrphans: true, avoidRunts: true },
headings: { fontFamily: 'Source Sans 3', color: col('accent'), fontWeight: 700, levels: [
{ level: 1, fontSize: pt(26), lineHeight: pt(30), marginTop: pt(0), marginBottom: pt(15) },
{ level: 2, fontSize: pt(10.5), lineHeight: pt(15), marginTop: pt(15), marginBottom: pt(0) },
] },
header: { elements: [] },
footer: { elements: [
{ kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Source Sans 3',
fontSize: pt(8), fontWeight: 700, color: col('accent'), align: 'center',
placement: { anchor: { to: 'page', edge: 'bottom-center' }, offset: { y: mm(-12) } } },
<main id="pages">
<div id="viewer"></div>
<aside id="panel">
<h2 id="heading"></h2>
<div id="claims"></div>
</aside>
</main>
/* The host's frame: the viewer on the left, the list of records on the right.
The viewer fills its container, so the container gets a height. */
main#pages {
display: grid; grid-template-columns: minmax(0, 1fr) 340px; height: max(560px, 100vh);
justify-items: stretch; gap: 0; padding: 0;
}
#viewer { min-height: 0; }
#viewer .postext-viewer { --pv-background: #e4e2dc; --pv-focus: #3d6b35; }
#panel {
overflow: auto; padding: 20px 18px; background: #faf9f6; border-left: 1px solid #cfccc4;
font: 15px/1.4 system-ui, sans-serif; color: #22201c;
}
#panel h2 { margin: 0 0 12px; font-size: 18px; }
#claims { display: grid; gap: 8px; }
#claims button {
display: grid; gap: 2px; min-height: 44px; padding: 8px 12px 9px 14px; text-align: left;
background: #fff; border: 1px solid #d6d3cb; border-left: 6px solid var(--tag);
border-radius: 6px; font: inherit; color: inherit; cursor: pointer;
}
#claims button:hover { border-color: var(--tag); }
#claims button:focus-visible { outline: 2px solid #3d6b35; outline-offset: 2px; }
#claims b { font-size: 12px; letter-spacing: .05em; text-transform: uppercase; color: #55524b; }
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
#Riempimenti più intensi
Su una pagina crema o tinta, un riempimento al 35 % può risultare troppo tenue.
- document: doc, markdown, zoom: 'fit-page', labels,
+ document: doc, markdown, zoom: 'fit-page', labels, marks: { highlightOpacity: 0.5 },#Sottolinea invece di riempire
Per una bozza più discreta, sottolinea le affermazioni nel colore del verdetto.
- id, kind: 'highlight', range, color: VERDICTS[verdict].color, // 35 % over the text
+ id, kind: 'underline', range, color: VERDICTS[verdict].color, // under the baselineCrediti
- Ricetta
- Ignacio Ferro
- Testo
- Testo originale, CC BY 4.0
- Font
- Source Serif 4 (SIL OFL 1.1) · Source Sans 3 (SIL OFL 1.1)
- Codice
- MIT, come Postext
Modifica questo testo ↗ (si apre in una nuova scheda)Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)



