Add a search bar: case-insensitive, steps through matches with Tab/Shift+Tab (Refs #27)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-24 14:27:48 -05:00
parent 14a46abc63
commit 2275889a86
8 changed files with 251 additions and 20 deletions

View File

@@ -13,6 +13,8 @@
pwChanged: false, // passphrase changed since the last save
tabs: {}, // section id -> id of the sub-tab being shown ('' = General); not saved
collapsed: new Set(), // ids of records folded to just their title (view mode only)
search: null, // { q, hits: [{sid, eid, n}], i, scroll }: the active search (not saved)
searchAll: false, // true only while building the hidden copy the search counts matches in
walk: null, // { id, k }: the visual sequence shown as a one-step-at-a-time walkthrough (not saved)
revealed: new WeakSet(), // secret field objects currently shown
blob: null, // encrypted payload taken from a file the user chose to open
@@ -374,7 +376,7 @@
// ---------- read-only view ----------
function statusBadge(status) {
return status === 'tbd' ? h('span', { class: 'badge tbd' }, 'TBD') : status === 'done' ? h('span', { class: 'badge done' }, 'Done') : null;
return status === 'tbd' ? h('span', { class: 'badge tbd nosearch' }, 'TBD') : status === 'done' ? h('span', { class: 'badge done nosearch' }, 'Done') : null;
}
function viewImageField(f) {
@@ -423,10 +425,10 @@
function viewRecord(s, r, i) {
const arr = s.records;
const same = sameTab(s);
const closed = state.collapsed.has(r.id);
const closed = !state.searchAll && state.collapsed.has(r.id);
const toggle = () => { state.collapsed[closed ? 'delete' : 'add'](r.id); render(); };
const shift = (dir) => { moveWithin(arr, i, dir, same); changed(r); render(); };
return h('article', { class: 'card' + (closed ? ' collapsed' : '') },
return h('article', { class: 'card' + (closed ? ' collapsed' : ''), 'data-eid': r.id },
h('div', { class: 'rechead' },
h('h3', {}, r.title, ' ', statusBadge(r.status)),
h('span', { class: 'tools' },
@@ -436,7 +438,7 @@
closed ? null : [
r.fields.length ? h('dl', {}, r.fields.map(viewField)) : null,
r.notes ? h('p', { class: 'notes' }, r.notes) : null,
h('p', { class: 'muted small' }, 'Updated ' + r.updated)]);
h('p', { class: 'muted small nosearch' }, 'Updated ' + r.updated)]);
}
function foldBar(entries) {
@@ -454,7 +456,7 @@
const label = q.title + ', step ' + (k + 1);
const layout = hidden ? 'none' : frameLayout(f);
return h('div', { class: 'frame ' + layout },
h('div', { class: 'fnum' }, 'Step ' + (k + 1)),
h('div', { class: 'fnum nosearch' }, 'Step ' + (k + 1)),
hidden ? h('div', {}, h('span', { class: 'secret' }, '(hidden step)'), btn('Show', toggle, 'link', { 'aria-label': 'Show ' + label })) : [
f.image ? markedImage(h('img', { class: 'fimg', src: f.image, alt: label, tabIndex: 0, title: 'Click to enlarge',
onclick: () => openLightbox(label, f.image, f.marks), onkeydown: (e) => { if (e.key === 'Enter') openLightbox(label, f.image, f.marks); } }), f.marks)
@@ -470,7 +472,7 @@
// The credentials a step needs, live from their records: secrets stay masked until shown.
function viewUses(f) {
if (!f.uses || !f.uses.length) return null;
return h('div', { class: 'fuses' }, h('strong', {}, 'You will need:'), f.uses.map((u) => {
return h('div', { class: 'fuses nosearch' }, h('strong', {}, 'You will need:'), f.uses.map((u) => {
const hit = findFieldRef(state.doc, u);
if (!hit) return h('p', { class: 'muted' }, '(a credential this step used has been removed)');
const fld = hit.field;
@@ -491,38 +493,38 @@
const n = q.frames.length;
const k = Math.max(0, Math.min(state.walk.k, n - 1));
const go = (to) => () => { state.walk = { id: q.id, k: to }; render(); };
return h('article', { class: 'card seq walk', 'data-seq': q.id },
return h('article', { class: 'card seq walk', 'data-seq': q.id, 'data-eid': q.id },
h('h3', {}, q.title),
viewFrame(q, q.frames[k], k),
h('div', { class: 'row walknav' },
h('div', { class: 'row walknav nosearch' },
btn('\u2190 Back', go(k - 1), '', { disabled: k === 0 }),
h('span', { class: 'muted', role: 'status' }, 'Step ' + (k + 1) + ' of ' + n),
btn('Next \u2192', go(k + 1), 'primary', { disabled: k === n - 1 }),
btn('Show all steps', () => { state.walk = null; render(); }, 'link')),
h('p', { class: 'muted small' }, 'Updated ' + q.updated + '.' + capturedNote(q)));
h('p', { class: 'muted small nosearch' }, 'Updated ' + q.updated + '.' + capturedNote(q)));
}
function viewSequence(q) {
if (state.walk && state.walk.id === q.id && q.frames.length) return walkSequence(q);
return h('article', { class: 'card seq' },
if (!state.searchAll && state.walk && state.walk.id === q.id && q.frames.length) return walkSequence(q);
return h('article', { class: 'card seq', 'data-eid': q.id },
h('h3', {}, q.title),
q.frames.length ? btn('Walk through, one step at a time', () => { state.walk = { id: q.id, k: 0 }; render(); }, 'small') : null,
q.frames.length ? h('div', { class: 'frames' }, q.frames.map((f, k) => viewFrame(q, f, k))) : h('p', { class: 'muted' }, '(no steps yet)'),
h('p', { class: 'muted small' }, 'Updated ' + q.updated + '.' + capturedNote(q)));
q.frames.length ? h('div', { class: 'frames' }, q.frames.map((f, k) => viewFrame(q, f, k))) : h('p', { class: 'muted nosearch' }, '(no steps yet)'),
h('p', { class: 'muted small nosearch' }, 'Updated ' + q.updated + '.' + capturedNote(q)));
}
const seqItem = (q) => h('li', { class: 'seqitem' }, viewSequence(q));
function viewItem(it, ordered) {
return h('li', { class: 'item ' + it.status },
return h('li', { class: 'item ' + it.status, 'data-eid': it.id },
h('div', {}, h('strong', {}, it.text), ' ', statusBadge(it.status)),
it.detail ? h('p', { class: 'notes' }, it.detail) : null);
}
function viewRecords(s) {
const entries = entriesInTab(s, currentTab(s));
return [tabBar(s),
hasTabs(s) && !entries.length ? h('p', { class: 'muted' }, 'Nothing in this sub-tab yet. Choose Edit to add or move records here.') : null,
foldBar(entries.map((x) => x.e)),
const entries = state.searchAll ? s.records.map((e, i) => ({ e, i })) : entriesInTab(s, currentTab(s));
return [state.searchAll ? null : tabBar(s),
hasTabs(s) && !entries.length ? h('p', { class: 'muted nosearch' }, 'Nothing in this sub-tab yet. Choose Edit to add or move records here.') : null,
state.searchAll ? null : foldBar(entries.map((x) => x.e)),
entries.map(({ e, i }) => (isSequence(e) ? viewSequence(e) : viewRecord(s, e, i)))];
}
@@ -1014,6 +1016,8 @@
function render() {
if (capture && !state.editing) endCapture(); // sharing only lasts while editing
if (state.editing) state.search = null; // search is for reading; Edit clears it
const keepFocus = searchEl && searchEl.contains(document.activeElement) ? document.activeElement : null;
root.replaceChildren();
if (!state.doc) return root.append(renderStart());
const onHeader = state.current === HEADER_ID;
@@ -1034,11 +1038,157 @@
btn('Change passphrase', changePassphrase),
btn('Print…', openPrintDialog),
btn(state.editing ? 'Done editing' : 'Edit', () => { state.editing = !state.editing; render(); }, state.editing ? 'primary' : ''))),
...(state.editing ? [] : [searchBarEl()]),
...(resetRequested() && !state.resetOffered ? [resetBanner()] : []), // never pass null: append() would print "null"
h('div', { class: 'layout' }, renderNav(),
h('main', {}, onHeader ? [h('h2', {}, 'Print header'), headerPanel()]
: sec ? [h('h2', {}, sec.title), state.editing ? editSection(sec) : viewSection(sec)]
: h('p', { class: 'muted' }, 'No sections yet. Choose Edit to add one.'))));
if (!state.editing) updateSearchUi();
if (keepFocus) keepFocus.focus();
highlightSearch();
}
// ---------- search (issue #27) ----------
// The search bar is built once and re-attached on every render(), so what was typed survives.
// Matches are counted in a hidden copy of every section (all sub-tabs, nothing folded) built by
// the same view functions as the page, so the count agrees with what is shown. Secret values,
// buttons, form fields and page furniture are never searched (see SEARCH_SKIP).
const SEARCH_SKIP = 'button,textarea,input,select,script,style,.secret,.nosearch,[hidden]';
let searchEl = null, searchInput = null, searchNote = null, searchBtns = {};
function searchBarEl() {
if (searchEl) return searchEl;
searchInput = h('input', { type: 'search', class: 'searchbox', 'aria-label': 'Search the document', placeholder: 'Search', autocomplete: 'off',
oninput: () => { if (state.search) { state.search = null; clearHighlights(); updateSearchUi(); } },
onkeydown: (e) => {
const found = state.search && state.search.hits.length;
if (e.key === 'Tab' && found) { e.preventDefault(); stepSearch(e.shiftKey ? -1 : 1); }
else if (e.key === 'Enter') {
e.preventDefault();
if (found && state.search.q === searchInput.value.trim()) stepSearch(e.shiftKey ? -1 : 1); else runSearch();
} else if (e.key === 'Escape') cancelSearch();
} });
searchNote = h('span', { class: 'muted small searchnote', role: 'status' });
searchBtns = {
search: btn('Search', runSearch, 'primary'),
prev: btn('\u2190 Previous', () => stepSearch(-1), '', { 'aria-label': 'Previous match' }),
next: btn('Next \u2192', () => stepSearch(1), '', { 'aria-label': 'Next match' }),
cancel: btn('Cancel', cancelSearch),
};
searchEl = h('div', { class: 'searchbar', role: 'search' }, searchInput, searchNote,
searchBtns.search, searchBtns.prev, searchBtns.next, searchBtns.cancel);
return searchEl;
}
function updateSearchUi() {
if (!searchEl) return;
const s = state.search;
const n = s ? s.hits.length : 0;
searchNote.textContent = !s ? '' : n ? (s.i + 1) + ' of ' + n : 'Not found';
searchBtns.prev.disabled = searchBtns.next.disabled = n === 0;
}
// Every text node under `container` that the search may look at.
function searchableText(container) {
const out = [];
const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT, {
acceptNode: (n) => (n.parentElement && !n.parentElement.closest(SEARCH_SKIP) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT) });
while (walker.nextNode()) out.push(walker.currentNode);
return out;
}
// Matches under `container`, in order, each labelled with the entry (record, item or
// sequence) it sits in and its count within that entry. '' means section-level text.
function matchesIn(container, q) {
const seen = {};
const out = [];
for (const node of searchableText(container)) {
const ranges = searchRanges(node.nodeValue, q);
if (!ranges.length) continue;
const entry = node.parentElement.closest('[data-eid]');
const eid = entry ? entry.dataset.eid : '';
for (const r of ranges) out.push({ node, start: r.start, end: r.end, eid, n: (seen[eid] = (seen[eid] || 0) + 1) - 1 });
}
return out;
}
function findAllHits(q) {
let host;
state.searchAll = true;
try {
host = h('div', {}, state.doc.sections.map((s) => h('section', { 'data-sid': s.id }, h('h2', {}, s.title), viewSection(s))));
} finally {
state.searchAll = false;
}
const hits = [];
for (const sec of host.querySelectorAll('section[data-sid]')) {
for (const m of matchesIn(sec, q)) hits.push({ sid: sec.dataset.sid, eid: m.eid, n: m.n });
}
return hits;
}
function runSearch() {
const q = searchInput.value.trim();
if (!q) return cancelSearch();
state.search = { q, hits: findAllHits(q), i: -1 };
if (state.search.hits.length) stepSearch(1); else render();
}
function cancelSearch() {
searchInput.value = '';
state.search = null;
render();
}
// Go to match i: its section, its sub-tab, unfolded, then highlight and scroll to it.
function stepSearch(dir) {
const s = state.search;
if (!s || !s.hits.length) return;
s.i = stepSearchIndex(s.i, dir, s.hits.length);
const hit = s.hits[s.i];
const sec = state.doc.sections.find((x) => x.id === hit.sid);
state.current = hit.sid;
state.walk = null;
if (hit.eid && sec) {
state.collapsed.delete(hit.eid);
const list = [...(sec.records || []), ...(sec.items || []), ...(sec.sequences || [])];
const entry = list.find((x) => x.id === hit.eid);
if (entry && sec.kind === 'records') state.tabs[sec.id] = entryTab(sec, entry);
}
s.scroll = true;
render();
}
function clearHighlights() {
for (const m of root.querySelectorAll('mark.hit')) {
const parent = m.parentNode;
m.replaceWith(...m.childNodes);
parent.normalize();
}
}
// After each render: wrap every match on screen in <mark>, the current one stronger.
function highlightSearch() {
const s = state.search;
if (!s || !s.hits.length || state.current === HEADER_ID) return;
const main = root.querySelector('main');
if (!main) return;
const cur = s.hits[s.i];
const found = matchesIn(main, s.q);
let current = null;
for (let k = found.length - 1; k >= 0; k--) { // last first, so earlier offsets stay valid
const f = found[k];
const range = document.createRange();
range.setStart(f.node, f.start);
range.setEnd(f.node, f.end);
const mark = document.createElement('mark');
mark.className = 'hit' + (cur && state.current === cur.sid && f.eid === cur.eid && f.n === cur.n ? ' cur' : '');
range.surroundContents(mark);
if (mark.classList.contains('cur')) current = mark;
}
if (current && s.scroll) current.scrollIntoView({ block: 'center' });
s.scroll = false;
}
window.addEventListener('hashchange', () => { state.resetOffered = false; render(); });

24
src/search.js Normal file
View File

@@ -0,0 +1,24 @@
// Pure helpers for the search bar (issue #27). No DOM; tested in Node.
// build.js strips `export` when bundling, so names here must not collide with other modules.
// Where `query` occurs in `text`, ignoring case: [{ start, end }], left to right, not overlapping.
// A blank query matches nothing.
export function searchRanges(text, query) {
const q = String(query || '').trim();
if (!q) return [];
const re = new RegExp(q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
const out = [];
let m;
while ((m = re.exec(String(text))) !== null) {
out.push({ start: m.index, end: m.index + m[0].length });
if (m[0].length === 0) re.lastIndex++; // cannot happen for a non-empty query; never loop forever
}
return out;
}
// The next index when stepping `dir` (+1 or -1) through `count` places, wrapping round.
// -1 when there is nowhere to go.
export function stepSearchIndex(i, dir, count) {
if (count <= 0) return -1;
return (((i + dir) % count) + count) % count;
}

View File

@@ -63,6 +63,11 @@ li.seqitem { display: block; list-style: none; margin-left: -1.4rem; } .frameedi
.mbox { position: absolute; box-sizing: border-box; border: 3px solid #e11; box-shadow: 0 0 0 1px #fff; border-radius: 3px; pointer-events: none; }
.mpin { position: absolute; box-sizing: border-box; transform: translate(-50%, -50%); width: 1.6rem; height: 1.6rem; border-radius: 50%; background: #e11; color: #fff; border: 2px solid #fff; font: 700 .85rem/1.2rem system-ui, sans-serif; text-align: center; pointer-events: none; }
.annotator { max-width: min(95vw, 70rem); } .annot { display: block; max-width: 100%; max-height: 65vh; margin: .5rem auto; cursor: crosshair; touch-action: none; border: 1px solid var(--line); }
.searchbar { display: flex; flex-wrap: wrap; gap: .5rem; align-items: center; margin: .75rem 0 1rem; }
.searchbox { flex: 1 1 14rem; min-width: 8rem; font: inherit; padding: .45rem .6rem; border: 1px solid var(--line); border-radius: .4rem; background: var(--card); color: var(--fg); }
.searchnote { min-width: 4.5rem; text-align: right; }
mark.hit { background: var(--warn-bg); color: var(--warn-fg); border-radius: .2rem; padding: 0 .1em; }
mark.hit.cur { background: var(--accent); color: var(--bg); outline: 2px solid var(--accent); }
.fuses { grid-column: 1 / -1; } .fuse { align-items: center; margin: .25rem 0; }
.fstop { border: 2px solid var(--danger); color: var(--danger); border-radius: .35rem; padding: .35rem .6rem; }
.fstuck { background: var(--warn-bg); color: var(--warn-fg); border-radius: .35rem; padding: .35rem .6rem; white-space: pre-wrap; }

View File

@@ -2,7 +2,7 @@
// YYMMDD is the date, X the iteration that day (A first, B second, ...).
// Bump with `npm run bump` (see bump-version.js). build.js strips `export`.
export const APP_VERSION = '261124G';
export const APP_VERSION = '261124H';
const VERSION_RE = /^(\d{6})([A-Z])$/;
export const isVersion = (v) => typeof v === 'string' && VERSION_RE.test(v);