import { SearchQuery } from "@codemirror/search"; import { documentMatches, type FindTarget } from "./findTarget"; /** Search the visible reading text without changing its Markdown or rendered nodes. */ export function readingSearch(root: HTMLElement, close: () => void, options: { includeButtons?: boolean; focusOnClose?: () => void } = {}): FindTarget { let query = new SearchQuery({ search: "" }); let current = -1; function ranges() { const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); const nodes: { node: Text; from: number; to: number }[] = []; let source = "", block: Element | null = null; while (walker.nextNode()) { const node = walker.currentNode as Text, parent = node.parentElement; if (!parent || parent.closest(options.includeButtons ? "[hidden], [aria-hidden=true], script, style" : "button, [hidden], script, style") || !parent.getClientRects().length) continue; const nextBlock = parent.closest("p, h1, h2, h3, h4, h5, h6, li, td, th, pre, button, div, section"); if (nodes.length && nextBlock !== block) source += "\n"; block = nextBlock; nodes.push({ node, from: source.length, to: source.length + node.length }); source += node.data; } return documentMatches(source, query).matches.flatMap(match => { const start = nodes.find(node => node.to > match.from || node.from === match.from); const end = nodes.find(node => node.to >= match.to); if (!start || !end) return []; const range = document.createRange(); range.setStart(start.node, Math.max(0, match.from - start.from)); range.setEnd(end.node, Math.max(0, match.to - end.from)); return [range]; }); } function next(backward = false) { const matches = ranges(); if (!matches.length) { current = -1; return; } current = current < 0 ? (backward ? matches.length - 1 : 0) : (current + (backward ? -1 : 1) + matches.length) % matches.length; const range = matches[current]; const selection = window.getSelection(); selection?.removeAllRanges(); selection?.addRange(range); range.startContainer.parentElement?.scrollIntoView({ block: "center" }); } return { get query() { return query; }, readOnly: true, canSelectAll: false, setQuery(value) { if (query.eq(value)) return; query = value; current = -1; window.getSelection()?.removeAllRanges(); }, next, selectAll() {}, replace() {}, close() { close(); if (options.focusOnClose) options.focusOnClose(); else root.focus({ preventScroll: true }); }, }; }