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

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

ページビューアーで見る本:ズームとページ移動

postext-viewer の createViewer で、組版した章を CMS の中にページの列として表示する。ズームボタンとページ番号はサイト側が持つ。

このページの内容
レベル
中級
Postext
Postext 1.103.1で検証済み
1.103.0以上が必要
ライセンス
2026年12月4日更新
コードMIT · 本文CC BY 4.0
開いたときのビューア:Flour, Water, Salt の1ページ全体が見え、その上にページカウンターとズームボタンを備えたホスト側のツールバーがある。
開いたときのビューア:Flour, Water, Salt の1ページ全体が見え、その上にページカウンターとズームボタンを備えたホスト側のツールバーがある。
  • 英語の見本:日本語版はまだありません
  • 仕上がり140 × 210 mm
  • 1段
  • Literata 9.8/14
  • Fraunces
  • Work Sans
  • 3ページ
  • レベル
  • Postext 1.103.1
  • 組版時間11 ms
  • コード138行

かんたんな説明

パン作りの手引き書の一章を、編集システムのようにウェブページの中で1ページずつ表示します。上のボタンで拡大・縮小し、ページを窓に合わせ、前後のページへ移動します。

できあがり

パン作りの手引き書 Flour, Water, Salt の第3章を、140 × 210 mm の判型で組み、編集システムが校正刷りを見せるようにウェブページの中に表示します。ページは暗い列を下へ並び、1枚ずつ白い紙に載っています。上のツールバーには校正する人が使うボタンが並びます。前へと次へ、縮小と拡大、幅に合わせる、ページ全体、そして現在のページと総ページ数を示す表示です。ツールバーはサイトのものです。ビューアーはページを描き、スクロールを追い、ページとズームが変わるたびに知らせます。サイトはその知らせからボタンを描き直します。

このレシピが答える質問

  • 組版した本を自分のCMSの中に、ズームとページ移動付きで表示するには?

手短な答え

script.js · 148〜176行コード全体で見る
// `view`, not `viewer`: the kit's viewer block declares a function of that name.
const view = createViewer(document.getElementById('viewer'), {
  document: doc,
  markdown, // the source: copying a selection gives the Markdown, not the painted text
  zoom: 'fit-page', // a whole page in view; a number is CSS px per page px
  minZoom: 0.4, maxZoom: 3, gap: 24,
  labels: labels.viewer, // what a screen reader hears: "Page 3 of 41", the selection's size
});
const $ = (id) => document.getElementById(id);
// The viewer says what changed; the host draws its own controls from that.
const showPage = (i) => {
  const folio = doc.pages[i].pageLabel || String(i + 1);
  $('counter').textContent = t({ en: `Page ${folio} of ${doc.pages.length}`,
    es: `Página ${folio} de ${doc.pages.length}` });
  $('prev').disabled = i === 0;
  $('next').disabled = i === doc.pages.length - 1;
};
view.on('pagechange', ({ pageIndex }) => showPage(pageIndex));
const showZoom = (zoom) => { $('percent').textContent = `${Math.round(zoom * 100)} %`; };
view.on('zoomchange', ({ zoom }) => showZoom(zoom));
const clicks = {
  prev: () => view.goToPage(view.pageIndex - 1),
  next: () => view.goToPage(view.pageIndex + 1),
  'zoom-out': () => view.setZoom(view.zoom / 1.25), // clamped to minZoom by the viewer
  'zoom-in': () => view.setZoom(view.zoom * 1.25),
  'fit-width': () => view.setZoom('fit-width'), // a fitted mode follows the container
  'fit-page': () => view.setZoom('fit-page'),
};
for (const [id, run] of Object.entries(clicks)) $(id).addEventListener('click', run);

材料

種類
Literata, Fraunces, Work Sans (SIL OFL 1.1)
素材
なし:画像はすべてコードで描画

作り方

#1 · 拡大に耐えるページを組む

script.js · 31〜54行コード全体で見る
const opener = { enabled: true, minHeight: mm(46), slot: { elements: [
  { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: 'Work Sans',
    fontSize: pt(7.5), fontWeight: 600, letterSpacing: pt(1.5), textTransform: 'uppercase',
    color: col('accent'), align: 'left', placement: { anchor: { to: 'container', edge: 'top-left' },
      offset: { y: mm(8) } } },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Fraunces', fontSize: pt(26),
    lineHeight: 1.05, fontWeight: 600, color: col('ink'), align: 'left', overflow: 'wrap',
    placement: { anchor: { to: '#kicker', edge: 'below' }, offset: { y: mm(3) },
      size: { width: mm(90) } } },
  { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(1.25), color: col('accent'),
    placement: { anchor: { to: '#title', edge: 'below' }, offset: { y: mm(4) },
      size: { width: mm(12) } } },
] } };
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'Work Sans', fontSize: pt(7), fontWeight: 500,
  letterSpacing: pt(1.1), textTransform: 'uppercase', color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(11) } }, ...extra });
