Files
RuneStone/src/lib/editor/readingSearch.ts
T
Knotty Wyvern cbdaa12c84 Keep the caret in Find while typing in Read
Find on the reading side stopped after one or two characters. Each key
cleared the window selection, and that also removed the caret of the
find field. This occurs only with real key input in WebView2.

- A new search text clears the selection only when it is a match in the
  text.
- After Enter selects a match, the next key puts the caret at the end of
  the field. Enter, Escape, Tab, function keys, and Ctrl+C keep the
  match selected.

The find/typing smoke test types key by key in Write, Source, Read, and
Split. Test keys do not show the first fault, so real keys in a debug
app confirmed that part. Card 340644d5.
2026-11-04 21:41:20 -07:00

64 lines
3.6 KiB
TypeScript

import { SearchQuery } from "@codemirror/search";
import { documentMatches, type FindTarget } from "./findTarget";
/** Keys that do not change the text of the find field. These keys keep the selected match. */
const keepsMatch = /^(?:Enter|Escape|Tab|Shift|Control|Alt|Meta|CapsLock|ContextMenu|F\d+)$/;
/** 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;
// The window selection also holds the caret of a focused find field. There it reads as collapsed and outside the text.
function matchSelected() {
const selection = window.getSelection();
return !!selection && !selection.isCollapsed && root.contains(selection.anchorNode);
}
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; if (matchSelected()) window.getSelection()?.removeAllRanges(); },
// A selected match takes the caret from the find field, and the browser then drops typed keys. Put the caret back first.
// The field cannot report its old caret at this time, so the caret goes to the end of the text.
keydown(event) {
const field = event.target;
const copy = (event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "c";
if (field instanceof HTMLInputElement && field.type === "text" && !copy && !keepsMatch.test(event.key) && matchSelected()) field.setSelectionRange(field.value.length, field.value.length);
return false;
},
next, selectAll() {}, replace() {},
close() { close(); if (options.focusOnClose) options.focusOnClose(); else root.focus({ preventScroll: true }); },
};
}