From 2275889a861f9ca1e86225db0a32bce382b5abc6 Mon Sep 17 00:00:00 2001 From: Eric Bell Date: Tue, 24 Nov 2026 14:27:48 -0500 Subject: [PATCH] Add a search bar: case-insensitive, steps through matches with Tab/Shift+Tab (Refs #27) Co-Authored-By: Claude Sonnet 5.5 --- OVERVIEW.md | 1 + README.md | 22 ++++++ build.js | 2 +- src/app.js | 186 +++++++++++++++++++++++++++++++++++++++----- src/search.js | 24 ++++++ src/style.css | 5 ++ src/version.js | 2 +- test/search.test.js | 29 +++++++ 8 files changed, 251 insertions(+), 20 deletions(-) create mode 100644 src/search.js create mode 100644 test/search.test.js diff --git a/OVERVIEW.md b/OVERVIEW.md index 3165b35..5cafea0 100644 --- a/OVERVIEW.md +++ b/OVERVIEW.md @@ -68,6 +68,7 @@ A **visual sequence** (`kind: 'sequence'`, numbered `frames` of image + text wit - **Walkthroughs (issue #23):** a sequence frame may carry `ifStuck` text and a `stop` flag, and a sequence a `captured` date. In Edit, "Capture from screen…" uses `getDisplayMedia` (`startScreenCapture`, `grabScreenFrame`, `stopScreenCapture` in `images.js`; the stream lives in a closure variable in `app.js`, ended when leaving edit mode) and adds frames via `addCapture()` in `ops.js`. In view mode `state.walk` (`{id, k}`, not saved) shows a sequence one step at a time (`walkSequence`). - **Credential references (issue #24):** a frame's `uses: [{record, field}]` points at record fields by id. A field gets an `id` the first time it is referenced (`ensureFieldId`, `addUse`, `findFieldRef`, `allRecordsIn` in `ops.js`). A dangling reference is shown as removed, never a validation error. `viewUses` and `copyValue` (30 s clipboard wipe) are in `app.js`; `usesView` in `print.js` does the masked/included print text. - **Annotation (issue #25):** a frame's `marks` are `{type:'marker',x,y}` or `{type:'box',x,y,w,h}` as fractions of the picture (`isMark`, `normRect` in `images.js`). `markedImage()` in `app.js` wraps a step's `` in a `.marked` box and lays CSS overlays over it, so the same marks work in the list, player, lightbox and print. `openAnnotator()` is a canvas dialog; Blur out runs `pixelateRegion()` (pure, in `images.js`) on the pixels and `Apply` re-encodes the picture, so no unblurred copy is stored. Marks are dropped when the picture is replaced, removed or erased by `clearSecrets`. +- **Search (issue #27):** `src/search.js` has the pure `searchRanges()` (case-insensitive, plain text) and `stepSearchIndex()`. In `app.js` the bar is a persistent element re-attached on every `render()` (so the typed text and focus survive). `findAllHits()` builds a hidden copy of every section with `state.searchAll` set (all sub-tabs, nothing folded) using the normal view functions, then counts matches per entry (`data-eid` on record/item/sequence elements). `stepSearch()` navigates (section, sub-tab, unfold, `state.walk = null`); `highlightSearch()` runs at the end of `render()` and wraps the matches in ``. Text under `SEARCH_SKIP` (buttons, inputs, `.secret`, `.nosearch`) is never searched, so secrets stay out. New view-mode furniture such as dates and badges needs the `nosearch` class or it will be counted. - **Reset (`?reset=1`):** opening the file with `?reset=1` or `#reset=1` shows a banner after unlock offering to erase every secret-flagged field value and secret frame (`clearSecrets()` in `ops.js`, count from `countSecrets`). Labels, structure and flags stay. It is read live (`resetRequested()`), with a `hashchange` listener to re-offer, and `state.resetOffered` dismisses it. Nothing is written until Save, so make a Backup copy first. It's meant for working on layout on a less safe machine. **Save.** Uses the File System Access API (`showSaveFilePicker`, handle reused) where available, otherwise a Blob download. `assemble()` rebuilds the full HTML from the page's own CSS and JS plus a fresh encrypted payload. "Backup copy" downloads `final-wishes-YYYYMMDD.html`. diff --git a/README.md b/README.md index 8b88135..6f74f2a 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,28 @@ After sealing, `data/seed.json` is still plaintext. Delete it (and see 4. If you changed the passphrase, the old file still opens with the *old* one until you save and replace it. +## Searching +Below the toolbar (in view mode) is a search box with **Search**, **← Previous**, +**Next →** and **Cancel** buttons. Type a word, press **Search** or Enter. +It ignores capitals and looks through the whole document: section titles, text, +record titles, field labels and values, notes, items and visual-sequence step +text. Every match on the page is highlighted and the current one is stronger; +the count shows as "2 of 6". + +- **Tab** and **Shift+Tab** (with the cursor in the search box), the arrow + buttons, or Enter / Shift+Enter move to the next or previous match. They wrap + round at the ends and jump to the right section and sub-tab, unfolding a + collapsed record if the match is inside it. +- **Not found:** nothing is highlighted, the box says "Not found", the arrows + are greyed and Tab behaves normally (it moves on to the next control). +- **Cancel** (or Esc) clears the box and the highlights. Typing a new word + also clears the old results until you search again. +- **Secrets are never searched or shown.** A word that only appears inside a + value marked secret is "Not found". Field labels are searched, values marked + secret are not. Image text is not searchable. +- Search is for reading: **Edit** hides the bar and clears the results. +- The Print header page and dates such as "Updated" are not searched. + ## Sub-tabs A *records* section (Banking, say) can be split into **sub-tabs** such as Standard, Online and Credit Union. Other kinds of section don't have them. diff --git a/build.js b/build.js index 622e867..6e85734 100644 --- a/build.js +++ b/build.js @@ -17,7 +17,7 @@ const root = dirname(fileURLToPath(import.meta.url)); const read = (p) => readFileSync(join(root, 'src', p), 'utf8'); // Modules are concatenated (ES `import` lines and `export` keywords dropped) ahead of app.js into one scope. -const MODULES = ['crypto.js', 'images.js', 'model.js', 'ops.js', 'print.js', 'template.js', 'version.js']; +const MODULES = ['crypto.js', 'images.js', 'model.js', 'ops.js', 'print.js', 'search.js', 'template.js', 'version.js']; export function bundleJs() { return MODULES.map((f) => read(f).replace(/^import .*$/gm, '').replace(/^export /gm, '')).concat(read('app.js')).join('\n'); } diff --git a/src/app.js b/src/app.js index 01a4295..b2fb8fe 100644 --- a/src/app.js +++ b/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 , 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(); }); diff --git a/src/search.js b/src/search.js new file mode 100644 index 0000000..b6f5569 --- /dev/null +++ b/src/search.js @@ -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; +} diff --git a/src/style.css b/src/style.css index f355df8..440c8aa 100644 --- a/src/style.css +++ b/src/style.css @@ -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; } diff --git a/src/version.js b/src/version.js index 72794a2..27125d3 100644 --- a/src/version.js +++ b/src/version.js @@ -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); diff --git a/test/search.test.js b/test/search.test.js new file mode 100644 index 0000000..8048895 --- /dev/null +++ b/test/search.test.js @@ -0,0 +1,29 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { searchRanges, stepSearchIndex } from '../src/search.js'; + +test('searchRanges is case-insensitive and finds every place', () => { + assert.deepEqual(searchRanges('Bitwarden, BITWARDEN and bitwarden.', 'bitwarden'), + [{ start: 0, end: 9 }, { start: 11, end: 20 }, { start: 25, end: 34 }]); + assert.deepEqual(searchRanges('Santander', 'BitWarden'), []); +}); + +test('searchRanges treats the query as plain text, ignores outer spaces, and blank matches nothing', () => { + assert.deepEqual(searchRanges('a.b (c) a.b', 'a.b'), [{ start: 0, end: 3 }, { start: 8, end: 11 }]); + assert.deepEqual(searchRanges('axb', 'a.b'), []); // "." is not a wildcard + assert.deepEqual(searchRanges('(c) [d] $5 ^ \\', '(c)'), [{ start: 0, end: 3 }]); + assert.equal(searchRanges('x', '[').length, 0); // a stray bracket must not throw + assert.deepEqual(searchRanges('go bitwarden go', ' bitwarden '), [{ start: 3, end: 12 }]); + assert.deepEqual(searchRanges('anything', ''), []); + assert.deepEqual(searchRanges('anything', ' '), []); + assert.deepEqual(searchRanges('aaaa', 'aa'), [{ start: 0, end: 2 }, { start: 2, end: 4 }]); // no overlap +}); + +test('stepSearchIndex wraps both ways and handles no results', () => { + assert.equal(stepSearchIndex(0, 1, 3), 1); + assert.equal(stepSearchIndex(2, 1, 3), 0); + assert.equal(stepSearchIndex(0, -1, 3), 2); + assert.equal(stepSearchIndex(0, 1, 1), 0); + assert.equal(stepSearchIndex(-1, 1, 3), 0); // nothing current yet: forward goes to the first + assert.equal(stepSearchIndex(0, 1, 0), -1); +});