انتقل إلى المحتوى الرئيسي
الوصفة رقم 223

دليل الوصفات · الفصل 13 · الدمج مع أنظمة إدارة المحتوى

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

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

في هذه الصفحة
المُخرَج
Canvas
المستوى
متوسط
Postext
اختُبرت مع Postext 1.103.1
تتطلب ≥ 1.103.0
الترخيص
حُدّثت في 4 ديسمبر 2026
الشيفرة MIT · النص CC BY 4.0
تطبيق القراءة عند فتحه: ثلاثة مقاطع مظلَّلة بالأصفر والأزرق والوردي، والمقاطع الثلاثة نفسها في القائمة بجانب الصفحات، مع لونها وصفحتها.
تطبيق القراءة عند فتحه: ثلاثة مقاطع مظلَّلة بالأصفر والأزرق والوردي، والمقاطع الثلاثة نفسها في القائمة بجانب الصفحات، مع لونها وصفحتها.
  • نموذج باللغة الإنجليزية: لا توجد طبعة عربية بعد
  • مقاس القص 129 × 198 مم
  • عمود واحد
  • Literata 10/14.5
  • Source Sans 3
  • 3 صفحات
  • المستوى
  • Postext 1.103.1
  • أُخرجت في 61 ms
  • أسطر الشيفرة: 242

باختصار

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

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

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

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

  • كيف أتيح للقرّاء تظليل فقرات من الكتاب بألوان يختارونها؟

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

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));

المكونات

الخطوط
Literata, Source Sans 3 (SIL OFL 1.1)
الأصول
لا شيء: كل صورة مرسومة بالشيفرة

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

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

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 · مدّ التحديد إلى كلمات كاملة واعرض الألوان

الشيفرة هي الجواب المختصر أعلاه. يُبلغ العارض عن كل تحديد مكتمل نطاقًا من Markdown. تمدّ wordRangeAt الطرف الذي يقع داخل كلمة إلى الكلمة كلها، فلا تترك حركة متعجلة نصف كلمة مظلَّلًا. ويعود النطاق المعدَّل إلى العارض عبر setSelection، ويتجاهل المعالج هذا الصدى، وإلا لظل يعرض اللوحة بلا نهاية.

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

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 · اعرض في قائمة ما علّمه القارئ

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، فتُمرَّر كلماته إلى مجال الرؤية.

الوصفة كاملة

// ═══ 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) } } },
  ] },
};

يعمل ملف script.js المجمّع كما هو: الصقه في سكربت الوحدة (module) لأي صفحة، أو افتح الوصفة على CodePen. مجلد الوصفة على GitHub ↗ (يفتح في تبويب جديد)

تنويعات

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

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

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

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

التظليل الذي يحمل ملاحظة أيضًا يصير راية في الهامش: تبني دفتر القارئ: ملاحظات على ما يحدده من نص الدفتر على المراسي نفسها.

الحقوق

الوصفة
Ignacio Ferro
النص
نص أصلي, CC BY 4.0
الخطوط
Literata (SIL OFL 1.1) · Source Sans 3 (SIL OFL 1.1)
الشيفرة
MIT، مثل Postext