本文へスキップ

章 24.4 · 部 III · 実践

連携:ページビューアー

postext-viewer:ページを表示し、選択と押下をMarkdownの範囲とオフセットで知らせ、注釈のマークを描き、ホスト用のレイヤーを各ページの上に用意し、ページ座標と画面座標を変換する埋め込み用のビューアー。Reactコンポーネントつき

更新日 2026-12-0412分所属する章: 24 連携enescadeelfritptruzhjaar

かんたんな説明

このページは開発者向けです。1回の呼び出しで本のページをWebページの中に置ける、できあいのビューアーを紹介します。使う人はスクロールし、拡大縮小し、言葉を選ぶことができ、システムはそれがテキストのどの言葉かを知ることができます。システムはページの上に自分のマークを描き、自分のボタンを重ねて置けます。ビューアーはキーボードでも、スクリーンリーダーでも使えます。

postext-viewerはページを表示し、Markdownの範囲で伝えます。何が選ばれたか、何が押されたか、マークをどこに置くか。

npm install postext postext-viewer
import { buildDocument } from 'postext';
import { createViewer } from 'postext-viewer';
 
const doc = buildDocument({ markdown }, config);
const viewer = createViewer(document.getElementById('pages'), { document: doc, markdown });
 
viewer.on('select', ({ range, text }) => {
  console.log(range, text); // { start: 52, end: 65 } 'hives at dawn'
});

ビューアーはコンテナいっぱいに広がるので、コンテナに高さを与えてください。ページはスクロールする縦の列に並び、renderPageToCanvasで、表示する大きさに画面のピクセル比を掛けた解像度で描かれます。描くのは見えているページと、その前後2ページずつだけです(overscan)。離れたページはメモリーを手放すので、600ページの本でもcanvasは数ページ分で済みます。

renderPageと同じく、ビューアーが描く前に、文書が使うフォントを読み込み、画像を登録しておきます(document.fonts.load、registerResourceImage)。

Postext · 埋め込み用のページビューアー
import { buildDocument } from 'https://esm.sh/postext';
import { createViewer } from 'https://esm.sh/postext-viewer';
 
const paragraph = 'The keeper walked the hives at dawn, lifting each lid with care and reading the frames for brood, honey and the queen. A hive that hums low in the cold keeps its cluster tight; one that roars at noon wants more room before the flow.';
const markdown = ['# The apiary', ...Array.from({ length: 10 }, () => paragraph)].join('\n\n');
 
const config = {
  page: { width: { value: 120, unit: 'mm' }, height: { value: 170, unit: 'mm' } },
  bodyText: { fontFamily: 'EB Garamond', fontSize: { value: 11, unit: 'pt' }, lineHeight: { value: 15, unit: 'pt' } },
};
 
// Postext measures text with the fonts the browser has loaded.
await Promise.all([
  document.fonts.load('16px "EB Garamond"'),
  document.fonts.load('italic 16px "EB Garamond"'),
  document.fonts.load('bold 16px "Open Sans"'),
]);
 
const doc = buildDocument({ markdown }, config);
// Fitted to the width, but never larger than 1.4 CSS px per page px.
const viewer = createViewer(document.getElementById('pages'), { document: doc, markdown, maxZoom: 1.4 });
 
// The host's own records. Postext only sees ranges and kinds.
const marks = [];
let selected = null;
 
const selection = document.getElementById('selection');
const highlight = document.getElementById('highlight');
const note = document.getElementById('note');
const list = document.getElementById('marks');
 
viewer.on('selectionchange', ({ range, text }) => {
  selected = range;
  const shown = text.length > 80 ? `${text.slice(0, 80)}…` : text;
  selection.textContent = range ? `“${shown}” (Markdown ${range.start}–${range.end})` : 'Select some words on the page.';
  highlight.disabled = note.disabled = !range;
});
 
function add(kind) {
  if (!selected) return;
  const id = `m${marks.length + 1}`;
  marks.push({ id, kind, range: selected, label: kind === 'note' ? String(marks.length + 1) : undefined });
  viewer.setAnnotations(marks);
  viewer.setSelection(null);
  draw();
}
highlight.addEventListener('click', () => add('highlight'));
note.addEventListener('click', () => add('note'));
 
function draw() {
  list.replaceChildren(...marks.map((m) => {
    const li = document.createElement('li');
    const go = document.createElement('button');
    go.textContent = `${m.kind}: ${markdown.slice(m.range.start, m.range.end)}`;
    go.addEventListener('click', () => viewer.revealAnnotation(m.id, { behavior: 'smooth' }));
    li.append(go);
    return li;
  }));
}
 
