# انقر على الصفحة لتجد موضعها في النص الأصلي

> تحوّل sourceAt وcaretAt نقرةً على صفحة منضَّدة إلى كتلة من Markdown وموضع فيه؛ ويعرض نظام إدارة المحتوى ذلك السطر من الأصل معلَّمًا.

- نسخة HTML: https://postext.dev/ar/cookbook/click-to-markdown-source
- وصفة رقم 216 · الدمج مع أنظمة إدارة المحتوى · المستوى 2 (متوسط) · المخرجات: Canvas, عناصر تحكم حية
- الأنواع: الأدلة والمراجع
- تتطلب postext ≥ 1.103.0 · اختُبرت مع 1.103.1 بتاريخ 2026-12-04
- الصفحات: [1](https://postext.dev/cookbook/click-to-markdown-source/en/p01.webp?v=57b3b5cd), [2](https://postext.dev/cookbook/click-to-markdown-source/en/p02.webp?v=57b3b5cd)
- ![نقرة على «a large correction» في الصفحة 1: كتلتها ملوّنة على الصفحة، ومؤشر يعلّم الإزاحة، والمصدر بجانبها يعرض الكتلة نفسها والسلسلة text › line › block.](https://postext.dev/cookbook/click-to-markdown-source/en/s01.webp?v=57b3b5cd)
- ![نقرة أبعد، في الصفحة 2: يُمرَّر المصدر إلى السطر 26 وتُعلَّم الفقرة التي وقعت فيها النقرة.](https://postext.dev/cookbook/click-to-markdown-source/en/s02.webp?v=57b3b5cd)
- آخر تحديث: 2026-12-04
- لغات أخرى: [en](https://postext.dev/en/cookbook/click-to-markdown-source.md), [es](https://postext.dev/es/cookbook/click-to-markdown-source.md), [ca](https://postext.dev/ca/cookbook/click-to-markdown-source.md), [de](https://postext.dev/de/cookbook/click-to-markdown-source.md), [el](https://postext.dev/el/cookbook/click-to-markdown-source.md), [fr](https://postext.dev/fr/cookbook/click-to-markdown-source.md), [it](https://postext.dev/it/cookbook/click-to-markdown-source.md), [pt](https://postext.dev/pt/cookbook/click-to-markdown-source.md), [ru](https://postext.dev/ru/cookbook/click-to-markdown-source.md), [zh](https://postext.dev/zh/cookbook/click-to-markdown-source.md), [ja](https://postext.dev/ja/cookbook/click-to-markdown-source.md)

## باختصار

فصل من دليل لإصلاح الدراجات معروض صفحاتٍ، وبجانبه النص الذي خرجت منه. نقرة على كلمة في الصفحة تجد الكلمة نفسها في النص، وتعلّم فقرتها، وتذكر رقم سطرها.

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

فصل من *The Home Bicycle Workshop* على صفحة 148 × 210 مم، معروض في postext-viewer على اليسار، ونص Markdown الخاص به على اليمين كما يحفظه نظام تحرير. نقرة في أي موضع من الصفحة تنقل لوحة الأصل إلى السطر الذي تحت المؤشر: تتلوّن الفقرة في الجانبين، ويقف مؤشر أخضر عند الحرف، ويذكر سطرا الحالة السطر والعمود والموضع، ثم سلسلة ما هو مرسوم في تلك النقطة. تُظهر البطاقة نقرة جاهزة في وسط فقرة من القسم الثالث.

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

- كيف أعرف أيّ جزء من Markdown وقعت عليه نقرة على الصفحة؟

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

```js
// script.js, سطرًا 122–145
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)](https://postext.dev/ar/docs/configuration-programmatic-usage.md#خريطة-المصدر-لمستند-منضد): تجيب sourceAt عن نقطة على الصفحة بسلسلة العناصر التي تحتها، من السطر إلى الكتلة، ولكلٍّ منها نطاقه في Markdown، وتسلك elementsForSource الطريق المعاكس.
- [هندسة النص (النطاقات والنقاط)](https://postext.dev/ar/docs/integration-geometry.md#النص-على-الصفحة): تحوّل rangeRects نطاقًا من Markdown إلى مستطيلات على الصفحات، وتعيد caretAt وwordAt وblockAt نقطةً على الصفحة إلى موضع أو كلمة أو كتلة في المصدر.

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

- [عارض الصفحات (postext-viewer)](https://postext.dev/ar/docs/integration-viewer.md#عارض-الصفحات)
- [علامات التعليق](https://postext.dev/ar/docs/integration-marks.md#علامات-التعليق)
- [صفحات على اللوحة (Canvas)](https://postext.dev/ar/docs/configuration-programmatic-usage.md#رسم-صفحة-في-صورة-نقطية)
- [الخطوط قبل الإخراج](https://postext.dev/ar/docs/configuration-programmatic-usage.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/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#تحميل-الخطوط-قبل-الإخراج), `caretAt`, `createViewer`, `rangeRects`, [`renderPageToCanvas`](https://postext.dev/ar/docs/configuration-programmatic-usage.md#رسم-صفحة-في-صورة-نقطية), `setAnnotations`, `sourceAt`

**الخطوط**

- Source Serif 4 (OFL-1.1), IBM Plex Sans (OFL-1.1)

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

### 1 · انضد فصلًا بتصميم خاص به

```js
// script.js, سطرًا 33–43
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 · اسأل التنضيد عمّا تحت النقطة

الشيفرة هي [الجواب المختصر](https://postext.dev/ar/cookbook/click-to-markdown-source.md#الجواب-المختصر) أعلاه. يعطي الحدث `click` في العارض الصفحة والنقطة بوحدات بكسل الصفحة، ويقرأ استدعاءان التنضيد عند تلك النقطة. تعدّد `sourceAt` ما هو مرسوم هناك من الداخل إلى الخارج: الحرف المرسوم، وسطره، وكتلته، وإطارًا حوله إن وُجد. الفقرة الموزعة على صفحتين تجيب بمداها كله، والترويسة تجيب ببند الإعدادات الذي وضعها لا بنص Markdown. وتعطي `caretAt` أقرب حدٍّ بين حرفين، كما تفعل نقرة في محرر نصوص. كلاهما يعدّ بوحدات UTF-16 في الملف مع مقدمته (front matter)، فيُستخرج السطر والعمود من Markdown نفسه.

### 3 · اعرض السطر في الأصل

```js
// script.js, سطرًا 149–177
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;
}
```

تقطع اللوحة كل سطر عند بداية الكتلة ونهايتها وعند موضع المؤشر، فيقع التعليم والمؤشر على الحروف نفسها التي تعرضها الصفحة. ويعود المدَيان نفساهما إلى العارض تظليلًا وعلامةَ إدراج، فيتحقق القارئ من أن الانتقال وقع حيث أراد.

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

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

- مجلد الوصفة: https://github.com/drnachio/postext/tree/main/cookbook/click-to-markdown-source

### index.html

```html
<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>
```

### style.css

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

```js
// ═══ 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,
  page: { sizePreset: 'custom', width: mm(148), height: mm(210), dpi: 150,
    margins: { top: mm(20), bottom: mm(20), left: mm(18), right: mm(16), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Source Serif 4', fontSize: pt(9.5), lineHeight: pt(LEAD),
    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: 'IBM Plex Sans', color: col('ink'), fontWeight: 600, levels: [
    { level: 1, fontSize: pt(22), lineHeight: pt(26), color: col('accent'),
      marginTop: mm(18), marginBottom: pt(LEAD * 2) },
    { level: 2, fontSize: pt(9.5), lineHeight: pt(LEAD), marginTop: pt(LEAD),
      marginBottom: pt(0) },
  ] },
  header,
  footer: { elements: [] },
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "The Home Bicycle Workshop"
author: "Tomás Reyes"
---

# Truing a wheel

A wheel is true when its rim runs straight, without a wobble from side to side or a hop up and down. Thirty-two or thirty-six spokes hold the rim in place, each pulling with a tension of about 100 kilograms on a modern road wheel. Every spoke pulls the rim towards its own side of the hub, so the shape of the rim is a balance of all those pulls. Truing means tightening and loosening single spokes, a quarter turn at a time, until the balance is even again.

## What you need

A truing stand makes the job easier, but a bicycle turned upside down will do: the brake pads, or a cable tie fixed to the frame, serve as a gauge beside the rim. You also need a spoke key that fits your nipples exactly. Most nipples are 3.2 mm across the flats; a key that is slightly too large rounds them off, and a rounded nipple can only be replaced.

Before you start, squeeze pairs of spokes together all the way round. A spoke that feels slack against its neighbours is the likely cause of the wobble, and it is worth checking the rim for a dent or a crack. No amount of truing will straighten a bent rim.

## Finding the wobble

Spin the wheel slowly and bring the gauge in until it just touches the rim at one spot. That spot is where the rim bends towards the gauge. Mark it with a piece of tape, and note how long the bend is: a short bend covers two or three spokes, a long one six or more.

The spokes that lead to the hub flange on the far side of the gauge pull the rim away from it. Tighten those in the middle of the bend by a quarter turn, and loosen the spokes on the near side, next to them, by the same amount. Spin the wheel again. Work in small steps; a half turn on a single spoke is already a large correction.

## Which way to turn

The nipple sits at the rim end of the spoke, and you are looking at it from the hub, which makes the direction easy to get wrong. Seen from the tyre, a nipple tightens clockwise, like any screw. Seen from the hub, with the wheel in the stand, it tightens anticlockwise. Many mechanics say it aloud as they work: righty-tighty only holds from outside the wheel.

Spokes also twist as they are tightened, and the twist springs back later. Turn the key a little past the mark and then back by an eighth, so the spoke is left straight.

## Hop and dish

A wheel can also be out of round. Watch the gap between the top of the rim and the gauge: where the rim rises, tighten the spokes on both sides at that spot by the same amount, which pulls the rim in without moving it sideways. Where it dips, loosen them.

On a rear wheel the rim does not sit in the middle of the hub, because the sprockets take up room on one side. The spokes on the sprocket side carry more tension to centre the rim over the axle. This offset is called dish. A dishing tool checks it, or you can turn the wheel round in the stand and see whether the rim sits in the same place both ways.

## Finishing

When the wobble is under half a millimetre, stress the wheel. Grip parallel spokes in pairs and squeeze them hard, all the way round, on both sides. The spokes settle in the flange and the nipples bed into the rim, and the wheel will often lose a little of its truth. Correct it again, then repeat. A wheel that comes through two rounds of squeezing without moving will stay true for many months of riding.
`; // content.<lang>.md, inlined by the Cookbook

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

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown }, config, kitFonts(FONTS));
kitStatus(t({ en: 'Click a page to see its source', es: 'Haz clic en una página' }));

const view = createViewer(document.getElementById('viewer'), { document: doc, markdown,
  zoom: 'fit-width', maxZoom: 1.3, gap: 20, labels: t({ en: {},
    es: { viewer: 'Páginas del libro', page: 'Página {n} de {count}' } }) });
const $ = (id) => document.getElementById(id);

// #region answer: a point on a page, back to a line of the 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));
// #endregion

// #region source: the Markdown, one numbered line per row, the block marked
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;
}
// #endregion

// For the card: a click in the middle of a phrase of the third section, as a reader would make.
const phrase = t({ en: 'a large correction', es: 'una corrección grande' });
const start = markdown.indexOf(phrase);
const [piece] = rangeRects(doc, { start, end: start + phrase.length });
pick(piece.pageIndex, piece.rect.x + piece.rect.width / 2, piece.rect.y + piece.rect.height / 2);
view.revealRange({ start, end: start });
$('title').textContent = t({ en: 'Markdown source', es: 'Original en Markdown' });

// The states the Cookbook photographs: a click further on in the chapter.
kitShots({ later: () => {
  const at = markdown.indexOf('\n\n', Math.floor(markdown.length * 0.6)) + 2;
  const [hit] = rangeRects(doc, { start: at, end: at + 12 });
  pick(hit.pageIndex, hit.rect.x + 4, hit.rect.y + hit.rect.height / 2);
  view.revealRange({ start: at, end: at + 12 });
} });

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

## تنويعات

### علّم الكلمة لا الفقرة

توسّع `wordAt` الموضع إلى الكلمة التي تحت النقطة، بحسب لغة المستند.

```diff
-  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 الذي يُنضَّد منه سطر واحد من الصفحة، وهو ما يشير إليه المصحِّح.

```diff
-  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 ([@drnachio](https://github.com/drnachio))
- الخطوط: Source Serif 4 (OFL-1.1), IBM Plex Sans (OFL-1.1)
- الشيفرة: MIT · محتوى المثال: CC-BY-4.0

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

- [رقم 212 · حدِّد على الصفحة واقرأ نطاق Markdown ونصّه](https://postext.dev/ar/cookbook/selection-as-markdown-range.md): يُبلغ postext-viewer عن التحديد على الصفحات المُخرَجة نطاقًا في Markdown، مع نص Markdown الذي يغطيه وقطعه سطرًا سطرًا. · المستوى 1 (أساسي) · المجلات والمجلات المستقلة
- [رقم 221 · Canvas خاص بك: renderPage وrangeRects وcaretAt](https://postext.dev/ar/cookbook/own-canvas-page-view.md): عرض صفحات مكتوب باليد دون postext-viewer: ترسم renderPage كل صفحة مرة واحدة، وترسم rangeRects التحديد، وتضع caretAt وcaretRect مؤشر الكتابة. · المستوى 3 (متقدم) · الأدب القصصي والمسرح والنثر الأدبي
- [رقم 219 · نتائج البحث مرسومة على الصفحات](https://postext.dev/ar/cookbook/search-results-on-pages.md): مربع بحث يجد العبارة في Markdown، ويرسم كل تطابق تظليلًا على الصفحات المنضَّدة، وينتقل بينها بـ revealAnnotation. · المستوى 2 (متوسط) · أي نوع