const folio = { fontWeight: 600, color: col('accent') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-title', '{title}', 'even', 'top-left', OUTER + 8),
  head('recto-chapter', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 8)),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };

ビューアーは 300 % まで拡大できるので、ページはそれに耐えなければなりません。見出しの属性から取った柱見出し付きの下げた章扉と、奇数・偶数で左右が入れ替わる柱です。同じ設定で印刷もでき、ビューアーは組版に何も加えません。

#2 · ビューアーを開き、その知らせを聞く

コードは上の手短な答えです。createViewer はコンテナいっぱいに広がるので、コンテナには高さが要ります。ここでは窓の高さからツールバーを引いた値です。ビューアーは最初のフレームで開いたときのズームとページを知らせるので、ツールバーは zoomchange と pagechange を聞くだけで済みます。ズームボタンは現在の倍率に掛け算し、ビューアーはそれを minZoom と maxZoom の間に収め、見ていた場所を保ちます。

#3 · すべてに読者の言語で名前を付ける

script.js · 135〜144行コード全体で見る
const labels = t({
  en: { prev: 'Previous page', next: 'Next page', 'zoom-out': 'Zoom out', 'zoom-in': 'Zoom in',
    'fit-width': 'Fit width', 'fit-page': 'Whole page', tools: 'Pages',
    viewer: {} }, // the viewer speaks English unless told otherwise
  es: { prev: 'Página anterior', next: 'Página siguiente', 'zoom-out': 'Reducir',
    'zoom-in': 'Ampliar', 'fit-width': 'Ajustar al ancho', 'fit-page': 'Página entera',
    tools: 'Páginas',
    viewer: { viewer: 'Páginas del libro', page: 'Página {n} de {count}',
      selection: '{count} caracteres seleccionados', selectionCleared: 'Selección borrada' } },
});

ビューアーはスクリーンリーダーのために自分の領域と各ページに名前を付け、選択の長さを読み上げます。英語版では何も要りません。スペイン語版は独自の labels を渡します。ツールバーのボタンにも名前を付けます。うち二つは矢印か記号しか表示しないからです。すべてのラベルとオプションはページビューアーの文書にあります。

レシピの全体

// ═══ Postext Cookbook · Nº 211 · A book in a page viewer ══════════════════════════════
// https://postext.dev/en/cookbook/book-in-a-page-viewer
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Literata, Fraunces, Work Sans (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A chapter of a baking manual, laid out once and shown in postext-viewer as a CMS would show
// it: a scrolling column of pages, zoom buttons, fit to the width or to the page, and a page
// counter. The toolbar is the host's own; the viewer only reports what changed.
import { buildDocumentWithFonts, renderPageToCanvas } 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 = 'book-in-a-page-viewer';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#1f1c19', // text: a warm near-black
  accent: '#8a4b1f', // crust brown: kicker, rule, list numbers, folios
  muted: '#6f675e', // 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 [OUTER, LEAD] = [15, 14]; // mm from the outer edge to the folios; pt of body leading

// #region book: a manual's page, a sunk chapter opener and running heads by parity
const opener = { enabled: true, minHeight: mm(46), slot: { elements: [
  { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: 'Work Sans',
    fontSize: pt(7.5), fontWeight: 600, letterSpacing: pt(1.5), textTransform: 'uppercase',
    color: col('accent'), align: 'left', placement: { anchor: { to: 'container', edge: 'top-left' },
      offset: { y: mm(8) } } },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Fraunces', fontSize: pt(26),
    lineHeight: 1.05, fontWeight: 600, color: col('ink'), align: 'left', overflow: 'wrap',
    placement: { anchor: { to: '#kicker', edge: 'below' }, offset: { y: mm(3) },
      size: { width: mm(90) } } },
  { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(1.25), color: col('accent'),
    placement: { anchor: { to: '#title', edge: 'below' }, offset: { y: mm(4) },
      size: { width: mm(12) } } },
] } };
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'Work Sans', fontSize: pt(7), fontWeight: 500,
  letterSpacing: pt(1.1), textTransform: 'uppercase', color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(11) } }, ...extra });
const folio = { fontWeight: 600, color: col('accent') };

組み立てたscript.jsはそのまま動きます。任意のページのモジュールスクリプトに貼り付けるか、レシピをCodePenで開いてください。 GitHub上のレシピのフォルダー ↗ (新しいタブで開きます)

アレンジ

#段の幅で開く

校正には、ページ全体よりも窓と同じ幅のページのほうが読みやすくなります。

-  zoom: 'fit-page', // a whole page in view; a number is CSS px per page px
+  zoom: 'fit-width', // the page as wide as the container; the column scrolls

#3Dでページをめくる

組版した本を机の上に3Dで開く は、同じ種類の文書を読者が手でめくる本として開きます。

クレジット

レシピ
Ignacio Ferro
本文
書き下ろしの文章, CC BY 4.0
フォント
Literata (SIL OFL 1.1) · Fraunces (SIL OFL 1.1) · Work Sans (SIL OFL 1.1)