本文へスキップ
レシピ番号215

レシピ集 · 第13章 · CMSへの組み込み

余白のメモと、ページ座標から置くポップオーバー

メモの印は語句を薄く塗り、外側の余白に旗を立てる。押すと、rangeRects と pageToClient で語句の下に置いたポップオーバーにメモが開く。

このページの内容
ジャンル
カタログ
出力
Canvas
レベル
中級
Postext
Postext 1.103.1で検証済み
1.103.0以上が必要
ライセンス
2026年12月4日更新
コードMIT · 本文CC BY 4.0
博物館の解説文に付けた査読者のメモ四つ:それぞれ自分の語句を塗り、広い余白の番号付きの旗へ破線を引く。メモ2はその語句の下に開いている。
博物館の解説文に付けた査読者のメモ四つ:それぞれ自分の語句を塗り、広い余白の番号付きの旗へ破線を引く。メモ2はその語句の下に開いている。
  • 英語の見本:日本語版はまだありません
  • 仕上がり160 × 220 mm
  • 1段
  • Alegreya 10.5/15
  • Alegreya Sans
  • 1ページ
  • レベル
  • Postext 1.103.1
  • 組版時間45 ms
  • コード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 mm の外側の余白なら、本文を詰めずに旗が収まります。ビューアーの 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]));

#各旗を近いほうの余白に立てる

2段組のページなら、左の段のメモは左の余白に立ちます。

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