// A press on a mark, with the pointer or the keyboard.
viewer.on('annotationclick', ({ id }) => {
  const i = marks.findIndex((m) => m.id === id);
  list.children[i]?.querySelector('button')?.focus();
});
index.html
<main>
  <div id="pages"></div>
  <aside>
    <p id="selection">Select some words on the page.</p>
    <div class="actions">
      <button id="highlight" disabled>Highlight</button>
      <button id="note" disabled>Note</button>
    </div>
    <ol id="marks"></ol>
  </aside>
</main>
style.css
body {
  margin: 0;
  font-family: system-ui, sans-serif;
  color: #1d1d1f;
}
main {
  display: grid;
  grid-template-columns: 1fr 240px;
  height: 100vh;
}
/* The viewer fills its container: give it a height. */
#pages {
  height: 100vh;
  min-width: 0;
  --pv-background: #ecebe6;
}
aside {
  padding: 16px;
  border-left: 1px solid #d8d6cf;
  overflow: auto;
  font-size: 14px;
}
#selection {
  min-height: 3.5em;
  color: #555;
}
.actions {
  display: flex;
  gap: 8px;
}
button {
  min-height: 44px;
  padding: 0 14px;
  font: inherit;
  border: 1px solid #2f6fd6;
  border-radius: 6px;
  background: #fff;
  color: #1f4f9e;
  cursor: pointer;
}
button:disabled {
  border-color: #c8c6bf;
  color: #8a8880;
  cursor: default;
}
#marks {
  padding-left: 20px;
}
#marks li {
  margin: 8px 0;
}
#marks button {
  min-height: 32px;
  border: 0;
  padding: 0;
  text-align: left;
  color: #1d1d1f;
  text-decoration: underline;
}

codepen.ioからインタラクティブなエディターを読み込みます。サンプルは最新リリースのpostextをCDNから読み込みます。

#オプション

オプション既定値働き
document組まれた文書。
markdown文書を組んだもとのMarkdown。ダブルクリックでの語の選択、選択したテキスト、コピーに必要です。
annotations[]postext/annotateのマーク。
zoom'fit-width'数値(ページpxあたりのCSS px)、'fit-width'、'fit-page'のいずれか。
minZoom、maxZoom0.1、8数値で指定する倍率の下限と上限。
gap16ページの間と周りのCSS px。
trimfalse裁ち落としとトンボを除いた仕上がりのページを表示する。座標は用紙のままです。
selectabletrueドラッグでテキストを選ぶかどうか。
overscan2見えているページの前後それぞれに、余分に描くページ数。
renderrenderPageToCanvasのオプション(singleInk、printPreview、finishes…)。
geometry本の1章を表示するときの{ ownChapter }(ページ上のテキストを参照)。
markslayoutAnnotationsのオプション(fontFamily、noteSide、paper…)。
layers[]ホストのレイヤー。下から上の順。
labels英語ビューアーが読み上げ、名前に使う言葉。ホストの言語に合わせます。
copyTextMarkdown(range, markdown) => string:コピーでクリップボードに入れるもの。

#イベント

viewer.on(type, handler)は、そのハンドラーを外す関数を返します。

イベント発生するとき渡すもの
selectionchange選択が変わったとき。ドラッグ中も発生します。range(またはnull)、text、rects
select選択が確定したとき。ポインターを離した、語をダブルクリックした、Shift + 矢印キー。同上
clickページ上で押したとき。pageIndex、x、y(ページpx)、offset、chapter、blockId、annotations(id、上にあるものが先)、originalEvent
hoverポインターが別のブロックや別のマークに移ったとき。clickと同じ
annotationclickポインターかキーボードでマークを押したとき。id、annotation、pageIndex、originalEvent
pagechangeいちばん大きく見えているページが変わったとき。pageIndex
zoomchange倍率が変わったとき(呼び出し、または合わせるモードでのサイズ変更)。zoom
renderページを描いたとき。pageIndex

最初のページはcreateViewerの次のフレームで描かれるので、その直後に加えたハンドラーも最初のrenderとpagechangeを受け取れます。

選択をコメントにする、ホスト側のコードの全体です。

viewer.on('select', async ({ range }) => {
  if (!range) return;
  const body = prompt('Comment');
  if (!body) return;
  const anchor = textAnchor(markdown, range);
  const saved = await api.createComment({ chapter, anchor, body }); // ホスト独自のAPI
  viewer.setAnnotations([...viewer.annotations, { id: saved.id, kind: 'note', range, label: String(saved.number) }]);
  viewer.setSelection(null);
});
viewer.on('annotationclick', ({ id }) => openThread(id));

#メソッド

