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