跳到主要内容
食谱编号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行代码

简单来说

一章讲摆钟历史的内容逐页显示,上方有一个搜索框。搜索的词在页面上出现的每个地方都会高亮,两个按钮可以跳到上一个或下一个。

成品一览

计时史 Keeping Time 中的一章,排在 135 × 205 mm 的页面上,在网站自己的搜索栏下方用 postext-viewer 显示。搜索词“pendulum”已经输入好:21 处匹配在页面上着色,第三处加了红框并滚动到视野中,计数器显示它在 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'))] : [];

致谢

文本
原创文字, CC BY 4.0
字体
Libre Caslon Text (SIL OFL 1.1) · Libre Franklin (SIL OFL 1.1)