メソッド働き
setDocument(doc, markdown?)新しいレイアウトを表示する(編集のあと)。見えているページ、選択のオフセット、マークは保たれます。
setMarkdown(md)組み直さずにMarkdownを替える。
setAnnotations(list)、annotationsマークを置き換える。
setSelection(range)、selectionコードから範囲を選ぶ。nullで解除。
setZoom(zoom)、zoom見えている位置を保ったまま拡大縮小する。
goToPage(i)、pageIndexページまでスクロールする。
revealRange(range)、revealAnnotation(id)範囲やマークが見えるところまでスクロールする。どのページにもなければfalse。
rangeRects(range)表示中の文書に対するrangeRects。
pageToClient(page, x, y)、clientToPage(x, y)ページpxとビューポートpxの相互変換。ポップオーバーの配置に使う。
pageElement(i)ページの要素。
addLayer(layer)、removeLayer(id)、refreshLayers()ホストのレイヤー。
destroy()ビューアーを取り除き、canvasを解放する。

#ホストのレイヤー

レイヤーは、ホストが持つものをページの上に描きます。コメントのピン、共同作業者のカーソル、翻訳メモリーの一致箇所の枠などです。

viewer.addLayer({
  id: 'pins',
  // ページpxのcanvasに、マークより上に描く
  paint(ctx, { pageIndex, page }) {
    for (const c of commentsOn(pageIndex)) {
      ctx.fillStyle = c.color;
      ctx.beginPath();
      ctx.arc(page.width - 24, c.y, 7, 0, Math.PI * 2);
      ctx.fill();
    }
  },
  // ページの上のDOM。そのCSS pxはページpx
  mount(el, { pageIndex }) {
    const root = createRoot(el);
    root.render(<Avatars page={pageIndex} />);
    return () => root.unmount();
  },
});

mountはページが描画の範囲に入ったときに実行され、その戻り値はページが範囲を出たときに実行されます。そのため、長い本でもホストのDOMは数ページ分を超えません。refreshLayers()は、ホストのデータが変わったあとでレイヤーを描き直し、マウントし直します。

#キーボードとスクリーンリーダー

  • ビューアーはフォーカスできる領域で、名前はlabels.viewerです。各ページには「Page 3 of 41」のような名前が付きます。
  • Page UpとPage Downで1ページ戻り、進みます。HomeとEndで最初と最後のページへ移ります。Ctrlまたは⌘と+、−で拡大縮小します。
  • Escapeで選択を解除します。Shift + ←と→で、選択の終わりを1文字動かします。
  • 各マークは、その言葉の上に重なるボタンで、「Replacement: young bees」のような名前を持ち、タブ順に入ります。EnterかSpaceでannotationclickが発生します。
  • 選択はライブリージョンで読み上げられます(「13 characters selected」)。

labelsで、これらをすべて翻訳できます。

createViewer(el, {
  document: doc,
  labels: {
    viewer: 'Páginas del libro',
    page: 'Página {n} de {count}',
    selection: '{count} caracteres seleccionados',
    selectionCleared: 'Selección borrada',
    kinds: { replace: 'Sustitución', note: 'Nota' },
  },
});

#見た目

ビューアーは小さなスタイルシートを1つ加えます。コンテナかその祖先のどれかに、次のカスタムプロパティを設定します。

プロパティ既定値
--pv-background#e8e6e1
--pv-page-background#fff
--pv-page-shadow2層の柔らかい影
--pv-selectionrgb(47 111 214 / .3)
--pv-focus#2f6fd6

#React

import { PostextViewer } from 'postext-viewer/react';
 
function Proofs({ doc, markdown, marks, onComment }) {
  const viewer = useRef(null);
  return (
    <PostextViewer
      ref={viewer}
      document={doc}
      markdown={markdown}
      annotations={marks}
      onSelect={({ range }) => range && onComment(range)}
      onAnnotationClick={({ id }) => openThread(id)}
      style={{ height: '80vh' }}
    />
  );
}

propsはオプションとイベントに対応します(onSelect、onSelectionChange、onClick、onHover、onAnnotationClick、onPageChange、onZoomChange、onRender)。document、markdown、annotations、zoom、layers、selectionは、変わったときに動いているビューアーに反映されます。ハンドラーはレンダーのたびに新しい関数でもかまいません。refはビューアーのハンドルで、上のメソッドがすべて使えます。

#ビューアーを使わない場合

独自のページ表示(すでに描いているcanvas、ページ画像、3Dの本)を持つホストには、ビューアーは要りません。ページ上のテキストと注釈のマークが、同じジオメトリとマークを呼び出しとして提供します。

#レシピ集の例

このページの内容を使うレシピを、いちばん近い節ごとにまとめました。どのレシピもページとスクリプト全体を並べて見せます。