Open History to see the last commit
1import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
2import { useEffect, useLayoutEffect, 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;
15}
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;
73}
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;
91}
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;
97}
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);
109}
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 const selectionRef = useRef({ activeRowId, activeOccurrence, onActiveRange });
123 useLayoutEffect(() => {
124 selectionRef.current = { activeRowId, activeOccurrence, onActiveRange };
125 }, [activeRowId, activeOccurrence, onActiveRange]);
126
127 useEffect(() => {
128 if (typeof CSS === "undefined" || !CSS.highlights || typeof Highlight === "undefined") {
129 selectionRef.current.onActiveRange(null);
130 return;
131 }
132 const clearHighlights = () => {
133 CSS.highlights.delete(THREAD_FIND_HIGHLIGHT_NAME);
134 CSS.highlights.delete(THREAD_FIND_ACTIVE_HIGHLIGHT_NAME);
135 };
136 rangesRef.current = [];
137 if (!container || query.length === 0) {
138 selectionRef.current.onActiveRange(null);
139 clearHighlights();
140 return;
141 }
142
143 const cache = new Map<Element, readonly ThreadFindRange[]>();
144 const paint = makeThreadFindHighlightPainter(container);
145 paintRef.current = paint;
146 const repaint = () => {
147 const rows = new Set(container.querySelectorAll("[data-timeline-row-id]"));
148 const ranges: ThreadFindRange[] = [];
149 for (const row of rows) {
150 let matches = cache.get(row);
151 if (
152 !matches ||
153 matches.some(
154 ({ range }) => !row.contains(range.startContainer) || !row.contains(range.endContainer),
155 )
156 ) {
157 matches = collectThreadFindRanges(row as HTMLElement, query);
158 cache.set(row, matches);
159 }
160 ranges.push(...matches);
161 }
162 for (const row of cache.keys()) if (!rows.has(row)) cache.delete(row);
163 rangesRef.current = ranges;
164 paint(ranges, selectionRef.current);
165 };
166 let frame: number | null = null;
167 const observer = new MutationObserver((mutations) => {
168 // Timers and status chrome tick every second; only searchable text and folds matter.
169 const relevant = mutations.filter(affectsSearchableText);
170 if (relevant.length === 0) return;
171 for (const mutation of relevant) {
172 const target =
173 mutation.target.nodeType === 1
174 ? (mutation.target as Element)
175 : mutation.target.parentElement;
176 const row = target?.closest("[data-timeline-row-id]");
177 if (row) cache.delete(row);
178 }
179 if (frame !== null) return;
180 frame = requestAnimationFrame(() => {
181 frame = null;
182 repaint();
183 });
184 });
185 observer.observe(container, {
186 subtree: true,
187 childList: true,
188 characterData: true,
189 attributes: true,
190 attributeFilter: [
191 "data-wrap",
192 "hidden",
193 "data-thread-find-fold",
194 "data-timeline-row-id",
195 "data-thread-find-text",
196 "data-thread-find-ignore",
197 ],
198 });
199 // Revealing the first match can synchronously mount or recycle list rows.
200 repaint();
201 return () => {
202 observer.disconnect();
203 if (frame !== null) cancelAnimationFrame(frame);
204 cache.clear();
205 paintRef.current = null;
206 rangesRef.current = [];
207 clearHighlights();
208 };
209 }, [container, query]);
210
211 useEffect(() => {
212 paintRef.current?.(rangesRef.current, { activeRowId, activeOccurrence, onActiveRange });
213 }, [activeOccurrence, activeRowId, onActiveRange]);
214}
215
216function makeThreadFindHighlightPainter(container: HTMLElement) {
217 let previousRanges: readonly ThreadFindRange[] | null = null;
218 const rangesByRow = new Map<string, Range[]>();
219 const inactive = new Highlight();
220 const active = new Highlight();
221 let previousActive: Range | null = null;
222 CSS.highlights.set(THREAD_FIND_HIGHLIGHT_NAME, inactive);
223 CSS.highlights.set(THREAD_FIND_ACTIVE_HIGHLIGHT_NAME, active);
224 return (
225 ranges: readonly ThreadFindRange[],
226 selection: Pick<
227 Parameters<typeof useThreadFindHighlights>[0],
228 "activeRowId" | "activeOccurrence" | "onActiveRange"
229 >,
230 ) => {
231 if (previousRanges !== ranges) {
232 previousRanges = ranges;
233 previousActive = null;
234 rangesByRow.clear();
235 inactive.clear();
236 for (const match of ranges) {
237 const row = rangesByRow.get(match.rowId) ?? [];
238 row[match.occurrence] = match.range;
239 rangesByRow.set(match.rowId, row);
240 if (foldsHiding(match.range, container).length === 0) inactive.add(match.range);
241 }
242 }
243 if (previousActive && foldsHiding(previousActive, container).length === 0)
244 inactive.add(previousActive);
245 const selected =
246 selection.activeRowId === null
247 ? null
248 : (rangesByRow.get(selection.activeRowId)?.[selection.activeOccurrence] ?? null);
249 active.clear();
250 if (selected) inactive.delete(selected);
251 previousActive = selected;
252 if (selected && revealFolded(selected, container)) {
253 selection.onActiveRange(null);
254 } else {
255 if (selected) active.add(selected);
256 selection.onActiveRange(selected);
257 }
258 };
259}