# Принять правки и перенести вместе с ними остальные заметки

> applyEdits вносит принятые исправления в Markdown и переносит якорь каждой другой заметки, отмечая заметки, внутрь которых попала правка.

- Версия HTML: https://postext.dev/ru/cookbook/applying-accepted-edits
- Рецепт № 218 · Интеграция с CMS · Уровень 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), [zh](https://postext.dev/zh/cookbook/applying-accepted-edits.md), [ja](https://postext.dev/ja/cookbook/applying-accepted-edits.md), [ar](https://postext.dev/ar/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/ru/docs/integration-anchors.md#якоря-и-правки): textAnchor хранит диапазон вместе с цитатой и контекстом, чтобы resolveAnchor нашёл его в исправленном тексте; applyEdits вносит принятые правки, а mapOffset переносит остальные позиции.
- [Пометки на тексте](https://postext.dev/ru/docs/integration-marks.md#пометки): Подсветка, подчёркивание, зачёркивание, замены, вставки, заметки и рамки, уложенные на текст страниц, нарисованные на canvas или записанные как SVG поверх изображений страниц.

**Также используются**

- [Просмотрщик страниц (postext-viewer)](https://postext.dev/ru/docs/integration-viewer.md#просмотрщик-страниц)
- [Страницы на холсте](https://postext.dev/ru/docs/configuration-programmatic-usage.md#рендеринг-страницы-в-растр)
- [Шрифты до вёрстки](https://postext.dev/ru/docs/configuration-programmatic-usage.md#загрузка-шрифтов-перед-вёрсткой)
- [Колонтитулы и колонцифры](https://postext.dev/ru/docs/configuration-headers-footers.md#верхние-и-нижние-колонтитулы)
- [Зеркальные поля](https://postext.dev/ru/docs/configuration-page-layout.md#зеркальные-поля)
- [Семантическая палитра](https://postext.dev/ru/docs/configuration-fonts-colors-viewers.md#палитра-цветов)
- [Колонтитулы по роли страницы](https://postext.dev/ru/docs/configuration-headers-footers.md#текстовые-элементы)

**Конфигурация вкратце**

- [`bodyText`](https://postext.dev/ru/docs/configuration-text.md#основной-текст), [`colorPalette`](https://postext.dev/ru/docs/configuration-fonts-colors-viewers.md#палитра-цветов), [`footer`](https://postext.dev/ru/docs/configuration-headers-footers.md#верхние-и-нижние-колонтитулы), [`header`](https://postext.dev/ru/docs/configuration-headers-footers.md#верхние-и-нижние-колонтитулы), [`headings`](https://postext.dev/ru/docs/configuration-headings.md#заголовки), [`layout`](https://postext.dev/ru/docs/configuration-page-layout.md#колонки), [`locale`](https://postext.dev/ru/docs/configuration-language.md#перенос-слов), [`page`](https://postext.dev/ru/docs/configuration-page-layout.md#страница)

**API**

- `annotations`, `applyEdits`, [`buildDocumentWithFonts`](https://postext.dev/ru/docs/configuration-programmatic-usage.md#загрузка-шрифтов-перед-вёрсткой), `createViewer`, `mapOffset`, [`renderPageToCanvas`](https://postext.dev/ru/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)) }));
```

Пен ставит каждую запись на черновик по её словам, как CMS прочитала бы их из своих таблиц. Предложение становится правкой `{ start, end, text }`: равные концы означают вставку, пустой текст — удаление. Заметка хранит `textAnchor`: свой диапазон со словами и немного контекста.

### 2 · Примените принятые правки одним вызовом

Код приведён в [коротком ответе](https://postext.dev/ru/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/ru/cookbook/proofreading-marks-on-pages.md): Правка редактора на свёрстанной странице рассказа в postext-viewer: вычеркнутые слова, замены, вписанные над ними, и знаки вставки по диапазонам Markdown. · Уровень 2 (Средний) · Художественная литература, драматургия и эссеистика
- [№ 215 · Заметки на полях и всплывающее окно по координатам](https://postext.dev/ru/cookbook/margin-notes-with-popovers.md): Заметки подкрашивают свои слова и ставят флажок на внешнем поле; нажатие открывает заметку во всплывающем окне под словами через rangeRects и pageToClient. · Уровень 2 (Средний) · Каталоги
- [№ 223 · Маркер для читателя: отрывок и цвет](https://postext.dev/ru/cookbook/reader-highlighter.md): Выделите слова в романе, и над ними откроются четыре цвета; выделение доводится до целых слов, хранится как якорь и попадает в список. · Уровень 2 (Средний) · Художественная литература, драматургия и эссеистика
