# قلم تظليل للقارئ: مقطع ولون

> تحدّد كلمات من رواية فتنفتح فوقها أربعة ألوان؛ ويمتد التظليل إلى كلمات كاملة، ويُحفظ مرساةً، وينضم إلى قائمة بجانب الصفحات.

- نسخة HTML: https://postext.dev/ar/cookbook/reader-highlighter
- وصفة رقم 223 · الدمج مع أنظمة إدارة المحتوى · المستوى 2 (متوسط) · المخرجات: Canvas
- الأنواع: الأدب القصصي والمسرح والنثر الأدبي
- تتطلب postext ≥ 1.103.0 · اختُبرت مع 1.103.1 بتاريخ 2026-12-04
- الصفحات: [1](https://postext.dev/cookbook/reader-highlighter/en/p01.webp?v=4cd29c98), [2](https://postext.dev/cookbook/reader-highlighter/en/p02.webp?v=4cd29c98), [3](https://postext.dev/cookbook/reader-highlighter/en/p03.webp?v=4cd29c98)
- ![تطبيق القراءة عند فتحه: ثلاثة مقاطع مظلَّلة بالأصفر والأزرق والوردي، والمقاطع الثلاثة نفسها في القائمة بجانب الصفحات، مع لونها وصفحتها.](https://postext.dev/cookbook/reader-highlighter/en/s01.webp?v=4cd29c98)
- ![مقطع محدَّد في الصفحة 1: لوحة الألوان الأربعة تطفو فوق سطره الأول، موضوعةً من إحداثيات الصفحة.](https://postext.dev/cookbook/reader-highlighter/en/s02.webp?v=4cd29c98)
- ![صار المقطع الجديد أخضر ودخل القائمة بترتيب القراءة؛ والضغط على التظليل الأصفر يعيد فتح اللوحة، ولونه محاط بدائرة وبجانبه زر لإزالته.](https://postext.dev/cookbook/reader-highlighter/en/s03.webp?v=4cd29c98)
- آخر تحديث: 2026-12-04
- لغات أخرى: [en](https://postext.dev/en/cookbook/reader-highlighter.md), [es](https://postext.dev/es/cookbook/reader-highlighter.md), [ca](https://postext.dev/ca/cookbook/reader-highlighter.md), [de](https://postext.dev/de/cookbook/reader-highlighter.md), [el](https://postext.dev/el/cookbook/reader-highlighter.md), [fr](https://postext.dev/fr/cookbook/reader-highlighter.md), [it](https://postext.dev/it/cookbook/reader-highlighter.md), [pt](https://postext.dev/pt/cookbook/reader-highlighter.md), [ru](https://postext.dev/ru/cookbook/reader-highlighter.md), [zh](https://postext.dev/zh/cookbook/reader-highlighter.md), [ja](https://postext.dev/ja/cookbook/reader-highlighter.md)

## باختصار

رواية في تطبيق للقراءة. حدّد بعض الكلمات فتظهر فوقها أربع نقاط ملوّنة؛ اختر واحدة فتُظلَّل الكلمات بذلك اللون. تبقى تظليلاتك محفوظة على هذا الجهاز، ومدرجة في قائمة بجانب الكتاب.

## ما الذي ستنضده

الفصل الأول من رواية قصيرة، *The Night Ferry* («عبّارة الليل»)، في تطبيق للقراءة. يمرّر القارئ إصبعه على جملة فيظهر فوقها شريط داكن فيه أربع نقاط ملوّنة. ضغطة واحدة فتُظلَّل الجملة بالأصفر أو الأخضر أو الأزرق أو الوردي، ويمتد التحديد إلى كلمات كاملة. والضغط على تظليل يعيد الشريط لتغيير لونه أو إزالته. العمود الأيمن قائمة القارئ نفسه، بترتيب القراءة، لكل مقطع لونه وصفحته. ويُحفظ كل ذلك على جهاز القارئ، في هيئة مراسٍ تظل تجد كلماتها حين يُصدر الناشر طبعة مصحَّحة.

**تجيب هذه الوصفة عن:**

- كيف أتيح للقراء تظليل مقاطع من الكتاب بألوان يختارونها؟

## الجواب المختصر

```js
// script.js, سطرًا 172–206
const view = createViewer($('viewer'), {
  document: doc, markdown, zoom: 'fit-width', maxZoom: 0.8, labels: L.viewer,
});
// A drag that starts or ends inside a word takes the whole word.
const snap = ({ start, end }) => {
  const a = wordRangeAt(markdown, start, { locale: config.locale });
  const b = wordRangeAt(markdown, end, { locale: config.locale });
  return { start: a && a.start < start && start < a.end ? a.start : start,
    end: b && b.start < end && end < b.end ? b.end : end };
};
let pending = null; // what the palette acts on: { range } for a new one, { id } for one saved
const offer = (range) => {
  pending = { range: snap(range) };
  view.setSelection(pending.range);
  openPalette(pending.range, null);
};
const pick = (pen) => {
  if (pending?.id) highlights = highlights.map((h) => (h.id === pending.id ? { ...h, pen } : h));
  else if (pending) highlights = [...highlights, { id: nextId(), pen, range: pending.range }];
  closePalette();
  view.setSelection(null);
  save();
  render();
};
const edit = (id) => {
  const h = highlights.find((x) => x.id === id);
  pending = { id };
  openPalette(h.range, h.pen);
};
view.on('select', ({ range }) => {
  if (!range || range.end <= range.start) return closePalette();
  const { start, end } = pending?.range ?? {};
  if (range.start !== start || range.end !== end) offer(range); // not the snapped one echoed back
});
view.on('annotationclick', ({ id }) => edit(id));
```

## المكونات

**تعلّم**

- [علامات التعليق](https://postext.dev/ar/docs/integration-marks.md#علامات-التعليق): تظليل وتسطير وشطب واستبدال وإدراج وملاحظات وإطارات توضع على نص الصفحات، وتُرسم على Canvas أو تُكتب SVG فوق صور الصفحات.
- [مراسٍ تبقى عبر المراجعات](https://postext.dev/ar/docs/integration-anchors.md#المراسي-والتعديلات): يحفظ textAnchor النطاق مع اقتباسه وسياقه، فيجده resolveAnchor من جديد في النص المنقَّح؛ ويكتب applyEdits التعديلات المقبولة، وينقل mapOffset المواضع الأخرى عبرها.

**تستخدم أيضًا**

- [عارض الصفحات (postext-viewer)](https://postext.dev/ar/docs/integration-viewer.md#عارض-الصفحات)
- [هندسة النص (النطاقات والنقاط)](https://postext.dev/ar/docs/integration-geometry.md#النص-على-الصفحة)
- [الخطوط قبل الإخراج](https://postext.dev/ar/docs/configuration-programmatic-usage.md#تحميل-الخطوط-قبل-الإخراج)
- [صفحات افتتاح مصمَّمة](https://postext.dev/ar/docs/configuration-headings.md#الامتداد-والتصميم-المتقدم)
- [الترويسات وأرقام الصفحات](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات)
- [هوامش متناظرة](https://postext.dev/ar/docs/configuration-page-layout.md#الهوامش-المتناظرة)
- [لوحة ألوان دلالية](https://postext.dev/ar/docs/configuration-fonts-colors-viewers.md#لوحة-الألوان)
- [سمات العنوان](https://postext.dev/ar/docs/document-format.md#سمات-العناوين)
- [الترويسات بحسب دور الصفحة](https://postext.dev/ar/docs/configuration-headers-footers.md#عناصر-النص)

**الإعدادات في لمحة**

- [`bodyText`](https://postext.dev/ar/docs/configuration-text.md#نص-المتن), [`colorPalette`](https://postext.dev/ar/docs/configuration-fonts-colors-viewers.md#لوحة-الألوان), [`footer`](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات), [`header`](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات), [`headings`](https://postext.dev/ar/docs/configuration-headings.md#العناوين), [`layout`](https://postext.dev/ar/docs/configuration-page-layout.md#التخطيط), [`locale`](https://postext.dev/ar/docs/configuration-language.md#تقسيم-الكلمات-بالواصلة), [`page`](https://postext.dev/ar/docs/configuration-page-layout.md#الصفحة)

**واجهات API**

- [`buildDocumentWithFonts`](https://postext.dev/ar/docs/configuration-programmatic-usage.md#تحميل-الخطوط-قبل-الإخراج), `createViewer`, [`renderPageToCanvas`](https://postext.dev/ar/docs/configuration-programmatic-usage.md#رسم-صفحة-في-صورة-نقطية), `resolveAnchor`, `setAnnotations`, `textAnchor`, `wordRangeAt`

**الخطوط**

- Literata (OFL-1.1), Source Sans 3 (OFL-1.1)

## طريقة التحضير

### 1 · احفظ التظليلات مراسيَ لا مواضع

```js
// script.js, سطرًا 146–168
const KEY = `${RECIPE}:${LANG}`;
const quote = (text) => { // the reader's first highlights, so the pen opens with some
  const start = markdown.indexOf(text);
  return { start, end: start + text.length };
};
const seed = t({
  en: [['yellow', 'a good sailor reads the water the way a scholar reads a book'],
    ['blue', 'Some things, Tom said, a man only writes down in the water.'],
    ['pink', 'as if he had wanted them to last']],
  es: [['yellow', 'un buen marino lee el agua como un estudioso lee un libro'],
    ['blue', 'Hay cosas, dijo Tom, que un hombre solo escribe en el agua.'],
    ['pink', 'como si él hubiera querido que duraran']],
}).map(([pen, text], i) => ({ id: `h${i + 1}`, pen, anchor: textAnchor(markdown, quote(text)) }));
const saved = JSON.parse(localStorage.getItem(KEY) ?? 'null') ?? seed;
// A new edition of the book moves the words: resolveAnchor finds each one again.
let highlights = saved.flatMap((h) => {
  const found = resolveAnchor(markdown, h.anchor);
  return found.status === 'exact' || found.status === 'moved'
    ? [{ ...h, range: { start: found.start, end: found.end } }] : [];
});
const nextId = () => `h${1 + Math.max(0, ...highlights.map((h) => Number(h.id.slice(1)) || 0))}`;
const save = () => localStorage.setItem(KEY, JSON.stringify(
  highlights.map(({ id, pen, range }) => ({ id, pen, anchor: textAnchor(markdown, range) }))));
```

يُحفظ التظليل لونًا ومرساةً من `textAnchor`: النطاق، والكلمات التي غطّاها، وشيئًا من النص على كل جانب. وحين يفتح التطبيق كتابًا، تجد `resolveAnchor` كل مرساة في النص الذي بين يديه الآن. في الطبعة نفسها يكون الجواب `exact`؛ وبعد تصحيح في الأصل يكون `moved` بمواضع جديدة، والمقطع المحذوف يصير `orphaned`، فيتركه التطبيق (أو يعرضه منفصلًا ليقرر القارئ).

### 2 · مدّ التحديد إلى كلمات كاملة واعرض الألوان

الشيفرة هي [الجواب المختصر](https://postext.dev/ar/cookbook/reader-highlighter.md#الجواب-المختصر) أعلاه. يُبلغ العارض عن كل تحديد مكتمل نطاقًا من Markdown. تمدّ `wordRangeAt` الطرف الذي يقع داخل كلمة إلى الكلمة كلها، فلا تترك حركة متعجلة نصف كلمة مظلَّلًا. ويعود النطاق المعدَّل إلى العارض عبر `setSelection`، ويتجاهل المعالج هذا الصدى، وإلا لظل يعرض اللوحة بلا نهاية.

### 3 · ضع اللوحة فوق المقطع

```js
// script.js, سطرًا 210–248
const bar = $('palette');
for (const [pen, { color, name }] of Object.entries(PENS)) {
  const b = Object.assign(document.createElement('button'), { type: 'button', title: name });
  b.dataset.pen = pen;
  b.style.setProperty('--pen', color);
  b.setAttribute('aria-label', L.pen(name));
  b.addEventListener('click', () => pick(pen));
  bar.insertBefore(b, $('remove'));
}
$('remove').textContent = L.remove;
$('remove').addEventListener('click', () => {
  highlights = highlights.filter((h) => h.id !== pending?.id);
  closePalette();
  save();
  render();
});
function openPalette(range, current) {
  for (const b of bar.querySelectorAll('[data-pen]')) b.setAttribute('aria-pressed', String(b.dataset.pen === current));
  $('remove').hidden = !current;
  bar.hidden = false;
  bar.dataset.range = `${range.start}-${range.end}`;
  place();
}
function closePalette() {
  pending = null;
  bar.hidden = true;
}
// Above the passage's first line, centred on it, in the window's px.
function place() {
  if (bar.hidden) return;
  const [start, end] = bar.dataset.range.split('-').map(Number);
  const first = view.rangeRects({ start, end })[0];
  const at = first && view.pageToClient(first.pageIndex, first.rect.x + first.rect.width / 2, first.rect.y);
  if (!at) return void (bar.hidden = true);
  Object.assign(bar.style, { left: `${at.x}px`, top: `${at.y - 10}px` });
}
view.on('zoomchange', place);
view.element.addEventListener('scroll', place, { capture: true, passive: true });
addEventListener('keydown', (e) => e.key === 'Escape' && closePalette());
```

تعطي `rangeRects` السطر الأول من المقطع بوحدات بكسل الصفحة، وتحوّله `pageToClient` إلى بكسل النافذة، فيستقر الشريط في الوسط فوق الكلمات مع أي تكبير. ويتحرك معها عند `zoomchange` وعند التمرير. والشريط HTML من التطبيق نفسه: يتبع تصميمه، ولأزراره أسماء تقرؤها قارئات الشاشة.

### 4 · اعرض في قائمة ما علّمه القارئ

```js
// script.js, سطرًا 252–271
function render() {
  highlights.sort((a, b) => a.range.start - b.range.start);
  view.setAnnotations(highlights.map(({ id, pen, range }) => ({
    id, kind: 'highlight', range, color: PENS[pen].color,
  })));
  $('count').textContent = highlights.length ? L.count(highlights.length) : L.empty;
  $('list').replaceChildren(...highlights.map(({ id, pen, range }) => {
    const item = document.createElement('button');
    item.type = 'button';
    item.style.setProperty('--pen', PENS[pen].color);
    item.innerHTML = '<q></q><small></small>';
    item.querySelector('q').textContent = markdown.slice(range.start, range.end).replace(/[*_]/g, '');
    const page = view.rangeRects(range)[0]?.pageIndex;
    item.querySelector('small').textContent = `${PENS[pen].name} · ${L.page(page + 1)}`;
    item.addEventListener('click', () => view.revealAnnotation(id, { behavior: 'smooth' }));
    return item;
  }));
}
$('title').textContent = L.title;
render();
```

ترسم `setAnnotations` كل تظليل بلونه؛ والقائمة هي السجلات نفسها مرتبةً بحسب الموضع، مع الصفحة التي تعطيها `rangeRects`. والضغط على بند يستدعي `revealAnnotation`، فتُمرَّر كلماته إلى مجال الرؤية.

## الوصفة كاملة

تُركَّب الملفات أدناه من مجلد الوصفة، ومعها نص المثال وأدوات دليل الوصفات المشتركة مضمّنة. لتشغيلها صفحةً واحدة، ضع HTML داخل `<body>`، وCSS داخل عنصر `<style>`، والسكربت داخل `<script type="module">`؛ أو الصق كلًّا منها في اللوحة المقابلة من مثال CodePen جديد (مع ضبط JS وحدةً). يستورد السكربت postext من esm.sh، فلا حاجة إلى تثبيت أو بناء.

- مجلد الوصفة: https://github.com/drnachio/postext/tree/main/cookbook/reader-highlighter

### index.html

```html
<main id="pages">
  <div id="viewer"></div>
  <aside id="panel">
    <h2 id="title"></h2>
    <p id="count"></p>
    <div id="list"></div>
  </aside>
  <div id="palette" role="toolbar" hidden>
    <button id="remove" type="button"></button>
  </div>
</main>
```

### style.css

```css
/* A reading app: the pages on a warm desk, the reader's highlights in a column beside them.
   The viewer fills its container, so the container gets a height. */
main#pages {
  display: grid; grid-template-columns: minmax(0, 1fr) 330px; height: max(560px, 100vh);
  justify-items: stretch; gap: 0; padding: 0; font: 15px/1.45 system-ui, sans-serif; color: #22201d;
  color-scheme: light;
}
#viewer { min-height: 0; }
#viewer .postext-viewer {
  --pv-background: #ebe6de; --pv-focus: #7a3e2b; --pv-selection: rgb(122 62 43 / .22);
}
#panel { overflow: auto; padding: 26px 22px; background: #fbf9f6; border-left: 1px solid #ddd6cc; }
#panel h2 { margin: 0; font: 600 22px/1.2 Literata, Georgia, serif; }
#count { margin: 4px 0 18px; font-size: 13px; color: #77706a; }
#list { display: grid; gap: 10px; }
#list button {
  display: grid; gap: 6px; min-height: 44px; padding: 12px 14px 11px 16px; text-align: left;
  background: #fff; border: 1px solid #e3ddd3; border-radius: 10px; cursor: pointer;
  box-shadow: inset 4px 0 0 var(--pen), 0 1px 2px rgb(60 40 20 / .06); color: inherit; font: inherit;
}
#list button:hover { border-color: var(--pen); }
#list button:focus-visible { outline: 2px solid #7a3e2b; outline-offset: 2px; }
#list q { font: italic 15px/1.45 Literata, Georgia, serif; quotes: '“' '”'; }
#list small { font-size: 12px; font-weight: 600; letter-spacing: .02em; color: #77706a; }
/* The palette floats over the passage: placed in window px from pageToClient, so fixed. */
#palette {
  position: fixed; z-index: 2; display: flex; align-items: center; gap: 6px; padding: 6px;
  transform: translate(-50%, -100%); background: #2a2622; border-radius: 999px;
  box-shadow: 0 12px 28px -10px rgb(0 0 0 / .55);
}
#palette[hidden] { display: none; }
#palette::after {
  content: ''; position: absolute; left: 50%; bottom: -5px; width: 10px; height: 10px;
  margin-left: -5px; background: #2a2622; transform: rotate(45deg);
}
#palette [data-pen] {
  width: 44px; height: 44px; padding: 0; border: 0; border-radius: 50%; cursor: pointer;
  background: radial-gradient(circle, var(--pen) 0 13px, transparent 14px);
}
#palette [data-pen]:hover, #palette [aria-pressed='true'] {
  background: radial-gradient(circle, var(--pen) 0 13px, transparent 14px 16px, #fff 17px 18px, transparent 19px);
}
#palette button:focus-visible { outline: 2px solid #fff; outline-offset: -3px; }
#remove {
  min-height: 44px; padding: 0 16px; margin-left: 2px; border: 0; border-left: 1px solid #4a443e;
  border-radius: 0 999px 999px 0; background: none; color: #f4efe8; font: 600 14px system-ui, sans-serif;
  cursor: pointer;
}
#remove[hidden] { display: none; }
```

### script.js

```js
// ═══ Postext Cookbook · Nº 223 · A reader's highlighter ══════════════════════════════
// https://postext.dev/en/cookbook/reader-highlighter
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Literata, Source Sans 3 (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// The first chapter of a novel in a reading app. Select a passage and a palette of four
// colours appears over it; pick one and the passage is highlighted, snapped to whole words,
// and saved on this device as an anchor. Press a highlight to change its colour or remove
// it. The list beside the pages holds every passage, in reading order.
import { buildDocumentWithFonts, renderPageToCanvas, wordRangeAt } from 'https://esm.sh/postext';
import { textAnchor, resolveAnchor } from 'https://esm.sh/postext/annotate';
import { createViewer } from 'https://esm.sh/postext-viewer';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'reader-highlighter';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#22201d', // text
  accent: '#7a3e2b', // rust: kicker, rule and folio
  muted: '#77706a', // 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

// #region page: a trade paperback, the chapter opener sunk below a kicker and a short rule
const opener = {
  enabled: true,
  minHeight: mm(46),
  slot: { elements: [
    { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: 'Source Sans 3',
      fontSize: pt(8), fontWeight: 700, letterSpacing: pt(1.6), textTransform: 'uppercase',
      color: col('accent'), align: 'left',
      placement: { anchor: { to: 'container', edge: 'top-left' }, offset: { x: mm(0), y: mm(10) } } },
    { kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Literata',
      fontSize: pt(25), lineHeight: 1.1, fontWeight: 600, color: col('ink'), align: 'left',
      placement: { anchor: { to: '#kicker', edge: 'below' }, offset: { x: mm(0), y: mm(3) },
        size: { width: mm(90), height: 'auto' } } },
    { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(1.5), color: col('accent'),
      placement: { anchor: { to: '#title', edge: 'below' }, offset: { x: mm(0), y: mm(5) },
        size: { width: mm(12) } } },
  ] },
};
const head = (id, content, parity, edge, x, extra = {}) => ({
  kind: 'text', id, content, parity, pages: 'body', fontFamily: 'Source Sans 3',
  fontSize: pt(7.5), fontWeight: 600, letterSpacing: pt(1.2), textTransform: 'uppercase',
  color: col('muted'), placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(12) } },
  ...extra,
});
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(129), height: mm(198), dpi: 150,
    margins: { top: mm(20), bottom: mm(22), left: mm(18), right: mm(15), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Literata', fontSize: pt(10), lineHeight: pt(14.5),
    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: 'Literata', color: col('ink'), fontWeight: 600, levels: [
    { level: 1, fontSize: pt(25), advancedDesign: opener },
  ] },
  header: { elements: [
    head('verso-folio', '{pageNumber}', 'even', 'top-left', 15, { color: col('accent'), fontWeight: 700 }),
    head('verso-title', '{title}', 'even', 'top-left', 23),
    head('recto-title', '{chapterTitle}', 'odd', 'top-right', -23),
    head('recto-folio', '{pageNumber}', 'odd', 'top-right', -15, { color: col('accent'), fontWeight: 700 }),
  ] },
  // The opener drops its folio to the foot, where no running head crowds the title.
  footer: { elements: [head('drop-folio', '{pageNumber}', 'all', 'bottom', 0, {
    pages: 'opener', color: col('accent'), fontWeight: 700,
    placement: { anchor: { to: 'page', edge: 'bottom' }, offset: { x: mm(0), y: mm(-11) } },
  })] },
};
// #endregion

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "The Night Ferry"
author: "Ines Calder"
---

# The Night Ferry {kicker="Chapter one"}

The ferry left at ten, whatever the weather, and on most nights Agnes Lowe was the only passenger who stayed on deck. She liked the cold. She liked the way the town shrank behind the boat until it was a handful of yellow windows, then a line, then nothing at all.

Her father had worked the crossing for thirty-one years. He knew the channel by its sounds: the slap of the tide against the north buoy, the long groan of the chain at the landing, the gulls that only cried when rain was coming. When she was small he had told her that a good sailor reads the water the way a scholar reads a book, slowly, and with a pencil in his hand.

She had not understood him then. She understood him now, on the night she carried his logbook across the water to give it back to the harbour office. Every page was full of small marks. A tick where the light at the point was late. A cross where the engine coughed. Once, in the margin beside an entry for a calm October night, three words in his careful capitals: *saw the whales*.

The office would want the numbers, the dates and the fuel. They would not want the whales. Agnes had decided, somewhere between the ticket booth and the rail, that she would copy those three words into her own notebook before she handed anything over.

The engine changed its note as the boat came round the point. Ahead, the island showed its one street lamp and the white shape of the chapel. A man in an orange coat was waiting at the landing with a rope coiled over his arm, and she knew without seeing his face that it was Tom Harker, who had been her father's deckhand and had never once been late.

"You brought it," he said, when the gangway was down.

"I brought it."

He did not ask to see the book. He walked beside her up the slope to the harbour office, where a light still burned, and he told her about the winter the ice had come into the channel and her father had broken it with a boathook for two hours so the doctor could get across. It was not in the logbook. Some things, Tom said, a man only writes down in the water.

At the office door she stopped and opened the book at the October page. The capitals were smaller than she remembered, pressed hard into the paper, as if he had wanted them to last. She read them twice and closed the cover.

Inside, the clerk thanked her and gave her a receipt, and the book went into a grey box with a number on the side. That was all. When she came out, Tom was looking at the dark water past the landing, and for a moment neither of them spoke.

Then something rose out there, a long black back in the moonlight, and sank again without a sound.
`; // content.<lang>.md, inlined by the Cookbook

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

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown }, config, kitFonts(FONTS));
kitStatus(t({ en: 'The Night Ferry · your highlights', es: 'El ferri de la noche · tus resaltados' }));

// #region colours: the reader's four pens, named for the buttons and the list
const PENS = {
  yellow: { color: '#e0a800', name: t({ en: 'Yellow', es: 'Amarillo' }) },
  green: { color: '#3c9a55', name: t({ en: 'Green', es: 'Verde' }) },
  blue: { color: '#2f7fd6', name: t({ en: 'Blue', es: 'Azul' }) },
  pink: { color: '#d64c86', name: t({ en: 'Pink', es: 'Rosa' }) },
};
// #endregion
const L = t({
  en: { title: 'Highlights', count: (n) => `${n} passage${n === 1 ? '' : 's'} · saved on this device`,
    page: (p) => `Page ${p}`, remove: 'Remove', pen: (name) => `Highlight in ${name.toLowerCase()}`,
    empty: 'Select a passage on the page to highlight it.', viewer: {} },
  es: { title: 'Resaltados', count: (n) => `${n} ${n === 1 ? 'pasaje' : 'pasajes'} · guardados en este dispositivo`,
    page: (p) => `Página ${p}`, remove: 'Quitar', pen: (name) => `Resaltar en ${name.toLowerCase()}`,
    empty: 'Selecciona un pasaje de la página para resaltarlo.',
    viewer: { viewer: 'Páginas del libro', page: 'Página {n} de {count}',
      selection: '{count} caracteres seleccionados', selectionCleared: 'Selección borrada',
      kinds: { highlight: 'Resaltado' } } },
});
const $ = (id) => document.getElementById(id);

// #region store: highlights kept as anchors, found again in the text the app has now
const KEY = `${RECIPE}:${LANG}`;
const quote = (text) => { // the reader's first highlights, so the pen opens with some
  const start = markdown.indexOf(text);
  return { start, end: start + text.length };
};
const seed = t({
  en: [['yellow', 'a good sailor reads the water the way a scholar reads a book'],
    ['blue', 'Some things, Tom said, a man only writes down in the water.'],
    ['pink', 'as if he had wanted them to last']],
  es: [['yellow', 'un buen marino lee el agua como un estudioso lee un libro'],
    ['blue', 'Hay cosas, dijo Tom, que un hombre solo escribe en el agua.'],
    ['pink', 'como si él hubiera querido que duraran']],
}).map(([pen, text], i) => ({ id: `h${i + 1}`, pen, anchor: textAnchor(markdown, quote(text)) }));
const saved = JSON.parse(localStorage.getItem(KEY) ?? 'null') ?? seed;
// A new edition of the book moves the words: resolveAnchor finds each one again.
let highlights = saved.flatMap((h) => {
  const found = resolveAnchor(markdown, h.anchor);
  return found.status === 'exact' || found.status === 'moved'
    ? [{ ...h, range: { start: found.start, end: found.end } }] : [];
});
const nextId = () => `h${1 + Math.max(0, ...highlights.map((h) => Number(h.id.slice(1)) || 0))}`;
const save = () => localStorage.setItem(KEY, JSON.stringify(
  highlights.map(({ id, pen, range }) => ({ id, pen, anchor: textAnchor(markdown, range) }))));
// #endregion

// #region answer: a selection, snapped to whole words, offered the four pens
const view = createViewer($('viewer'), {
  document: doc, markdown, zoom: 'fit-width', maxZoom: 0.8, labels: L.viewer,
});
// A drag that starts or ends inside a word takes the whole word.
const snap = ({ start, end }) => {
  const a = wordRangeAt(markdown, start, { locale: config.locale });
  const b = wordRangeAt(markdown, end, { locale: config.locale });
  return { start: a && a.start < start && start < a.end ? a.start : start,
    end: b && b.start < end && end < b.end ? b.end : end };
};
let pending = null; // what the palette acts on: { range } for a new one, { id } for one saved
const offer = (range) => {
  pending = { range: snap(range) };
  view.setSelection(pending.range);
  openPalette(pending.range, null);
};
const pick = (pen) => {
  if (pending?.id) highlights = highlights.map((h) => (h.id === pending.id ? { ...h, pen } : h));
  else if (pending) highlights = [...highlights, { id: nextId(), pen, range: pending.range }];
  closePalette();
  view.setSelection(null);
  save();
  render();
};
const edit = (id) => {
  const h = highlights.find((x) => x.id === id);
  pending = { id };
  openPalette(h.range, h.pen);
};
view.on('select', ({ range }) => {
  if (!range || range.end <= range.start) return closePalette();
  const { start, end } = pending?.range ?? {};
  if (range.start !== start || range.end !== end) offer(range); // not the snapped one echoed back
});
view.on('annotationclick', ({ id }) => edit(id));
// #endregion

// #region bar: the floating palette, placed over the passage from page coordinates
const bar = $('palette');
for (const [pen, { color, name }] of Object.entries(PENS)) {
  const b = Object.assign(document.createElement('button'), { type: 'button', title: name });
  b.dataset.pen = pen;
  b.style.setProperty('--pen', color);
  b.setAttribute('aria-label', L.pen(name));
  b.addEventListener('click', () => pick(pen));
  bar.insertBefore(b, $('remove'));
}
$('remove').textContent = L.remove;
$('remove').addEventListener('click', () => {
  highlights = highlights.filter((h) => h.id !== pending?.id);
  closePalette();
  save();
  render();
});
function openPalette(range, current) {
  for (const b of bar.querySelectorAll('[data-pen]')) b.setAttribute('aria-pressed', String(b.dataset.pen === current));
  $('remove').hidden = !current;
  bar.hidden = false;
  bar.dataset.range = `${range.start}-${range.end}`;
  place();
}
function closePalette() {
  pending = null;
  bar.hidden = true;
}
// Above the passage's first line, centred on it, in the window's px.
function place() {
  if (bar.hidden) return;
  const [start, end] = bar.dataset.range.split('-').map(Number);
  const first = view.rangeRects({ start, end })[0];
  const at = first && view.pageToClient(first.pageIndex, first.rect.x + first.rect.width / 2, first.rect.y);
  if (!at) return void (bar.hidden = true);
  Object.assign(bar.style, { left: `${at.x}px`, top: `${at.y - 10}px` });
}
view.on('zoomchange', place);
view.element.addEventListener('scroll', place, { capture: true, passive: true });
addEventListener('keydown', (e) => e.key === 'Escape' && closePalette());
// #endregion

// #region list: every highlight in reading order, with its page; a press shows it
function render() {
  highlights.sort((a, b) => a.range.start - b.range.start);
  view.setAnnotations(highlights.map(({ id, pen, range }) => ({
    id, kind: 'highlight', range, color: PENS[pen].color,
  })));
  $('count').textContent = highlights.length ? L.count(highlights.length) : L.empty;
  $('list').replaceChildren(...highlights.map(({ id, pen, range }) => {
    const item = document.createElement('button');
    item.type = 'button';
    item.style.setProperty('--pen', PENS[pen].color);
    item.innerHTML = '<q></q><small></small>';
    item.querySelector('q').textContent = markdown.slice(range.start, range.end).replace(/[*_]/g, '');
    const page = view.rangeRects(range)[0]?.pageIndex;
    item.querySelector('small').textContent = `${PENS[pen].name} · ${L.page(page + 1)}`;
    item.addEventListener('click', () => view.revealAnnotation(id, { behavior: 'smooth' }));
    return item;
  }));
}
$('title').textContent = L.title;
render();
// #endregion

// The states the Cookbook photographs: a passage offered the pens, then one opened again.
kitShots({
  select: () => {
    const range = quote(t({ en: 'three words in his careful capitals',
      es: 'tres palabras en sus mayúsculas cuidadosas' }));
    view.revealRange(range);
    offer(range);
  },
  change: () => { pick('green'); view.revealAnnotation('h1'); edit('h1'); },
});

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

## تنويعات

### سطّر بلون القارئ

يفضّل بعض القراء خطًا على التعبئة، والخط يحفظ تباين النص على أي ورق.

```diff
-    id, kind: 'highlight', range, color: PENS[pen].color,
+    id, kind: 'underline', range, color: PENS[pen].color,
```

### اكتب ملاحظة على تظليل

التظليل الذي يحمل ملاحظة أيضًا يصير راية في الهامش: تبني [دفتر القارئ: ملاحظات على ما يحدده من نص](https://postext.dev/ar/cookbook/reader-notebook.md) الدفتر على المراسي نفسها.

## الحقوق

- الوصفة: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- الخطوط: Literata (OFL-1.1), Source Sans 3 (OFL-1.1)
- الشيفرة: MIT · محتوى المثال: CC-BY-4.0

## وصفات ذات صلة

- [رقم 213 · تظليل انطلاقًا من قائمة نطاقات](https://postext.dev/ar/cookbook/highlights-from-ranges.md): سجلات أداة مراجعة، كلٌّ منها نطاق في Markdown وحكم، تُرسَم على الصفحات المُخرَجة تظليلًا بثلاثة ألوان باستخدام setAnnotations. · المستوى 1 (أساسي) · الجرائد والنشرات
- [رقم 212 · حدِّد على الصفحة واقرأ نطاق Markdown ونصّه](https://postext.dev/ar/cookbook/selection-as-markdown-range.md): يُبلغ postext-viewer عن التحديد على الصفحات المُخرَجة نطاقًا في Markdown، مع نص Markdown الذي يغطيه وقطعه سطرًا سطرًا. · المستوى 1 (أساسي) · المجلات والمجلات المستقلة
- [رقم 217 · مراسٍ عبر مراجعة: موجودة أو منقولة أو ملتبسة أو يتيمة](https://postext.dev/ar/cookbook/anchors-through-a-revision.md): تحفظ textAnchor كل ملاحظة مع كلماتها وسياقها، وتجدها resolveAnchor في المراجعة التالية: في مكانها أو منقولة أو ملتبسة أو يتيمة. · المستوى 2 (متوسط) · الأدلة والمراجع
