باختصار
فصل من دليل لإصلاح الدراجات معروض صفحاتٍ، وبجانبه النص الذي خرجت منه. نقرة على كلمة في الصفحة تجد الكلمة نفسها في النص، وتعلّم فقرتها، وتذكر رقم سطرها.
ما الذي ستنضده
فصل من The Home Bicycle Workshop على صفحة 148 × 210 مم، معروض في postext-viewer على اليسار، ونص Markdown الخاص به على اليمين كما يحفظه نظام تحرير. نقرة في أي موضع من الصفحة تنقل لوحة الأصل إلى السطر الذي تحت المؤشر: تتلوّن الفقرة في الجانبين، ويقف مؤشر أخضر عند الحرف، ويذكر سطرا الحالة السطر والعمود والموضع، ثم سلسلة ما هو مرسوم في تلك النقطة. تُظهر البطاقة نقرة جاهزة في وسط فقرة من القسم الثالث.
تجيب هذه الوصفة عن
- كيف أعرف أيّ جزء من Markdown وقعت عليه نقرة على الصفحة؟
الجواب المختصر
const span = ({ level, source: s }) => `${level} ${s.kind === 'config' ? s.path
: s.start === undefined ? s.resourceId : `[${s.start}, ${s.end})`}`;
function pick(pageIndex, x, y) {
// What is painted there, innermost first: a glyph, its line, its paragraph, a box round
// it; a running head answers with the config entry that set it.
const chain = sourceAt(doc, pageIndex, x, y);
$('chain').textContent = chain.map(span).join(' › ');
const block = chain.find((e) => e.level === 'block' && e.source.kind === 'markdown')?.source;
const hit = caretAt(doc, pageIndex, x, y); // the character boundary nearest the point
if (!block || !hit) return view.setAnnotations([]);
// Offsets count UTF-16 units of the whole file, front matter included, so the line and
// column come from the Markdown itself.
const before = markdown.slice(0, hit.offset).split('\n');
const [line, column] = [before.length, before.at(-1).length + 1];
$('where').textContent = t({ en: `Line ${line}, column ${column} · offset ${hit.offset}`,
es: `Línea ${line}, columna ${column} · posición ${hit.offset}` });
showSource(block, hit.offset, line);
// The same ranges, drawn back on the page.
view.setAnnotations([
{ id: 'block', kind: 'highlight', range: block, color: '#2a9aa6' },
{ id: 'caret', kind: 'insert', range: { start: hit.offset, end: hit.offset } },
]);
}
view.on('click', ({ pageIndex, x, y }) => pick(pageIndex, x, y));
المكونات
- الميزات
- خريطة المصدر (من الصفحة إلى Markdown)هندسة النص (النطاقات والنقاط)عارض الصفحات (postext-viewer)علامات التعليقصفحات على اللوحة (Canvas)الخطوط قبل الإخراجالترويسات وأرقام الصفحاتهوامش متناظرةلوحة ألوان دلالية
- تستخدم أيضًا
- الترويسات بحسب دور الصفحة
- الخطوط
- Source Serif 4, IBM Plex Sans (SIL OFL 1.1)
- الأصول
- لا شيء: كل صورة مرسومة بالشيفرة
طريقة التحضير
#1 · انضد فصلًا بتصميم خاص به
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
pages: 'body', fontFamily: 'IBM Plex Sans', fontSize: pt(7), fontWeight: 500,
letterSpacing: pt(0.6), color: col('muted'),
placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(10) } }, ...extra });
const folio = { fontWeight: 600, color: col('accent') };
const header = { elements: [
head('verso-folio', '{pageNumber}', 'even', 'top-left', 16, folio),
head('verso-title', '{title}', 'even', 'top-left', 24),
head('recto-chapter', '{chapterTitle}', 'odd', 'top-right', -24),
head('recto-folio', '{pageNumber}', 'odd', 'top-right', -16, folio),
] };
الصفحة صفحة دليل ورشة بلا زخارف: Source Serif 4 بحجم 9.5 نقطة، وعناوين بخط IBM Plex Sans، وترويسات تغيّر جهتها مع الصفحة. لا شيء في التنضيد موضوع من أجل النقرة؛ فكل مستند منضَّد يجيب عن الاستدعاءات نفسها.
#2 · اسأل التنضيد عمّا تحت النقطة
الشيفرة هي الجواب المختصر أعلاه. يعطي الحدث click في العارض الصفحة والنقطة بوحدات بكسل الصفحة، ويقرأ استدعاءان التنضيد عند تلك النقطة. تعدّد sourceAt ما هو مرسوم هناك من الداخل إلى الخارج: الحرف المرسوم، وسطره، وكتلته، وإطارًا حوله إن وُجد. الفقرة الموزعة على صفحتين تجيب بمداها كله، والترويسة تجيب ببند الإعدادات الذي وضعها لا بنص Markdown. وتعطي caretAt أقرب حدٍّ بين حرفين، كما تفعل نقرة في محرر نصوص. كلاهما يعدّ بوحدات UTF-16 في الملف مع مقدمته (front matter)، فيُستخرج السطر والعمود من Markdown نفسه.
#3 · اعرض السطر في الأصل
function showSource(block, offset, line) {
const rows = [];
let at = 0;
for (const [i, text] of markdown.split('\n').entries()) {
const row = document.createElement('div');
row.className = 'row';
row.dataset.n = String(i + 1);
const body = row.appendChild(document.createElement('span')); // one grid cell
// Cut the line where the block starts and ends and where the caret is.
const cuts = [at, at + text.length];
for (const c of [block.start, block.end, offset]) if (c > at && c < cuts[1]) cuts.push(c);
cuts.sort((a, b) => a - b);
for (let k = 0; k < cuts.length - 1; k++) {
const [from, to] = [cuts[k], cuts[k + 1]];
if (from === offset) body.append(Object.assign(document.createElement('span'),
{ className: 'caret' }));
const inBlock = from >= block.start && to <= block.end;
body.append(inBlock ? Object.assign(document.createElement('mark'),
{ textContent: markdown.slice(from, to) }) : markdown.slice(from, to));
}
if (offset === cuts.at(-1) && offset > at) body.append(Object.assign(
document.createElement('span'), { className: 'caret' })); // a caret at the line's end
rows.push(row);
at += text.length + 1;
}
$('lines').replaceChildren(...rows);
const target = rows[line - 1];
$('lines').scrollTop = target.offsetTop - $('lines').clientHeight / 3;
}
تقطع اللوحة كل سطر عند بداية الكتلة ونهايتها وعند موضع المؤشر، فيقع التعليم والمؤشر على الحروف نفسها التي تعرضها الصفحة. ويعود المدَيان نفساهما إلى العارض تظليلًا وعلامةَ إدراج، فيتحقق القارئ من أن الانتقال وقع حيث أراد.
الوصفة كاملة
// ═══ Postext Cookbook · Nº 216 · Click on the page to find the source ═════════════════
// https://postext.dev/en/cookbook/click-to-markdown-source
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Source Serif 4, IBM Plex Sans (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A chapter of a workshop manual in postext-viewer, with its Markdown beside it. A click on a
// page asks the layout which character and which block lie under the point, and the source
// panel scrolls to that line with the block marked and a caret at the character, the way a
// CMS jumps from a proof to the text an author has to change.
import { buildDocumentWithFonts, renderPageToCanvas, sourceAt, caretAt, 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 = 'click-to-markdown-source';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
ink: '#1d2125', // text
accent: '#1f6f78', // workshop teal: headings' rule, folios
muted: '#68707a', // 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
const LEAD = 13.5; // pt of body leading
// #region book: a manual's page with running heads by parity
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
pages: 'body', fontFamily: 'IBM Plex Sans', fontSize: pt(7), fontWeight: 500,
letterSpacing: pt(0.6), color: col('muted'),
placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(10) } }, ...extra });
const folio = { fontWeight: 600, color: col('accent') };
const header = { elements: [
head('verso-folio', '{pageNumber}', 'even', 'top-left', 16, folio),
head('verso-title', '{title}', 'even', 'top-left', 24),
head('recto-chapter', '{chapterTitle}', 'odd', 'top-right', -24),
head('recto-folio', '{pageNumber}', 'odd', 'top-right', -16, folio),
] };
// #endregion
const config = {
locale: t({ en: 'en-gb', es: 'es' }),
colorPalette,
<main id="pages">
<div id="viewer"></div>
<aside id="source">
<h2 id="title"></h2>
<p id="where" role="status"></p>
<p id="chain"></p>
<div id="lines" tabindex="0"></div>
</aside>
</main>
/* The host's frame: the pages on the left, the Markdown on the right. Both scroll on their
own, so the frame gets a height: the window under the kit's bar. */
main#pages {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
height: max(560px, calc(100vh - 44px)); gap: 0; padding: 0; justify-items: stretch;
}
#viewer { min-height: 0; }
#viewer .postext-viewer { --pv-background: #0e1014; --pv-focus: #2a9aa6; }
#source {
display: flex; flex-direction: column; min-height: 0; background: #15181d;
border-left: 1px solid #23262d; color: #c9ccd3;
}
#source h2 { margin: 0; padding: 14px 18px 4px; font: 600 13px/1.3 system-ui, sans-serif;
letter-spacing: .08em; text-transform: uppercase; color: #f4f1ea; }
#where, #chain { margin: 0; padding: 0 18px 4px; font: 13px/1.4 system-ui, sans-serif;
color: #7fd0d8; font-variant-numeric: tabular-nums; }
#chain { padding-bottom: 12px; color: #9aa0aa; border-bottom: 1px solid #23262d; }
#lines { flex: 1; min-height: 0; overflow: auto; padding: 10px 0 40px; position: relative;
font: 12.5px/1.6 ui-monospace, 'SF Mono', Menlo, Consolas, monospace; }
#lines:focus-visible { outline: 2px solid #2a9aa6; outline-offset: -2px; }
.row { display: grid; grid-template-columns: 3.2em 1fr; white-space: pre-wrap;
overflow-wrap: anywhere; padding-right: 18px; }
.row::before { content: attr(data-n); padding-right: 1em; text-align: right; color: #5b616c; }
.row mark { background: rgb(42 154 166 / .28); color: #f4f1ea; border-radius: 2px; }
.row .caret { display: inline-block; width: 2px; height: 1.25em; margin: 0 -1px;
vertical-align: text-bottom; background: #34c27a; }
يعمل ملف script.js المجمّع كما هو: الصقه في سكربت الوحدة (module) لأي صفحة، أو افتح الوصفة على CodePen. مجلد الوصفة على GitHub ↗ (يفتح في تبويب جديد)
تنويعات
#علّم الكلمة لا الفقرة
توسّع wordAt الموضع إلى الكلمة التي تحت النقطة، بحسب لغة المستند.
- const block = chain.find((e) => e.level === 'block' && e.source.kind === 'markdown')?.source;
+ const block = wordAt(doc, pageIndex, x, y, markdown); // import wordAt from postext#علّم السطر المطبوع
العنصر line في السلسلة هو مقطع Markdown الذي يُنضَّد منه سطر واحد من الصفحة، وهو ما يشير إليه المصحِّح.
- const block = chain.find((e) => e.level === 'block' && e.source.kind === 'markdown')?.source;
+ const block = chain.find((e) => e.level === 'line' && e.source.kind === 'markdown')?.source;الحقوق
- الوصفة
- Ignacio Ferro
- النص
- نص أصلي, CC BY 4.0
- الخطوط
- Source Serif 4 (SIL OFL 1.1) · IBM Plex Sans (SIL OFL 1.1)
- الشيفرة
- MIT، مثل Postext
حرّر هذا الشرح ↗ (يفتح في تبويب جديد)مجلد الوصفة على GitHub ↗ (يفتح في تبويب جديد)



