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:
186
src/app.js
186
src/app.js
@@ -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(); });
|
||||
|
||||
Reference in New Issue
Block a user