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

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

Заметки на полях и всплывающее окно по координатам

Заметки подкрашивают свои слова и ставят флажок на внешнем поле; нажатие открывает заметку во всплывающем окне под словами через rangeRects и pageToClient.

На этой странице
Конфигурация вкратце
bodyTextcolorPalettefooterheaderheadingslayoutlocalepage
Вывод
Canvas
Уровень
Средний
Postext
Проверено с Postext 1.103.1
Требуется ≥ 1.103.0
Лицензия
Обновлено 4 дек. 2026 г.
Код: MIT · Текст: CC BY 4.0
Четыре заметки рецензента к музейному тексту: каждая подкрашивает свои слова и ведёт пунктир к пронумерованному флажку на широком поле; заметка 2 открыта под своими словами.
Четыре заметки рецензента к музейному тексту: каждая подкрашивает свои слова и ведёт пунктир к пронумерованному флажку на широком поле; заметка 2 открыта под своими словами.
  • Образец на английском: русского издания пока нет
  • Обрезной формат 160 × 220 мм
  • 1 колонка
  • Alegreya 10,5/15
  • Alegreya Sans
  • 1 страница
  • Уровень
  • Postext 1.103.1
  • Свёрстано за 45 мс
  • Строк кода: 118

Коротко

Музейный текст для зала с заметками рецензентки. Каждая заметка подкрашивает свои слова и ставит пронумерованный ярлык на широком правом поле, соединённый пунктиром. Нажатие на ярлык открывает заметку в окошке прямо под её словами.

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

Музейный текст для зала об Антикитерском механизме так, как его видит редактор выставки вместе с заметками рецензентки. Каждая из четырёх заметок подкрашивает свои слова и ведёт пунктир к пронумерованному флажку на широком внешнем поле. Заметка 2 открыта: всплывающее окно с комментарием стоит прямо под словами, к которым относится, и указывает уголком на последнее. Нажмите другой флажок или подкрашенные слова, и окно переместится туда; прокрутите страницу или измените размер, и оно останется при своих словах.

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

  • Как поставить заметку или всплывающее окно рядом с фрагментом свёрстанной страницы?

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

script.js · строки 108–130в полном коде
const view = createViewer(document.getElementById('viewer'), {
  document: doc, markdown, zoom: 'fit-width', maxZoom: 1, labels: L.viewer,
  marks: { noteSide: 'end' }, // the flags in the outer margin, not the nearer one
  annotations: notes.map(({ id, label, range }) => ({ id, kind: 'note', range, label })),
});
let open = null; // the note the popover shows
const place = () => {
  if (!open) return;
  // Under the last piece of the noted words: page px, turned into the window's px.
  const last = rangeRects(doc, open.range).at(-1);
  const at = last && view.pageToClient(last.pageIndex, last.rect.x, last.rect.y + last.rect.height);
  pop.hidden = !at;
  if (at) Object.assign(pop.style, { left: `${at.x}px`, top: `${at.y + 8}px` });
};
const show = (id) => {
  open = notes.find((n) => n.id === id) ?? null;
  if (open) fill(open);
  place();
};
view.on('annotationclick', ({ id }) => show(id)); // a flag or the tinted words
view.on('zoomchange', place); // the pages moved under the popover
view.element.addEventListener('scroll', place, { capture: true, passive: true });
show('n2');

Ингредиенты

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

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

#1 · Оставьте поле для флажков

script.js · строки 29–49в полном коде
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(160), height: mm(220), dpi: 150,
    margins: { top: mm(20), bottom: mm(24), left: mm(18), right: mm(42) } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Alegreya', fontSize: pt(10.5), lineHeight: pt(15),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'left', firstLineIndent: mm(5), indentAfterHeading: false,
    hyphenation: { enabled: true }, avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: 'Alegreya Sans', color: col('accent'), fontWeight: 700, levels: [
    { level: 1, fontSize: pt(22), lineHeight: pt(26), marginTop: pt(4), marginBottom: pt(15) },
  ] },
  header: { elements: [] },
  footer: { elements: [
    { kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Alegreya Sans',
      fontSize: pt(8.5), fontWeight: 700, color: col('accent'), align: 'left',
      placement: { anchor: { to: 'page', edge: 'bottom-left' },
        offset: { x: mm(18), y: mm(-12) } } },
  ] },
};

