Коротко
Глава по истории маятниковых часов, показанная страница за страницей, с полем поиска сверху. Каждое место, где встречается искомое слово, выделено на страницах, а две кнопки ведут к предыдущему или следующему.
Что получится
Глава из Keeping Time, истории измерения времени на странице 135 × 205 мм, в postext-viewer под собственной строкой поиска сайта. Запрос «pendulum» уже введён: 21 совпадение подкрашено на страницах, третье обведено красной рамкой и прокручено в поле зрения, а счётчик показывает его место среди всех 21. При наборе совпадения меняются на ходу; Enter и кнопки со стрелками идут вперёд, Shift + Enter назад.
Рецепт отвечает на вопросы
- Как показать результаты поиска на свёрстанных страницах?
Короткий ответ
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'));
Ингредиенты
- Возможности
- Пометки на текстеГеометрия текста (диапазоны и точки)Просмотрщик страниц (postext-viewer)Страницы на холстеШрифты до вёрсткиКолонтитулы и колонцифрыЗеркальные поляСемантическая палитра
- Также применяет
- Колонтитулы по роли страницы
- Шрифты
- Libre Caslon Text, Libre Franklin (SIL OFL 1.1)
- Материалы
- Нет: все иллюстрации рисует код
Порядок работы
#1 · Сверстайте книжную страницу
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 пт, подзаголовки в Libre Franklin и колонтитулы, которые меняют сторону вместе со страницей. Поиску ничего не нужно от вёрстки.
#2 · Ищите в Markdown, рисуйте на страницах
Код приведён в коротком ответе выше. Поиск идёт по Markdown, а не по нарисованному тексту, поэтому индекс каждого совпадения уже и есть позиция для пометок: переводить текст страницы обратно в исходник не нужно. Совпадение, которое страницы не рисуют, например заголовок во front matter или адрес ссылки, не даёт кусков в rangeRects и не входит в счёт. Каждое совпадение становится highlight, текущее ещё и box, а revealAnnotation прокручивает просмотрщик к нему.
#3 · Следуйте за клавишами читателя
$('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 } },
<main id="pages">
<form id="tools" role="search">
<input id="query" type="search" autocomplete="off" spellcheck="false">
<span id="count" role="status"></span>
<button id="prev" type="button">‹</button>
<button id="next" type="button">›</button>
</form>
<div id="viewer"></div>
</main>
/* The host's frame: a search bar over the viewer, which fills what the window leaves. */
main#pages {
display: flex; flex-direction: column; height: max(540px, calc(100vh - 44px));
justify-items: normal; padding: 0;
}
#tools {
display: flex; align-items: center; gap: 8px; padding: 8px 16px; background: #16181d;
border-bottom: 1px solid #23262d; font: 500 14px/1.2 system-ui, sans-serif; color: #f4f1ea;
}
#query {
flex: 0 1 320px; min-height: 44px; padding: 0 12px; border: 1px solid #4a505b;
border-radius: 6px; background: #0e1014; color: #f4f1ea; font: inherit; font-size: 16px;
}
#query:focus-visible, #tools button:focus-visible { outline: 2px solid #e8a33d; outline-offset: 2px; }
#count { min-width: 7em; padding: 0 6px; color: #e8a33d; font-variant-numeric: tabular-nums; }
#tools button {
min-width: 44px; min-height: 44px; border: 1px solid #4a505b; border-radius: 6px;
background: #1f2229; color: #f4f1ea; font: inherit; font-size: 18px; cursor: pointer;
}
#tools button:hover { border-color: #e8a33d; }
#viewer { flex: 1; min-height: 0; }
#viewer .postext-viewer { --pv-background: #0e1014; --pv-focus: #e8a33d; }
Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)
Варианты
#Ищите целые слова
Границы слов не пускают «pendulums» в поиск по «pendulum» в латинском тексте.
- 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)
Изменить описание рецепта ↗ (открывается в новой вкладке)Папка рецепта на GitHub ↗ (открывается в новой вкладке)



