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

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

検索結果を組版したページの上に描く

検索ボックスで Markdown から語句を探し、すべての一致を組版したページ上のハイライトとして描き、revealAnnotation で順にたどる。

このページの内容
レベル
中級
Postext
Postext 1.103.1で検証済み
1.103.0以上が必要
ライセンス
2026年12月4日更新
コードMIT · 本文CC BY 4.0
「pendulum」の検索:ページ上の一致がすべて塗られ、現在の一致は赤い枠で囲まれ、検索ボックスの横に件数が出る。
「pendulum」の検索:ページ上の一致がすべて塗られ、現在の一致は赤い枠で囲まれ、検索ボックスの横に件数が出る。
  • 英語の見本:日本語版はまだありません
  • 仕上がり135 × 205 mm
  • 1段
  • Libre Caslon Text 8.8/13.2
  • Libre Franklin
  • 2ページ
  • レベル
  • Postext 1.103.1
  • 組版時間68 ms
  • コード123行

かんたんな説明

振り子時計の歴史を扱った一章をページごとに表示し、その上に検索ボックスを置きます。探した語が出てくる場所はすべてページ上で色が付き、2つのボタンで前後の一致へ移れます。

できあがり

時間の計り方の歴史を扱う Keeping Time の一章を 135 × 205 mm のページに組み、サイト自身の検索バーの下で postext-viewer に表示します。「pendulum」はすでに入力済みで、21か所の一致がページ上で色付けされ、3つ目が赤い枠で囲まれて画面に入り、カウンターは21件中の位置を示します。入力するたびに一致が変わり、Enter と矢印ボタンで次へ、Shift + Enter で前へ進みます。

このレシピが答える質問

  • 検索結果を組版したページの上に表示するには?

手短な答え

script.js · 113〜137行コード全体で見る
let matches = [];
let current = 0;
function search(query) {
  const escaped = query.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  // A regular expression over the Markdown itself, so each match index is already an offset.
  const found = escaped ? [...markdown.matchAll(new RegExp(escaped, 'giu'))] : [];
  // A match the pages do not paint (the front matter, a link's address) has no pieces.
  matches = found.map((m) => ({ start: m.index, end: m.index + m[0].length }))
    .filter((range) => rangeRects(doc, range).length > 0);
  show(0);
}
function show(index, behavior = 'auto') {
  current = matches.length ? (index + matches.length) % matches.length : 0;
  view.setAnnotations([
    ...matches.map((range, i) => ({ id: `m${i}`, kind: 'highlight', range })),
    ...matches.slice(current, current + 1).map((range) =>
      ({ id: 'current', kind: 'box', range, color: '#c0362c' })),
  ]);
  if (matches.length) view.revealAnnotation('current', { behavior });
  $('count').textContent = matches.length
    ? t({ en: `${current + 1} of ${matches.length}`, es: `${current + 1} de ${matches.length}` })
    : t({ en: 'No matches', es: 'Sin resultados' });
}
$('prev').addEventListener('click', () => show(current - 1, 'smooth'));
$('next').addEventListener('click', () => show(current + 1, 'smooth'));

材料

種類
Libre Caslon Text, Libre Franklin (SIL OFL 1.1)
素材
なし:画像はすべてコードで描画

作り方

#1 · 本のページを組む

script.js · 31〜41行コード全体で見る
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'Libre Franklin', fontSize: pt(6.8), fontWeight: 500,
  letterSpacing: pt(0.9), textTransform: 'uppercase', 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', 15, folio),
  head('verso-title', '{title}', 'even', 'top-left', 22),
  head('recto-chapter', '{chapterTitle}', 'odd', 'top-right', -22),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -15, folio),
] };

章は飾りのない歴史書として組みます。本文は Libre Caslon Text の 8.8 pt、小見出しは Libre Franklin、柱はページの左右に合わせて位置を変えます。検索に組版側の準備は要りません。

#2 · Markdown で探し、ページに描く

コードは上の手短な答えです。検索は描かれたテキストではなく Markdown に対して行うので、各一致のインデックスがそのまま印の位置になります。ページのテキストから原稿へ変換し直す必要はありません。front matter の題名やリンクのアドレスのように、ページに描かれない一致は rangeRects で断片を持たないので、数から外れます。一致はそれぞれ highlight になり、現在の一致はさらに box になり、revealAnnotation がビューアーをそこまでスクロールします。

#3 · 読む人のキー操作に合わせる

script.js · 141〜150行コード全体で見る
$('query').addEventListener('input', (e) => search(e.target.value));
$('query').addEventListener('keydown', (e) => {
  if (e.key !== 'Enter') return;
  e.preventDefault();
  show(current + (e.shiftKey ? -1 : 1), 'smooth');
});
// A press on a highlight makes it the current match.
view.on('annotationclick', ({ id }) => {
  if (id.startsWith('m')) show(Number(id.slice(1)), 'smooth');
});

印の一覧はキーを押すたびに作り直されます。ビューアーは同じ組版の上に印を並べ直し、一章なら数ミリ秒で済みます。ハイライトを押すと、annotationclick を通じてそれが現在の一致になります。

レシピの全体

// ═══ Postext Cookbook · Nº 219 · Search results drawn on the pages ═══════════════════
// https://postext.dev/en/cookbook/search-results-on-pages
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Libre Caslon Text, Libre Franklin (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A chapter of a history of timekeeping in postext-viewer, with a search box over it. The
// query is looked for in the Markdown, every match becomes a highlight on the pages, and the
// previous and next buttons box one match and scroll it into view with revealAnnotation.
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 = 'search-results-on-pages';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#211d1a', // text
  accent: '#7a2e2a', // oxblood: title, subheads, folios
  muted: '#6e665f', // 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.2; // pt of body leading

// #region heads: running heads that change side with the page
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'Libre Franklin', fontSize: pt(6.8), fontWeight: 500,
  letterSpacing: pt(0.9), textTransform: 'uppercase', 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', 15, folio),
  head('verso-title', '{title}', 'even', 'top-left', 22),
  head('recto-chapter', '{chapterTitle}', 'odd', 'top-right', -22),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -15, folio),
] };
// #endregion

const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(135), height: mm(205), dpi: 150,
    margins: { top: mm(19), bottom: mm(20), left: mm(17), right: mm(15), mirror: true } },

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

アレンジ

#語全体で一致させる

ラテン文字のテキストでは、語の境界を使うと「pendulum」の検索に「pendulums」が入らなくなります。

-  const found = escaped ? [...markdown.matchAll(new RegExp(escaped, 'giu'))] : [];
+  const found = escaped ? [...markdown.matchAll(new RegExp(`\\b${escaped}\\b`, 'giu'))] : [];

#大文字と小文字を区別する

i フラグを外すと、文頭の「Pendulum」は一致しなくなります。

-  const found = escaped ? [...markdown.matchAll(new RegExp(escaped, 'giu'))] : [];
+  const found = escaped ? [...markdown.matchAll(new RegExp(escaped, 'gu'))] : [];

クレジット

レシピ
Ignacio Ferro
本文
書き下ろしの文章, CC BY 4.0
フォント
Libre Caslon Text (SIL OFL 1.1) · Libre Franklin (SIL OFL 1.1)