# تطبيق التعديلات المقبولة ونقل الملاحظات الأخرى معها

> تكتب applyEdits التصحيحات المقبولة في Markdown وتنقل معها مرساة كل ملاحظة أخرى، وتعلّم الملاحظات التي وقع داخلها تعديل.

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

## باختصار

مقالة في مجلة عليها أربعة تصحيحات مقترحة وثلاث ملاحظات من محررة. تُقبل ثلاثة تصحيحات وتُكتب في النص. تنتقل الملاحظات مع كلماتها، والملاحظة التي تغيّرت كلماتها تُعلَّم لتُقرأ من جديد.

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

مقالة من *Field Notes on Ice*، صفحة مجلة مقاسها 130 × 190 مم، تُعرض مرتين. على اليسار المسودة وعليها أربعة تعديلات مقترحة مرسومة بعلامات التصحيح وثلاث ملاحظات مرقمة من المحررة. وعلى اليمين النص بعد أن كُتبت التعديلات الثلاثة المقبولة في Markdown وأُعيد تنضيده: الكلمات الجديدة ملونة بالأخضر، والملاحظات منقولة مع كلماتها، والحذف المرفوض ما زال مفتوحًا بالرمادي، والملاحظة 2 معلَّمة بالكهرماني لأن تعديلًا مقبولًا غيّر الكلمات التي كانت عليها.

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

- كيف أطبّق التعديلات المقبولة على Markdown وأنقل الملاحظات الأخرى معها؟

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

```js
// script.js, سطرًا 152–177
const accepted = edits.filter((e) => e.accepted);
const declined = edits.filter((e) => !e.accepted);
const kept = [...notes.map((n) => n.anchor), ...declined.map((e) => textAnchor(markdown, e))];
// One call: the new Markdown, a map of old offsets to new ones, and every anchor carried.
const { markdown: next, map, anchors } = applyEdits(markdown, accepted, kept);
const after = await buildDocumentWithFonts({ markdown: next }, config, kitFonts(FONTS));
const marks = [
  // The text each accepted edit put in, where it now is.
  ...accepted.map((e, i) => {
    const start = mapOffset(map, e.start, 'before');
    return { id: `a${i}`, kind: 'highlight', range: { start, end: start + e.text.length },
      color: '#1f8a4c' };
  }),
  // The notes: a note an edit fell inside is touched, for a person to read again.
  ...notes.map((n, i) => {
    const { anchor, touched } = anchors[i];
    return { id: `n${i}`, kind: 'note', range: anchor, label: touched ? `${i + 1}?` : `${i + 1}`,
      color: touched ? '#c4720a' : undefined };
  }),
  // The declined edit stays open on the new text.
  ...declined.map((e, k) => {
    const { start, end } = anchors[notes.length + k].anchor;
    return suggestion({ ...e, start, end }, `d${k}`);
  }),
];
openPages('after', after, next, marks);
```

## المكونات

**تعلّم**

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

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

