باختصار
مقال عن عدسات المنارات في عارض صفحات، وبجانبه لوحة. حين يحدّد أحدهم كلمات على الصفحة، تُظهر اللوحة موضعها في النص المصدر وما يقوله المصدر هناك، مع علامات التنسيق.
ما الذي ستنضده
مقال من صفحتين عن عدسات المنارات، معروض في عارض صفحات وعلى يمينه لوحة، مثل التي تضعها أداة مراجعة بجانب المقطع قيد النقاش. في الصفحة الأولى جملة محدَّدة، واللوحة تقرؤها بثلاث طرق: النطاق { start, end } في ملف Markdown، ونص Markdown الذي فيه حيث يحتفظ الاسم الفرنسي المائل بنجمتيه، والفقرة كاملة والتحديد معلَّم فيها. اسحب فوق كلمات أخرى فتتبعك اللوحة أثناء السحب.
تجيب هذه الوصفة عن
- كيف أحصل على نطاق Markdown ونص ما يحدده المحرر على الصفحة؟
الجواب المختصر
const view = createViewer($('viewer'), {
document: doc,
markdown, // with it, each selection event carries the Markdown it covers
zoom: 'fit-page', labels: L.viewer,
});
view.on('selectionchange', ({ range, text }) => {
$('panel').classList.toggle('empty', !range);
if (!range) return void ($('range').textContent = L.none);
$('range').textContent = `{ start: ${range.start}, end: ${range.end} }`;
$('text').textContent = text; // the Markdown, emphasis marks included
// The range is a plain value: the core API places it too, one piece per line, in page px.
const rects = rangeRects(doc, range);
const pages = [...new Set(rects.map((r) => r.pageIndex + 1))].join(', ');
$('lines').textContent = L.lines(rects.length, pages);
// The paragraph around it: offsets count in the Markdown file, front matter included.
const from = markdown.lastIndexOf('\n\n', range.start) + 2;
let to = markdown.indexOf('\n\n', range.end);
if (to < 0) to = markdown.length; // the last paragraph
const mark = Object.assign(document.createElement('mark'), { textContent: text });
const [before, after] = [markdown.slice(from, range.start), markdown.slice(range.end, to)];
$('source').replaceChildren(before, mark, after);
});
المكونات
- الخطوط
- Newsreader, Archivo (SIL OFL 1.1)
- الأصول
- لا شيء: كل صورة مرسومة بالشيفرة
طريقة التحضير
#1 · انضد صفحة للتحديد عليها
const config = {
locale: t({ en: 'en-gb', es: 'es' }),
colorPalette,
layout: { layoutType: 'single' },
page: { sizePreset: 'custom', width: mm(140), height: mm(210), dpi: 150,
margins: { top: mm(20), bottom: mm(24), left: mm(22), right: mm(22) } },
bodyText: { fontFamily: 'Newsreader', fontSize: pt(10.5), lineHeight: pt(15),
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: 'Archivo', color: col('accent'), fontWeight: 600, levels: [
{ level: 1, fontSize: pt(22), lineHeight: pt(26), marginTop: pt(6), marginBottom: pt(15) },
{ level: 2, fontSize: pt(10), lineHeight: pt(15), marginTop: pt(15), marginBottom: pt(0) },
] },
header: { elements: [] },
footer: { elements: [
{ kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Archivo', fontSize: pt(8),
fontWeight: 600, color: col('accent'), align: 'center',
placement: { anchor: { to: 'page', edge: 'bottom-center' }, offset: { y: mm(-12) } } },
] },
};
صفحة مجلة بسيطة: عمود واحد مضبوط بخط Newsreader، وعناوين بخط Archivo بلون أزرق الميناء، ورقم الصفحة في الذيل. يعمل التحديد بالطريقة نفسها في أي إخراج، في الأعمدة وفي الصفحات من اليمين إلى اليسار أو العمودية أيضًا، لأن العارض يسأل الإخراج أين رُسم كل سطر.
#2 · اقرأ التحديد بوصفه Markdown
الشيفرة هي الجواب المختصر أعلاه. مرِّر markdown إلى createViewer فيحمل كل selectionchange النطاق ونص Markdown الذي يغطيه. النطاق مجرد { start, end }، فتضعه rangeRects من النواة على الصفحات دون العارض، قطعة لكل سطر يعبره. تُعَدّ الإزاحات داخل ملف Markdown، بما فيها البيانات التمهيدية، فالفقرة المحيطة بالتحديد شريحة من السلسلة نفسها، والنطاق المحفوظ اليوم يشير غدًا إلى الكلمات نفسها ما دام النص لم يتغيّر.
#3 · استعِد تحديدًا محفوظًا
const quote = t({ en: 'The first *lentille à échelons* was lit in July 1823',
es: 'La primera *lentille à échelons* se encendió en julio de 1823' });
const start = markdown.indexOf(quote);
view.setSelection({ start, end: start + quote.length });
تأخذ setSelection نطاقًا من الشيفرة وتطلق الأحداث نفسها التي يطلقها السحب، فتمتلئ اللوحة وحدها. هذا ما تفعله أداة تعيد فتح مقطع تعليق؛ وتشرح المراسي والتعديلات كيف يبقى هذا النطاق صالحًا بعد تعديل النص.
الوصفة كاملة
// ═══ Postext Cookbook · Nº 212 · Select on the page, read the Markdown range and text ═══
// https://postext.dev/en/cookbook/selection-as-markdown-range
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Newsreader, Archivo (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// An article on lighthouse lenses in postext-viewer, with a panel beside it that a review
// tool would fill from the selection: the range in the Markdown, the Markdown it covers and
// the paragraph around it. The pen selects one sentence itself; drag over the page to change it.
import { buildDocumentWithFonts, renderPageToCanvas, rangeRects } from 'https://esm.sh/postext';
import { createViewer } from 'https://esm.sh/postext-viewer';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'selection-as-markdown-range';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
ink: '#1b1f24', // text: a cool near-black
accent: '#1d5c73', // harbour blue: 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 magazine page, one column, a folio at the foot
const config = {
locale: t({ en: 'en-gb', es: 'es' }),
colorPalette,
layout: { layoutType: 'single' },
page: { sizePreset: 'custom', width: mm(140), height: mm(210), dpi: 150,
margins: { top: mm(20), bottom: mm(24), left: mm(22), right: mm(22) } },
bodyText: { fontFamily: 'Newsreader', fontSize: pt(10.5), lineHeight: pt(15),
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: 'Archivo', color: col('accent'), fontWeight: 600, levels: [
{ level: 1, fontSize: pt(22), lineHeight: pt(26), marginTop: pt(6), marginBottom: pt(15) },
{ level: 2, fontSize: pt(10), lineHeight: pt(15), marginTop: pt(15), marginBottom: pt(0) },
] },
header: { elements: [] },
footer: { elements: [
{ kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Archivo', fontSize: pt(8),
fontWeight: 600, 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" aria-live="polite">
<h2 data-en="Selection" data-es="Selección"></h2>
<p class="label" data-en="Range in the Markdown" data-es="Rango en el Markdown"></p>
<p id="range" class="value"></p>
<div id="details">
<p id="lines" class="note"></p>
<p class="label" data-en="Text (Markdown)" data-es="Texto (Markdown)"></p>
<pre id="text"></pre>
<p class="label" data-en="In the source" data-es="En el original"></p>
<pre id="source"></pre>
</div>
</aside>
</main>
/* The host's frame: the viewer on the left, the selection panel on the right.
The viewer fills its container, so the container gets a height. */
main#pages {
display: grid; grid-template-columns: minmax(0, 1fr) 380px; height: max(560px, 100vh);
justify-items: stretch; gap: 0; padding: 0;
}
#viewer { min-height: 0; }
#viewer .postext-viewer {
--pv-background: #dfe3e6;
--pv-selection: rgb(29 92 115 / .28);
--pv-focus: #1d5c73;
}
#panel {
overflow: auto; padding: 20px 22px; background: #fbfbf9; border-left: 1px solid #c9cfd4;
font: 15px/1.45 system-ui, sans-serif; color: #1b1f24;
}
#panel h2 { margin: 0 0 14px; font-size: 18px; }
#panel .label {
margin: 18px 0 4px; font-size: 12px; font-weight: 600; letter-spacing: .06em;
text-transform: uppercase; color: #4d5861;
}
#panel .value { margin: 0; font: 600 16px/1.4 ui-monospace, Menlo, monospace; }
#panel .note { margin: 2px 0 0; color: #4d5861; font-size: 14px; }
#panel pre {
margin: 0; padding: 10px 12px; white-space: pre-wrap; overflow-wrap: anywhere;
background: #fff; border: 1px solid #d5dadf; border-radius: 6px;
font: 13.5px/1.5 ui-monospace, Menlo, monospace;
}
#panel mark { background: rgb(29 92 115 / .2); color: inherit; border-radius: 2px; }
#panel.empty #details { display: none; }
يعمل ملف script.js المجمّع كما هو: الصقه في سكربت الوحدة (module) لأي صفحة، أو افتح الوصفة على CodePen. مجلد الوصفة على GitHub ↗ (يفتح في تبويب جديد)
تنويعات
#تصرّف حين يكتمل التحديد فقط
يُطلَق selectionchange عند كل خطوة من السحب، أما select فمرة واحدة، عند إفلات المؤشر أو النقر المزدوج على كلمة.
-view.on('selectionchange', ({ range, text }) => {
+view.on('select', ({ range, text }) => {#اقرأه بعرض العمود
بعرض العمود يسهل سحب التحديد بدقة.
- zoom: 'fit-page', labels: L.viewer,
+ zoom: 'fit-width', labels: L.viewer,الحقوق
- الوصفة
- Ignacio Ferro
- النص
- نص أصلي, CC BY 4.0
- الخطوط
- Newsreader (SIL OFL 1.1) · Archivo (SIL OFL 1.1)
- الشيفرة
- MIT، مثل Postext
حرّر هذا الشرح ↗ (يفتح في تبويب جديد)مجلد الوصفة على GitHub ↗ (يفتح في تبويب جديد)