Внешнее поле в 42 мм вмещает флажки, не стесняя текст. Параметр marks просмотрщика передаёт noteSide: 'end' в раскладку пометок, поэтому все флажки уходят на правое поле; без него каждый встаёт на поле, ближайшее к его строке. Флажки на одной высоте складываются вниз по полю без наложений, а слишком длинный ярлык обрезается многоточием.

#2 · Храните заметки как диапазоны с ярлыками

script.js · строки 80–96в полном коде
// A tool stores the offsets; the pen finds them from quotes so that both editions run.
const notes = t({
  en: [['In the spring of 1901', 'The wreck was found in 1900; the mechanism came up in 1901.'],
    ['a small ball, half silver and half dark',
      'Is the ball still there? If not, say it is reconstructed.'],
    ['nineteen-year calendar', 'Name it: the Metonic cycle. Readers will look it up.'],
    ['X-ray scans', 'Give the year of the scans, 2005.']],
  es: [['En la primavera de 1901', 'El naufragio se halló en 1900; el mecanismo salió en 1901.'],
    ['una bolita, mitad plateada y mitad oscura',
      '¿Se conserva la bolita? Si no, di que es una reconstrucción.'],
    ['calendario de diecinueve años', 'Dale su nombre: el ciclo metónico. El lector lo buscará.'],
    ['radiografías', 'Pon el año de las radiografías, 2005.']],
}).map(([quote, body], i) => {
  const start = markdown.indexOf(quote);
  const range = { start, end: start + quote.length };
  return { id: `n${i + 1}`, label: String(i + 1), body, range };
});

Пометке-заметке нужны диапазон и короткий label для флажка, номер или инициал. Сам комментарий, его автор и обсуждение остаются в записях сайта; пометка лишь говорит, куда они относятся.

#3 · Поставьте окно по координатам страницы

Код приведён в коротком ответе выше. rangeRects даёт куски помеченных слов в px страницы; нижний левый угол последнего куска, переданный в pageToClient, возвращается в px окна и годится для элемента с position: fixed. Просмотрщик сообщает начальный масштаб в первом кадре, так что слушатель zoomchange заново ставит первое окно, когда страницы нарисованы, а слушатель прокрутки на view.element держит его под словами.

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

// ═══ Postext Cookbook · Nº 215 · Notes in the margin, with a popover ═════════════════
// https://postext.dev/en/cookbook/margin-notes-with-popovers
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Alegreya, Alegreya Sans (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A museum's gallery text with a reviewer's notes on it: each note tints its words and
// puts a numbered flag in the outer margin. Pressing a flag opens the note in a popover,
// which the host places under the words from their page coordinates. Note 2 opens itself.
import { buildDocumentWithFonts, renderPageToCanvas, 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 = 'margin-notes-with-popovers';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#211f1c', // text
  accent: '#9a4b16', // bronze: title and folio
};
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

// #region page: a wide outer margin, where the reviewer's flags go
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(160), height: mm(220), dpi: 150,
    margins: { top: mm(20), bottom: mm(24), left: mm(18), right: mm(42) } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Alegreya', fontSize: pt(10.5), lineHeight: pt(15),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'left', firstLineIndent: mm(5), indentAfterHeading: false,
    hyphenation: { enabled: true }, avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: 'Alegreya Sans', color: col('accent'), fontWeight: 700, levels: [
    { level: 1, fontSize: pt(22), lineHeight: pt(26), marginTop: pt(4), marginBottom: pt(15) },
  ] },
  header: { elements: [] },
  footer: { elements: [
    { kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Alegreya Sans',
      fontSize: pt(8.5), fontWeight: 700, color: col('accent'), align: 'left',
      placement: { anchor: { to: 'page', edge: 'bottom-left' },
        offset: { x: mm(18), y: mm(-12) } } },
  ] },

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

Варианты

#Открывайте заметку при наведении

Событие hover несёт id пометок под указателем, верхнюю первой.

 view.on('annotationclick', ({ id }) => show(id)); // a flag or the tinted words
+view.on('hover', ({ annotations }) => annotations[0] && show(annotations[0]));

#Пусть каждый флажок встаёт на ближайшее поле

На странице в две колонки заметки левой колонки тогда уйдут на левое поле.

-  marks: { noteSide: 'end' }, // the flags in the outer margin, not the nearer one
+  marks: {}, // each flag in the margin nearer its words

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

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