- [عارض الصفحات (postext-viewer)](https://postext.dev/ar/docs/integration-viewer.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**

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

**الخطوط**

- Spectral (OFL-1.1), Karla (OFL-1.1)

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

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

```js
// script.js, سطرًا 94–125
// A suggestion: [words that place it, the words it changes ('' inserts after them), the new
// text ('' deletes), accepted?]. A note: [the words it is on, what the editor wrote].
const [EDITS, NOTES] = t({
  en: [[
    ['always on the move', 'on the move', 'moving', true],
    ['slides on it', '', ' (basal sliding)', true],
    ['the speed doubles', 'doubles', 'can double', true],
    ['like a very stiff', 'very ', '', false],
  ], [
    ['a stake hammered into the surface', 'A photograph of a survey stake?'],
    ['the speed doubles for a few days', 'Which glaciers? Give a source.'],
    ['between 30 and 200 metres a year', 'Name one glacier as an example.'],
  ]],
  es: [[
    ['siempre en movimiento', 'en movimiento', 'moviéndose', true],
    ['resbala sobre ella', '', ' (deslizamiento basal)', true],
    ['la velocidad se duplica', 'se duplica', 'puede duplicarse', true],
    ['líquido muy rígido', 'muy ', '', false],
  ], [
    ['una estaca clavada en la superficie', '¿Una foto de una estaca de medición?'],
    ['la velocidad se duplica durante unos días', '¿En qué glaciares? Falta la fuente.'],
    ['entre 30 y 200 metros al año', 'Pon un glaciar concreto como ejemplo.'],
  ]],
});
const place = (around, words) => {
  const at = markdown.indexOf(around) + (words ? around.indexOf(words) : around.length);
  return { start: at, end: at + words.length };
};
const edits = EDITS.map(([around, words, text, accepted]) =>
  ({ ...place(around, words), text, accepted }));
const notes = NOTES.map(([words, body]) =>
  ({ body, anchor: textAnchor(markdown, place(words, words)) }));
```

يضع الـ pen كل سجل على المسودة بحسب كلماته، كما يقرؤه نظام إدارة المحتوى من جداوله. يصير المقترح تعديلًا `{ start, end, text }`: الطرفان المتساويان يعنيان إدراجًا، والنص الفارغ يعني حذفًا. وتحفظ الملاحظة `textAnchor`، أي مداها مع كلماته وشيئًا من السياق.

### 2 · طبّق التعديلات المقبولة باستدعاء واحد

الشيفرة هي [الجواب المختصر](https://postext.dev/ar/cookbook/applying-accepted-edits.md#الجواب-المختصر) أعلاه. تأخذ `applyEdits` كل التعديلات بمواضع المسودة وبأي ترتيب، فلا يحتاج الموقع أبدًا إلى إزاحة تعديل بسبب آخر. وتعيد Markdown الجديد، و`map` لأي موضع آخر، وكل مرساة منقولة عبر التعديلات: مزاحة بقدر ما أضافته التعديلات السابقة أو حذفته، و`touched` إذا وقع تعديل داخلها. لا حاجة إلى بحث، فلا يمكن لمرساة نُقلت هكذا أن تصير ملتبسة. وتضع `mapOffset` مع `'before'` كل نص جديد حيث يبدأ الآن.

### 3 · بيّن معنى الألوان

```js
// script.js, سطرًا 181–190
const legend = t({
  en: [['Draft', '3 edits accepted, 1 declined (grey) · notes 1–3'],
    ['After applyEdits', 'green: applied · 2?: an edit fell inside note 2 · grey: still open']],
  es: [['Borrador', '3 cambios aceptados, 1 rechazado (gris) · notas 1–3'],
    ['Tras applyEdits', 'verde: aplicado · 2?: un cambio dentro de la nota 2 · gris: pendiente']],
});
for (const [i, [title, text]] of legend.entries()) {
  document.querySelectorAll('#pages h2')[i].textContent = title;
  document.querySelectorAll('#pages p')[i].textContent = text;
}
```

تحمل الملاحظة الملموسة علامة استفهام في رايتها ولونًا آخر. أما هل ما زالت الملاحظة تصلح لـ «can double» فتقرره المحررة؛ ولا يفعل Postext سوى الإبلاغ بأن الكلمات تغيّرت. والتعديلات المتداخلة ترمي `RangeError`، لأن تصحيحين للكلمات نفسها يحتاجان إلى من يختار بينهما.

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

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

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

### index.html

```html
<main id="pages">
  <section>
    <header><h2></h2><p></p></header>
    <div id="before" class="pane"></div>
  </section>
  <section>
    <header><h2></h2><p></p></header>
    <div id="after" class="pane"></div>
  </section>
</main>
```

### style.css

```css
/* The host's frame: the draft and the new text side by side, each viewer under a legend. */
main#pages {
  display: grid; grid-template-columns: 1fr 1fr; height: max(560px, calc(100vh - 44px));
  gap: 0; padding: 0; justify-items: stretch;
}
#pages section { display: flex; flex-direction: column; min-height: 0; min-width: 0; }
#pages section + section { border-left: 1px solid #23262d; }
#pages header { padding: 12px 16px 10px; background: #15181d; border-bottom: 1px solid #23262d; }
#pages h2 { margin: 0; font: 600 13px/1.3 system-ui, sans-serif; letter-spacing: .08em;
  text-transform: uppercase; color: #f4f1ea; }
#pages header p { margin: 4px 0 0; font: 13px/1.4 system-ui, sans-serif; color: #a9aeb8; }
.pane { flex: 1; min-height: 0; }
.pane .postext-viewer { --pv-background: #0e1014; --pv-focus: #e0a43a; }
```

### script.js

```js
// ═══ Postext Cookbook · Nº 218 · Applying accepted edits ═════════════════════════════
// https://postext.dev/en/cookbook/applying-accepted-edits
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Spectral, Karla (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A magazine piece with four suggested edits and three editor's notes. Three edits are
// accepted and written into the Markdown with applyEdits; the notes and the declined edit are
// carried through as anchors, without a search, and a note an edit fell inside comes back
// flagged as touched. The draft and the new text are laid out side by side, each with its marks.
import { buildDocumentWithFonts, renderPageToCanvas } from 'https://esm.sh/postext';
import { textAnchor, applyEdits, mapOffset } 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 = 'applying-accepted-edits';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#1c1f24', // text
  accent: '#2b5f8a', // glacier blue: title, subheads, folios
  muted: '#677080', // 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.4; // pt of body leading

const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'Karla', fontSize: pt(7), fontWeight: 500, letterSpacing: pt(0.9),
  textTransform: 'uppercase', color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(10) } }, ...extra });
const folio = { fontWeight: 700, color: col('accent') };

const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(130), height: mm(190), dpi: 150,
    margins: { top: mm(18), bottom: mm(18), left: mm(16), right: mm(14), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Spectral', fontSize: pt(9.4), 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: 'Karla', color: col('accent'), fontWeight: 700, levels: [
    { level: 1, fontFamily: 'Spectral', fontWeight: 600, fontSize: pt(21), lineHeight: pt(25),
      marginTop: mm(12), marginBottom: pt(LEAD) },
    { level: 2, fontSize: pt(8.5), lineHeight: pt(LEAD), letterSpacing: pt(0.5),
      textTransform: 'uppercase', marginTop: pt(LEAD), marginBottom: pt(0) },
  ] },
  header: { elements: [
    head('verso-folio', '{pageNumber}', 'even', 'top-left', 14, folio),
    head('verso-title', '{title}', 'even', 'top-left', 21),
    head('recto-chapter', '{chapterTitle}', 'odd', 'top-right', -21),
    head('recto-folio', '{pageNumber}', 'odd', 'top-right', -14, folio),
  ] },
  footer: { elements: [] },
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "Field Notes on Ice"
author: "Ingrid Solberg"
---

# How a glacier moves

A glacier looks as still as the rock around it, but it is always on the move. Snow that falls on its upper basin is buried by the next winter’s snow, pressed into grains called firn, and after some decades turned into dense blue ice. That ice flows downhill, too slowly for anyone to see, but fast enough that a stake hammered into the surface stands somewhere else a month later.

## Ice that bends

Ice is brittle in a freezer tray and in the top layer of a glacier, where it cracks into crevasses. Deeper down, under the weight of the ice above, it behaves differently. Once a glacier is about 50 metres thick, the crystals near its bed start to slip along their own internal layers, and the ice deforms like a very stiff liquid. The surface moves fastest and the bed slowest, and the middle of the glacier moves faster than its edges, where the valley walls hold it back.

## Ice that slides

A second motion happens at the bed. Where the base of the glacier is at the melting point, a thin film of water lies between ice and rock, and the whole glacier slides on it. In summer, meltwater from the surface drains down through cracks and through shafts called moulins, and raises the water pressure at the bed. On some Alpine glaciers the speed doubles for a few days after warm weather, then falls back when the channels under the ice open up and carry the water away.

## Measuring the flow

The first measurements were made with lines of stakes across the ice, surveyed year after year from fixed points on the valley sides. Today satellites compare two radar images taken a few days apart and map the movement of the whole surface at once. A typical valley glacier in the Alps moves between 30 and 200 metres a year. The fastest outlet glaciers of Greenland have been measured at more than 40 metres a day.

## Why the front retreats

The ice keeps flowing even while a glacier shrinks. Its front retreats when more ice melts there each summer than the flow brings down from above. A glacier can therefore move forward and lose ground at the same time, like a person walking down an escalator that runs upward a little faster.

The meltwater tells the same story. A stream that leaves a retreating glacier carries more water in a hot August than it did a century ago, because it drains ice that is not being replaced. Its flow rises for decades as the glacier thins, peaks, and then falls away as the ice that feeds it runs out. Several valleys in the Alps have already passed that peak.
`; // content.<lang>.md, the draft

// #region records: the host's suggestions and notes, each kept as an anchor on the draft
// A suggestion: [words that place it, the words it changes ('' inserts after them), the new
// text ('' deletes), accepted?]. A note: [the words it is on, what the editor wrote].
const [EDITS, NOTES] = t({
  en: [[
    ['always on the move', 'on the move', 'moving', true],
    ['slides on it', '', ' (basal sliding)', true],
    ['the speed doubles', 'doubles', 'can double', true],
    ['like a very stiff', 'very ', '', false],
  ], [
    ['a stake hammered into the surface', 'A photograph of a survey stake?'],
    ['the speed doubles for a few days', 'Which glaciers? Give a source.'],
    ['between 30 and 200 metres a year', 'Name one glacier as an example.'],
  ]],
  es: [[
    ['siempre en movimiento', 'en movimiento', 'moviéndose', true],
    ['resbala sobre ella', '', ' (deslizamiento basal)', true],
    ['la velocidad se duplica', 'se duplica', 'puede duplicarse', true],
    ['líquido muy rígido', 'muy ', '', false],
  ], [
    ['una estaca clavada en la superficie', '¿Una foto de una estaca de medición?'],
    ['la velocidad se duplica durante unos días', '¿En qué glaciares? Falta la fuente.'],
    ['entre 30 y 200 metros al año', 'Pon un glaciar concreto como ejemplo.'],
  ]],
});
const place = (around, words) => {
  const at = markdown.indexOf(around) + (words ? around.indexOf(words) : around.length);
  return { start: at, end: at + words.length };
};
const edits = EDITS.map(([around, words, text, accepted]) =>
  ({ ...place(around, words), text, accepted }));
const notes = NOTES.map(([words, body]) =>
  ({ body, anchor: textAnchor(markdown, place(words, words)) }));
// #endregion

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = {
  Spectral: ['400', '600'],
  Karla: ['500', '700'],
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const before = await buildDocumentWithFonts({ markdown }, config, kitFonts(FONTS));
kitStatus(t({ en: 'Three edits accepted, the notes carried', es: 'Tres cambios aceptados' }));

const GREY = '#8a8f98';
const suggestion = (e, id) => ({ id, range: e, color: e.accepted ? undefined : GREY,
  ...(e.start === e.end ? { kind: 'insert', text: e.text }
    : e.text ? { kind: 'replace', text: e.text } : { kind: 'strike' }) });
const openPages = (id, doc, md, annotations) => createViewer(document.getElementById(id), {
  document: doc, markdown: md, annotations, zoom: 'fit-width', maxZoom: 1.2, gap: 18,
  marks: { fontFamily: 'Karla' },
  labels: t({ en: {}, es: { page: 'Página {n} de {count}', kinds: { note: 'Nota',
    replace: 'Sustitución', insert: 'Inserción', strike: 'Supresión',
    highlight: 'Cambio aplicado' } } }) });
openPages('before', before, markdown, [...edits.map((e, i) => suggestion(e, `e${i}`)),
  ...notes.map((n, i) => ({ id: `n${i}`, kind: 'note', range: n.anchor, label: `${i + 1}` }))]);

// #region answer: write the accepted edits and carry everything else through them
const accepted = edits.filter((e) => e.accepted);
const declined = edits.filter((e) => !e.accepted);
const kept = [...notes.map((n) => n.anchor), ...declined.map((e) => textAnchor(markdown, e))];
// One call: the new Markdown, a map of old offsets to new ones, and every anchor carried.
const { markdown: next, map, anchors } = applyEdits(markdown, accepted, kept);
const after = await buildDocumentWithFonts({ markdown: next }, config, kitFonts(FONTS));
const marks = [
  // The text each accepted edit put in, where it now is.
  ...accepted.map((e, i) => {
    const start = mapOffset(map, e.start, 'before');
    return { id: `a${i}`, kind: 'highlight', range: { start, end: start + e.text.length },
      color: '#1f8a4c' };
  }),
  // The notes: a note an edit fell inside is touched, for a person to read again.
  ...notes.map((n, i) => {
    const { anchor, touched } = anchors[i];
    return { id: `n${i}`, kind: 'note', range: anchor, label: touched ? `${i + 1}?` : `${i + 1}`,
      color: touched ? '#c4720a' : undefined };
  }),
  // The declined edit stays open on the new text.
  ...declined.map((e, k) => {
    const { start, end } = anchors[notes.length + k].anchor;
    return suggestion({ ...e, start, end }, `d${k}`);
  }),
];
openPages('after', after, next, marks);
// #endregion

// #region legends: what each column shows, in the edition's language
const legend = t({
  en: [['Draft', '3 edits accepted, 1 declined (grey) · notes 1–3'],
    ['After applyEdits', 'green: applied · 2?: an edit fell inside note 2 · grey: still open']],
  es: [['Borrador', '3 cambios aceptados, 1 rechazado (gris) · notas 1–3'],
    ['Tras applyEdits', 'verde: aplicado · 2?: un cambio dentro de la nota 2 · gris: pendiente']],
});
for (const [i, [title, text]] of legend.entries()) {
  document.querySelectorAll('#pages h2')[i].textContent = title;
  document.querySelectorAll('#pages p')[i].textContent = text;
}
// #endregion

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

## تنويعات

### احفظ المراسي المنقولة

يكتب الموقع كل مرساة منقولة في صفها من جديد، لتبدأ المراجعة التالية من النص الجديد.

```diff
 const { markdown: next, map, anchors } = applyEdits(markdown, accepted, kept);
+notes.forEach((n, i) => { n.anchor = anchors[i].anchor; }); // write these back to the rows
```

## الحقوق

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

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

- [رقم 214 · علامات التصحيح: الشطب والاستبدال والإدراج](https://postext.dev/ar/cookbook/proofreading-marks-on-pages.md): تصحيحات محرّر مرسومة على صفحة قصة مُخرَجة في postext-viewer: كلمات مشطوبة، وبدائل مكتوبة فوقها، وعلامات إدراج، انطلاقًا من نطاقات Markdown. · المستوى 2 (متوسط) · الأدب القصصي والمسرح والنثر الأدبي
- [رقم 215 · ملاحظات في الهامش، ونافذة منبثقة تُوضع من إحداثيات الصفحة](https://postext.dev/ar/cookbook/margin-notes-with-popovers.md): تلوّن علامات الملاحظات كلماتها وتضع راية في الهامش الخارجي؛ والضغط يفتح الملاحظة في نافذة منبثقة تحت الكلمات بواسطة rangeRects وpageToClient. · المستوى 2 (متوسط) · الكتالوجات
- [رقم 223 · قلم تظليل للقارئ: مقطع ولون](https://postext.dev/ar/cookbook/reader-highlighter.md): تحدّد كلمات من رواية فتنفتح فوقها أربعة ألوان؛ ويمتد التظليل إلى كلمات كاملة، ويُحفظ مرساةً، وينضم إلى قائمة بجانب الصفحات. · المستوى 2 (متوسط) · الأدب القصصي والمسرح والنثر الأدبي
