Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadFindHighlights.ts

265 lines9.7 KB

1import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
2import { useEffect, useEffectEvent, useRef } from "react";
3import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindText";
4​
5const THREAD_FIND_HIGHLIGHT_NAME = "t3-thread-find";
6const THREAD_FIND_ACTIVE_HIGHLIGHT_NAME = "t3-thread-find-active";
7​
8const THREAD_FIND_TEXT_SELECTOR = "[data-thread-find-text]";
9const THREAD_FIND_IGNORE_SELECTOR = "[data-thread-find-ignore]";
10​
11interface ThreadFindRange {
12 readonly rowId: string;
13 readonly occurrence: number;
14 readonly range: Range;
16​
17export function collectThreadFindRanges(container: HTMLElement, query: string): ThreadFindRange[] {
18 if (query.length === 0) return [];
19​
20 const ranges: ThreadFindRange[] = [];
21 const occurrenceByRowId = new Map<string, number>();
22​
23 for (const scope of container.querySelectorAll(THREAD_FIND_TEXT_SELECTOR)) {
24 if (scope.parentElement?.closest(THREAD_FIND_TEXT_SELECTOR)) continue;
25 const rowId = scope.closest("[data-timeline-row-id]")?.getAttribute("data-timeline-row-id");
26 if (!rowId) continue;
27​
28 let text = "";
29 let nodes: { node: Node; start: number; end: number }[] = [];
30 const flush = () => {
31 let startIndex = 0;
32 let endIndex = 0;
33 for (const offset of findThreadSearchOccurrences(text, query)) {
34 while (startIndex < nodes.length && nodes[startIndex]!.end <= offset) startIndex++;
35 if (endIndex < startIndex) endIndex = startIndex;
36 while (endIndex < nodes.length && nodes[endIndex]!.end < offset + query.length) endIndex++;
37 const start = nodes[startIndex];
38 const end = nodes[endIndex];
39 if (!start || !end) continue;
40 const range = container.ownerDocument.createRange();
41 range.setStart(start.node, offset - start.start);
42 range.setEnd(end.node, offset + query.length - end.start);
43 const occurrence = occurrenceByRowId.get(rowId) ?? 0;
44 ranges.push({ rowId, occurrence, range });
45 occurrenceByRowId.set(rowId, occurrence + 1);
46 }
47 text = "";
48 nodes = [];
49 };
50 const visit = (node: Node, inPre = false) => {
51 const element = node.nodeType === 1 ? (node as Element) : null;
52 if (element?.matches("svg")) return;
53 if (element?.matches(`${THREAD_FIND_IGNORE_SELECTOR}, [role="toolbar"]`)) {
54 flush();
55 return;
56 }
57 const tag = element?.tagName.toLowerCase() ?? "";
58 const block = THREAD_FIND_BLOCK_TAGS.has(tag);
59 if (block) flush();
60 if (node.nodeType === 3) {
61 const value = node.nodeValue ?? "";
62 const start = text.length;
63 text += inPre ? value : value.replace(/\r?\n/g, " ");
64 nodes.push({ node, start, end: text.length });
65 }
66 for (const child of node.childNodes) visit(child, inPre || tag === "pre");
67 if (block) flush();
68 };
69 visit(scope);
70 flush();
71 }
72 return ranges;
74​
75const FOLD_SELECTOR = "[hidden], [data-thread-find-fold]";
76​
77function foldsHiding(range: Range, container: HTMLElement): Element[] {
78 const folds: Element[] = [];
79 for (
80 let fold = range.startContainer.parentElement?.closest(FOLD_SELECTOR);
81 fold && container.contains(fold);
82 fold = fold.parentElement?.closest(FOLD_SELECTOR)
83 ) {
84 if (
85 fold.hasAttribute("hidden") ||
86 range.getBoundingClientRect().bottom > fold.getBoundingClientRect().bottom
87 )
88 folds.push(fold);
89 }
90 return folds;
92​
93function revealFolded(range: Range, container: HTMLElement): boolean {
94 const folds = foldsHiding(range, container);
95 for (const fold of folds) fold.dispatchEvent(new Event("beforematch"));
96 return folds.length > 0;
98​
99function affectsSearchableText(record: MutationRecord): boolean {
100 if (record.type === "attributes") return true;
101 const target =
102 record.target.nodeType === 1 ? (record.target as Element) : record.target.parentElement;
103 if (target?.closest(THREAD_FIND_TEXT_SELECTOR)) return true;
104 const touchesScope = (node: Node) =>
105 node.nodeType === 1 &&
106 ((node as Element).matches(THREAD_FIND_TEXT_SELECTOR) ||
107 (node as Element).querySelector(THREAD_FIND_TEXT_SELECTOR) !== null);
108 return [...record.addedNodes, ...record.removedNodes].some(touchesScope);
110​
111export function useThreadFindHighlights(input: {
112 readonly container: HTMLElement | null;
113 readonly query: string;
114 readonly activeRowId: string | null;
115 readonly activeOccurrence: number;
116 readonly onActiveRange: (range: Range | null) => void;
117}): void {
118 const { container, query, activeRowId, activeOccurrence, onActiveRange } = input;
119​
120 const rangesRef = useRef<readonly ThreadFindRange[]>([]);
121 const paintRef = useRef<ReturnType<typeof makeThreadFindHighlightPainter> | null>(null);
122 // The observer repaints with whichever match is selected when text changes.
123 const readSelection = useEffectEvent(() => ({ activeRowId, activeOccurrence, onActiveRange }));
124​
125 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- paints CSS Highlight ranges for the query, repainting on DOM mutations, and clears them on cleanup
126 useEffect(() => {
127 if (typeof CSS === "undefined" || !CSS.highlights || typeof Highlight === "undefined") {
128 readSelection().onActiveRange(null);
129 return;
130 }
131 const clearHighlights = () => {
132 CSS.highlights.delete(THREAD_FIND_HIGHLIGHT_NAME);
133 CSS.highlights.delete(THREAD_FIND_ACTIVE_HIGHLIGHT_NAME);
134 };
135 rangesRef.current = [];
136 if (!container || query.length === 0) {
137 readSelection().onActiveRange(null);
138 clearHighlights();
139 return;
140 }
141​
142 const cache = new Map<Element, readonly ThreadFindRange[]>();
143 const paint = makeThreadFindHighlightPainter(container);
144 paintRef.current = paint;
145 const repaint = () => {
146 const rows = new Set(container.querySelectorAll("[data-timeline-row-id]"));
147 const ranges: ThreadFindRange[] = [];
148 for (const row of rows) {
149 let matches = cache.get(row);
150 if (
151 !matches ||
152 matches.some(
153 ({ range }) => !row.contains(range.startContainer) || !row.contains(range.endContainer),
154 )
155 ) {
156 matches = collectThreadFindRanges(row as HTMLElement, query);
157 cache.set(row, matches);
158 }
159 ranges.push(...matches);
160 }
161 for (const row of cache.keys()) if (!rows.has(row)) cache.delete(row);
162 rangesRef.current = ranges;
163 paint(ranges, readSelection());
164 };
165 let frame: number | null = null;
166 const observer = new MutationObserver((mutations) => {
167 // Ignore timer and status mutations outside searchable text and folds.
168 const relevant = mutations.filter(affectsSearchableText);
169 if (relevant.length === 0) return;
170 for (const mutation of relevant) {
171 const target =
172 mutation.target.nodeType === 1
173 ? (mutation.target as Element)
174 : mutation.target.parentElement;
175 const row = target?.closest("[data-timeline-row-id]");
176 if (row) cache.delete(row);
177 }
178 if (frame !== null) return;
179 frame = requestAnimationFrame(() => {
180 frame = null;
181 repaint();
182 });
183 });
184 observer.observe(container, {
185 subtree: true,
186 childList: true,
187 characterData: true,
188 attributes: true,
189 attributeFilter: [
190 "data-wrap",
191 "hidden",
192 "data-thread-find-fold",
193 "data-timeline-row-id",
194 "data-thread-find-text",
195 "data-thread-find-ignore",
196 ],
197 });
198 // Revealing the first match can synchronously mount or recycle list rows.
199 repaint();
200 return () => {
201 observer.disconnect();
202 if (frame !== null) cancelAnimationFrame(frame);
203 cache.clear();
204 paintRef.current = null;
205 rangesRef.current = [];
206 clearHighlights();
207 };
208 }, [container, query]);
209​
210 // onActiveRange is read at paint time: its identity follows the caller's
211 // layout inputs, and repainting the active highlight for those is wasted work.
212 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- repaints the active CSS Highlight range when the selected match changes
213 useEffect(() => {
214 paintRef.current?.(rangesRef.current, {
215 activeRowId,
216 activeOccurrence,
217 onActiveRange: readSelection().onActiveRange,
218 });
219 }, [activeOccurrence, activeRowId]);
221​
222function makeThreadFindHighlightPainter(container: HTMLElement) {
223 let previousRanges: readonly ThreadFindRange[] | null = null;
224 const rangesByRow = new Map<string, Range[]>();
225 const inactive = new Highlight();
226 const active = new Highlight();
227 let previousActive: Range | null = null;
228 CSS.highlights.set(THREAD_FIND_HIGHLIGHT_NAME, inactive);
229 CSS.highlights.set(THREAD_FIND_ACTIVE_HIGHLIGHT_NAME, active);
230 return (
231 ranges: readonly ThreadFindRange[],
232 selection: Pick<
233 Parameters<typeof useThreadFindHighlights>[0],
234 "activeRowId" | "activeOccurrence" | "onActiveRange"
235 >,
236 ) => {
237 if (previousRanges !== ranges) {
238 previousRanges = ranges;
239 previousActive = null;
240 rangesByRow.clear();
241 inactive.clear();
242 for (const match of ranges) {
243 const row = rangesByRow.get(match.rowId) ?? [];
244 row[match.occurrence] = match.range;
245 rangesByRow.set(match.rowId, row);
246 if (foldsHiding(match.range, container).length === 0) inactive.add(match.range);
247 }
248 }
249 if (previousActive && foldsHiding(previousActive, container).length === 0)
250 inactive.add(previousActive);
251 const selected =
252 selection.activeRowId === null
253 ? null
254 : (rangesByRow.get(selection.activeRowId)?.[selection.activeOccurrence] ?? null);
255 active.clear();
256 if (selected) inactive.delete(selected);
257 previousActive = selected;
258 if (selected && revealFolded(selected, container)) {
259 selection.onActiveRange(null);
260 } else {
261 if (selected) active.add(selected);
262 selection.onActiveRange(selected);
263 }
264 };