# Επισημάνσεις από μια λίστα ευρών

> Οι εγγραφές ενός εργαλείου ελέγχου, η καθεμιά ένα εύρος του Markdown και μια ετυμηγορία, ως επισημάνσεις σε τρία χρώματα με setAnnotations.

- Έκδοση HTML: https://postext.dev/el/cookbook/highlights-from-ranges
- Συνταγή Αρ. 213 · Ενσωμάτωση σε CMS · Επίπεδο 1 (Βασικό) · Έξοδοι: Canvas
- Είδη: Εφημερίδες και ενημερωτικά δελτία
- Απαιτεί postext ≥ 1.103.0 · δοκιμασμένη με 1.103.1 στις 2026-12-04
- Σελίδες: [1](https://postext.dev/cookbook/highlights-from-ranges/en/p01.webp?v=3c91b3b4)
- ![Πέντε ισχυρισμοί σε ένα δελτίο, χρωματισμένοι ανάλογα με την ετυμηγορία: ελεγμένοι σε κίτρινο, όσοι θέλουν πηγή σε μπλε, ερώτηση προς τον συγγραφέα σε ροζ, και ο καθένας γραμμένος και στη λίστα δίπλα στις σελίδες.](https://postext.dev/cookbook/highlights-from-ranges/en/s01.webp?v=3c91b3b4)
- Τελευταία ενημέρωση: 2026-12-04
- Άλλες γλώσσες: [en](https://postext.dev/en/cookbook/highlights-from-ranges.md), [es](https://postext.dev/es/cookbook/highlights-from-ranges.md), [ca](https://postext.dev/ca/cookbook/highlights-from-ranges.md), [de](https://postext.dev/de/cookbook/highlights-from-ranges.md), [fr](https://postext.dev/fr/cookbook/highlights-from-ranges.md), [it](https://postext.dev/it/cookbook/highlights-from-ranges.md), [pt](https://postext.dev/pt/cookbook/highlights-from-ranges.md), [ru](https://postext.dev/ru/cookbook/highlights-from-ranges.md), [zh](https://postext.dev/zh/cookbook/highlights-from-ranges.md), [ja](https://postext.dev/ja/cookbook/highlights-from-ranges.md), [ar](https://postext.dev/ar/cookbook/highlights-from-ranges.md)

## Με λίγα λόγια

Ένα άρθρο για τα πλατάνια του Λονδίνου, όπως το βλέπει ο ελεγκτής γεγονότων: οι ελεγμένες φράσεις είναι σκιασμένες κίτρινες, μπλε ή ροζ ανάλογα με την ετυμηγορία, και μια λίστα δίπλα τις ονομάζει. Ένα κλικ οδηγεί σε αυτές.

## Τι θα στοιχειοθετήσετε

Ένα άρθρο ενημερωτικού δελτίου για το πλατάνι του Λονδίνου, όπως το βλέπει η ομάδα ελέγχου γεγονότων σε ένα εργαλείο ελέγχου. Πέντε φράσεις έχουν ετυμηγορία: κίτρινο για ό,τι ελέγχθηκε, μπλε όπου ο συγγραφέας χρωστά ακόμη πηγή, ροζ για ερώτηση προς τον συγγραφέα. Οι επισημάνσεις κάθονται πάνω στη σελιδοποιημένη σελίδα, σπασμένες όπου η φράση αλλάζει γραμμή, και η λίστα στα δεξιά κρατά τις ίδιες πέντε εγγραφές με σειρά ανάγνωσης. Πατήστε μια εγγραφή και η προβολή φέρνει τις λέξεις της μπροστά σας.

**Αυτή η συνταγή απαντά:**

- Πώς σχεδιάζω επισημάνσεις στις σελίδες από μια λίστα εύρων του Markdown;

## Η σύντομη απάντηση

```js
// script.js, γραμμές 112–128
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);
}
```

## Υλικά

**Διδάσκει**

- [Σημάδια σχολιασμού](https://postext.dev/el/docs/integration-marks.md#σημάνσεις-σχολιασμού): Επισημάνσεις, υπογραμμίσεις, διαγραφές, αντικαταστάσεις, προσθήκες, σημειώσεις και πλαίσια πάνω στο κείμενο των σελίδων, ζωγραφισμένα σε καμβά ή γραμμένα ως SVG πάνω σε εικόνες σελίδων.
- [Πρόγραμμα προβολής σελίδων (postext-viewer)](https://postext.dev/el/docs/integration-viewer.md#το-πρόγραμμα-προβολής-σελίδων): Το postext-viewer δείχνει τις σελίδες ενός σελιδοποιημένου εγγράφου σε μια στήλη με κύλιση μέσα στη σελίδα μιας άλλης εφαρμογής: ζουμ, πλοήγηση στις σελίδες, επιλογές που επιστρέφουν ως εύρη Markdown, σημάδια και επίπεδα πάνω στο κείμενο.

**Χρησιμοποιεί επίσης**

- [Γραμματοσειρές πριν από τη σελιδοποίηση](https://postext.dev/el/docs/configuration-programmatic-usage.md#φόρτωση-γραμματοσειρών-πριν-από-τη-σελιδοποίηση)

**Η διαμόρφωση με μια ματιά**

- [`bodyText`](https://postext.dev/el/docs/configuration-text.md#κυρίως-κείμενο), [`colorPalette`](https://postext.dev/el/docs/configuration-fonts-colors-viewers.md#παλέτα-χρωμάτων), [`footer`](https://postext.dev/el/docs/configuration-headers-footers.md#κεφαλίδες-και-υποσέλιδα), [`header`](https://postext.dev/el/docs/configuration-headers-footers.md#κεφαλίδες-και-υποσέλιδα), [`headings`](https://postext.dev/el/docs/configuration-headings.md#επικεφαλίδες), [`layout`](https://postext.dev/el/docs/configuration-page-layout.md#διάταξη), [`locale`](https://postext.dev/el/docs/configuration-language.md#συλλαβισμός), [`page`](https://postext.dev/el/docs/configuration-page-layout.md#σελίδα)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/el/docs/configuration-programmatic-usage.md#φόρτωση-γραμματοσειρών-πριν-από-τη-σελιδοποίηση), `createViewer`, [`renderPageToCanvas`](https://postext.dev/el/docs/configuration-programmatic-usage.md#απόδοση-σελίδας-σε-bitmap), `setAnnotations`

**Γραμματοσειρές**

- Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)

## Προετοιμασία

### 1 · Κρατήστε τις εγγραφές ως εύρη

```js
// script.js, γραμμές 85–103
// 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 } };
});
```

Μια εγγραφή είναι ό,τι αποθηκεύει ήδη το εργαλείο: ένα εύρος `{ start, end }` στο Markdown του κεφαλαίου και την ετυμηγορία του ελεγκτή. Τα σημάδια δεν ξέρουν τίποτα από ετυμηγορίες· ο ιστότοπος κάνει την καθεμιά χρώμα. Εδώ οι θέσεις βγαίνουν από παράθεση του κειμένου, ώστε να τρέχουν και η αγγλική και η ισπανική έκδοση· ένα σύστημα περιεχομένου θα τις διάβαζε από τη βάση του.

### 2 · Ζωγραφίστε τες ως επισημάνσεις

Ο κώδικας είναι [η σύντομη απάντηση](https://postext.dev/el/cookbook/highlights-from-ranges.md#η-σύντομη-απάντηση) παραπάνω. Η `setAnnotations` αντικαθιστά τα σημάδια που δείχνει η προβολή· κάθε επισήμανση είναι ένα διαφανές γέμισμα πάνω σε κάθε κομμάτι του εύρους της, στο 35 % του `color`, οπότε το κείμενο από κάτω μένει μαύρο. Καλέστε την ξανά με τη νέα λίστα όταν αλλάξουν οι εγγραφές, και η προβολή ξαναζωγραφίζει μόνο τις ορατές σελίδες. Η λίστα στα δεξιά είναι οι ίδιες εγγραφές: η `revealAnnotation` φέρνει ένα σημάδι στο οπτικό πεδίο με το id που του έδωσε ο ιστότοπος.

### 3 · Ονομάστε τα σημάδια στη γλώσσα του αναγνώστη

```js
// script.js, γραμμές 107–108
const labels = t({ en: {}, es: { viewer: 'Páginas del boletín', page: 'Página {n} de {count}',
  kinds: { highlight: 'Resaltado' } } });
```

Η προβολή κάνει κάθε σημάδι κουμπί για το πληκτρολόγιο, με όνομα από τα `labels.kinds` και το σημαδεμένο κείμενο, οπότε ένας αναγνώστης οθόνης ανακοινώνει «Highlight: set out in 1789». Η ισπανική έκδοση περνά δικά της ονόματα· η αγγλική δεν χρειάζεται κανένα.

## Η πλήρης συνταγή

Τα παρακάτω αρχεία συντίθενται από τον φάκελο της συνταγής, με το δείγμα κειμένου και το κοινό κιτ του Συνταγολογίου ενσωματωμένα. Για να τα εκτελέσετε ως μία σελίδα, βάλτε την HTML στο `<body>`, το CSS σε ένα στοιχείο `<style>` και το script σε ένα `<script type="module">`· ή επικολλήστε το καθένα στο αντίστοιχο πάνελ ενός νέου CodePen (το JS ως module). Το script εισάγει το postext από το esm.sh, οπότε δεν χρειάζεται εγκατάσταση ούτε build.

- Φάκελος πηγής: https://github.com/drnachio/postext/tree/main/cookbook/highlights-from-ranges

### index.html

```html
<main id="pages">
  <div id="viewer"></div>
  <aside id="panel">
    <h2 id="heading"></h2>
    <div id="claims"></div>
  </aside>
</main>
```

### style.css

```css
/* 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; }
```

### script.js

```js
// ═══ 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) } } },
  ] },
};
// #endregion

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "Street Trees"
author: "Owen Hartley"
---

# The tree that took the smoke

The London plane lines more streets in the city than any other tree. It is a hybrid of the oriental plane of the eastern Mediterranean and the American sycamore, which reached England from Virginia in the seventeenth century. The cross was first recorded in that century, perhaps in Spain, perhaps in an English garden where the two parents grew side by side. Neither parent does well in a crowded city; their offspring does.

Its defence is in the bark. A plane sheds its outer bark in large flakes, leaving the trunk patched in olive, cream and grey. In the coal-burning city of the nineteenth century, soot settled on every surface and clogged the pores of most trees; the plane threw its dirty bark away with the soot on it. Its broad, glossy leaves wash clean in the rain, and its roots put up with compacted soil and paving.

## Planted in the squares

The oldest planes in London stand in Berkeley Square, set out in 1789. Victorian planners used the tree along the new Embankment and in the parks, and in the central boroughs it became the commonest street tree. Councils now plant a wider mix of species, so that a single disease cannot strip a whole street.

## What it costs

The plane is not free of trouble. The fine hairs on its seed balls and young leaves irritate eyes and throats in spring, and a large tree drops a heavy load of leaves that are slow to rot. Its roots can lift pavements. Massaria, a fungal disease first recorded in London in 2008, kills branches high in the crown, which can fall without warning, so the city’s arborists now inspect mature planes every year from the ground and from a lift.
`; // content.<lang>.md, inlined by the Cookbook

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = {
  'Source Serif 4': ['400'],
  'Source Sans 3': ['700'],
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown }, config, kitFonts(FONTS));
kitStatus(t({ en: 'Street Trees · checked claims', es: 'Árboles de calle · datos revisados' }));

// #region records: the desk's records, as a content system keeps them
// 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 } };
});
// #endregion

// #region labels: each mark is a button for the keyboard, named "Highlight: set out in 1789"
const labels = t({ en: {}, es: { viewer: 'Páginas del boletín', page: 'Página {n} de {count}',
  kinds: { highlight: 'Resaltado' } } });
// #endregion

// #region answer: one highlight per record, coloured by its verdict, and the same records listed
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);
}
// #endregion
document.getElementById('heading').textContent = t({ en: 'Claims', es: 'Datos' });

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

## Παραλλαγές

### Πιο έντονα γεμίσματα

Σε κρεμ ή χρωματιστή σελίδα ένα γέμισμα 35 % μπορεί να φαίνεται αχνό.

```diff
-  document: doc, markdown, zoom: 'fit-page', labels,
+  document: doc, markdown, zoom: 'fit-page', labels, marks: { highlightOpacity: 0.5 },
```

### Υπογράμμιση αντί για γέμισμα

Για πιο ήσυχο δοκίμιο, υπογραμμίστε τις φράσεις στο χρώμα της ετυμηγορίας.

```diff
-  id, kind: 'highlight', range, color: VERDICTS[verdict].color, // 35 % over the text
+  id, kind: 'underline', range, color: VERDICTS[verdict].color, // under the baseline
```

## Ευχαριστίες

- Συνταγή: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Γραμματοσειρές: Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)
- Κώδικας: MIT · Δείγμα περιεχομένου: CC-BY-4.0

## Σχετικές συνταγές

- [Αρ. 219 · Αποτελέσματα αναζήτησης πάνω στις σελίδες](https://postext.dev/el/cookbook/search-results-on-pages.md): Ένα πεδίο αναζήτησης βρίσκει το ερώτημα στο Markdown, σχεδιάζει κάθε εύρημα ως επισήμανση στις σελίδες και τα διατρέχει με τη revealAnnotation. · Επίπεδο 2 (Μεσαίο) · Οποιοδήποτε είδος
- [Αρ. 215 · Σημειώσεις στο περιθώριο, με αναδυόμενο από τη σελίδα](https://postext.dev/el/cookbook/margin-notes-with-popovers.md): Οι σημειώσεις χρωματίζουν τις λέξεις τους και βάζουν σημαία στο περιθώριο· ένα πάτημα τις ανοίγει σε αναδυόμενο με rangeRects και pageToClient. · Επίπεδο 2 (Μεσαίο) · Κατάλογοι
- [Αρ. 220 · Σημάνσεις σε SVG πάνω σε εικόνες σελίδων, για μια αναφορά](https://postext.dev/el/cookbook/marks-as-svg-over-pages.md): Οι layoutAnnotations και annotationsSvg βάζουν σημάνσεις διορθωτή πάνω σε εικόνες σελίδων, χωρίς πρόγραμμα προβολής: αναφορά που ένα CMS στέλνει με email. · Επίπεδο 2 (Μεσαίο) · Εφημερίδες και ενημερωτικά δελτία
