Перейти к основному содержанию
Рецепт номер 216

Рецепты · Глава 13 · Интеграция с CMS

Щелчок по странице ведёт к исходному тексту

sourceAt и caretAt превращают щелчок по свёрстанной странице в блок Markdown и позицию; CMS показывает эту строку исходника с пометкой.

На этой странице
Щелчок по «a large correction» на странице 1: блок подкрашен на странице, курсор отмечает смещение, а исходник рядом показывает тот же блок и цепочку text › line › block.
Щелчок по «a large correction» на странице 1: блок подкрашен на странице, курсор отмечает смещение, а исходник рядом показывает тот же блок и цепочку text › line › block.
  • Образец на английском: русского издания пока нет
  • Обрезной формат 148 × 210 мм
  • 1 колонка
  • Source Serif 4 9,5/13,5
  • IBM Plex Sans
  • 2 страницы
  • Уровень
  • Postext 1.103.1
  • Свёрстано за 78 мс
  • Строк кода: 145

Коротко

Глава из руководства по ремонту велосипеда, показанная страницами, а рядом текст, из которого они собраны. Щелчок по слову на странице находит это же слово в тексте, отмечает его абзац и называет номер строки.

Что получится

Глава из The Home Bicycle Workshop на странице 148 × 210 мм, слева в postext-viewer, справа её Markdown, как его хранила бы редакционная система. Щелчок в любом месте страницы переносит панель исходника к строке под указателем: абзац подкрашивается с обеих сторон, зелёный курсор встаёт у символа, а две строки состояния называют строку, столбец и позицию, а также цепочку того, что нарисовано в этой точке. На карточке щелчок уже сделан посреди абзаца третьего раздела.

Рецепт отвечает на вопросы

  • Как узнать, на какую часть Markdown пришёлся щелчок по странице?

Короткий ответ

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));

Ингредиенты

Шрифты
Source Serif 4, IBM Plex Sans (SIL OFL 1.1)
Материалы
Нет: все иллюстрации рисует код

Порядок работы

#1 · Сверстайте главу в собственном оформлении

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 · Спросите вёрстку, что лежит под точкой

Код приведён в коротком ответе выше. Событие click просмотрщика даёт страницу и точку в пикселях страницы, и два вызова читают вёрстку в этой точке. sourceAt перечисляет то, что нарисовано там, изнутри наружу: глиф, его строку, его блок, врезку вокруг. Абзац, разорванный между двумя страницами, отвечает всем своим диапазоном, а колонтитул отвечает записью конфигурации, которая его поставила, а не Markdown. caretAt даёт ближайшую границу между символами, как щелчок в текстовом редакторе. Оба считают единицы UTF-16 файла вместе с front matter, поэтому строка и столбец берутся из самого Markdown.

#3 · Покажите строку в исходнике

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;
}

Панель режет каждую строку там, где блок начинается и кончается и где стоит курсор, так что пометка и курсор приходятся на те же символы, что показывает страница. Те же два диапазона возвращаются в просмотрщик как выделение цветом и знак вставки, и читатель проверяет, что переход попал туда, куда он хотел.

Рецепт целиком

// ═══ 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,

Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)

Варианты

#Отмечайте слово, а не абзац

wordAt расширяет позицию до слова под точкой, с учётом языка документа.

-  const block = chain.find((e) => e.level === 'block' && e.source.kind === 'markdown')?.source;
+  const block = wordAt(doc, pageIndex, x, y, markdown); // import wordAt from postext

#Отмечайте напечатанную строку

Элемент line в цепочке — это отрезок Markdown, из которого набрана одна строка страницы; на него и указывает корректор.

-  const block = chain.find((e) => e.level === 'block' && e.source.kind === 'markdown')?.source;
+  const block = chain.find((e) => e.level === 'line' && e.source.kind === 'markdown')?.source;

Источники и лицензии

Рецепт
Ignacio Ferro
Текст
Оригинальный текст, CC BY 4.0
Шрифты
Source Serif 4 (SIL OFL 1.1) · IBM Plex Sans (SIL OFL 1.1)