The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; |
| 2 | import { useEffect, useEffectEvent, useRef } from "react"; |
| 3 | import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindText"; |
| 4 | |
| 5 | import { observeResize } from "~/lib/observeResize"; |
| 6 | |
| 7 | const THREAD_FIND_HIGHLIGHT_NAME = "t3-thread-find"; |
| 8 | const THREAD_FIND_ACTIVE_HIGHLIGHT_NAME = "t3-thread-find-active"; |
| 9 | |
| 10 | const THREAD_FIND_TEXT_SELECTOR = "[data-thread-find-text]"; |
| 11 | const THREAD_FIND_IGNORE_SELECTOR = "[data-thread-find-ignore]"; |
| 12 | |
| 13 | interface ThreadFindRange { |
| 14 | readonly rowId: string; |
| 15 | readonly occurrence: number; |
| 16 | readonly range: Range; |
| 17 | } |
| 18 | |
| 19 | export function collectThreadFindRanges(container: HTMLElement, query: string): ThreadFindRange[] { |
| 20 | if (query.length === 0) return []; |
| 21 | |
| 22 | const ranges: ThreadFindRange[] = []; |
| 23 | const occurrenceByRowId = new Map<string, number>(); |
| 24 | |
| 25 | for (const scope of container.querySelectorAll(THREAD_FIND_TEXT_SELECTOR)) { |
| 26 | if (scope.parentElement?.closest(THREAD_FIND_TEXT_SELECTOR)) continue; |
| 27 | const rowId = scope.closest("[data-timeline-row-id]")?.getAttribute("data-timeline-row-id"); |
| 28 | if (!rowId) continue; |
| 29 | |
| 30 | let text = ""; |
| 31 | let nodes: { node: Node; start: number; end: number }[] = []; |
| 32 | const flush = () => { |
| 33 | let startIndex = 0; |
| 34 | let endIndex = 0; |
| 35 | for (const offset of findThreadSearchOccurrences(text, query)) { |
| 36 | while (startIndex < nodes.length && nodes[startIndex]!.end <= offset) startIndex++; |
| 37 | if (endIndex < startIndex) endIndex = startIndex; |
| 38 | while (endIndex < nodes.length && nodes[endIndex]!.end < offset + query.length) endIndex++; |
| 39 | const start = nodes[startIndex]; |
| 40 | const end = nodes[endIndex]; |
| 41 | if (!start || !end) continue; |
| 42 | const range = container.ownerDocument.createRange(); |
| 43 | range.setStart(start.node, offset - start.start); |
| 44 | range.setEnd(end.node, offset + query.length - end.start); |
| 45 | const occurrence = occurrenceByRowId.get(rowId) ?? 0; |
| 46 | ranges.push({ rowId, occurrence, range }); |
| 47 | occurrenceByRowId.set(rowId, occurrence + 1); |
| 48 | } |
| 49 | text = ""; |
| 50 | nodes = []; |
| 51 | }; |
| 52 | const visit = (node: Node, inPre = false) => { |
| 53 | const element = node.nodeType === 1 ? (node as Element) : null; |
| 54 | if (element?.matches("svg")) return; |
| 55 | if (element?.matches(`${THREAD_FIND_IGNORE_SELECTOR}, [role="toolbar"]`)) { |
| 56 | flush(); |
| 57 | return; |
| 58 | } |
| 59 | const tag = element?.tagName.toLowerCase() ?? ""; |
| 60 | const block = THREAD_FIND_BLOCK_TAGS.has(tag); |
| 61 | if (block) flush(); |
| 62 | if (node.nodeType === 3) { |
| 63 | const value = node.nodeValue ?? ""; |
| 64 | const start = text.length; |
| 65 | text += inPre ? value : value.replace(/\r?\n/g, " "); |
| 66 | nodes.push({ node, start, end: text.length }); |
| 67 | } |
| 68 | for (const child of node.childNodes) visit(child, inPre || tag === "pre"); |
| 69 | if (block) flush(); |
| 70 | }; |
| 71 | visit(scope); |
| 72 | flush(); |
| 73 | } |
| 74 | return ranges; |
| 75 | } |
| 76 | |
| 77 | const FOLD_SELECTOR = "[hidden], [data-thread-find-fold]"; |
| 78 | |
| 79 | function foldsHiding(range: Range, container: HTMLElement): Element[] { |
| 80 | const folds: Element[] = []; |
| 81 | for ( |
| 82 | let fold = range.startContainer.parentElement?.closest(FOLD_SELECTOR); |
| 83 | fold && container.contains(fold); |
| 84 | fold = fold.parentElement?.closest(FOLD_SELECTOR) |
| 85 | ) { |
| 86 | if ( |
| 87 | fold.hasAttribute("hidden") || |
| 88 | range.getBoundingClientRect().bottom > fold.getBoundingClientRect().bottom |
| 89 | ) |
| 90 | folds.push(fold); |
| 91 | } |
| 92 | return folds; |
| 93 | } |
| 94 | |
| 95 | function revealFolded(range: Range, container: HTMLElement): boolean { |
| 96 | const folds = foldsHiding(range, container); |
| 97 | for (const fold of folds) fold.dispatchEvent(new Event("beforematch")); |
| 98 | return folds.length > 0; |
| 99 | } |
| 100 | |
| 101 | function affectsSearchableText(record: MutationRecord): boolean { |
| 102 | if (record.type === "attributes") return true; |
| 103 | const target = |
| 104 | record.target.nodeType === 1 ? (record.target as Element) : record.target.parentElement; |
| 105 | if (target?.closest(THREAD_FIND_TEXT_SELECTOR)) return true; |
| 106 | const touchesScope = (node: Node) => |
| 107 | node.nodeType === 1 && |
| 108 | ((node as Element).matches(THREAD_FIND_TEXT_SELECTOR) || |
| 109 | (node as Element).querySelector(THREAD_FIND_TEXT_SELECTOR) !== null); |
| 110 | return [...record.addedNodes, ...record.removedNodes].some(touchesScope); |
| 111 | } |
| 112 | |
| 113 | export function useThreadFindHighlights(input: { |
| 114 | readonly container: HTMLElement | null; |
| 115 | readonly query: string; |
| 116 | readonly activeRowId: string | null; |
| 117 | readonly activeOccurrence: number; |
| 118 | readonly onActiveRange: (range: Range | null) => void; |
| 119 | }): void { |
| 120 | const { container, query, activeRowId, activeOccurrence, onActiveRange } = input; |
| 121 | |
| 122 | const rangesRef = useRef<readonly ThreadFindRange[]>([]); |
| 123 | const paintRef = useRef<ReturnType<typeof makeThreadFindHighlightPainter> | null>(null); |
| 124 | // The observer repaints with whichever match is selected when text changes. |
| 125 | const readSelection = useEffectEvent(() => ({ activeRowId, activeOccurrence, onActiveRange })); |
| 126 | |
| 127 | // 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 |
| 128 | useEffect(() => { |
| 129 | if (typeof CSS === "undefined" || !CSS.highlights || typeof Highlight === "undefined") { |
| 130 | readSelection().onActiveRange(null); |
| 131 | return; |
| 132 | } |
| 133 | const clearHighlights = () => { |
| 134 | CSS.highlights.delete(THREAD_FIND_HIGHLIGHT_NAME); |
| 135 | CSS.highlights.delete(THREAD_FIND_ACTIVE_HIGHLIGHT_NAME); |
| 136 | }; |
| 137 | rangesRef.current = []; |
| 138 | if (!container || query.length === 0) { |
| 139 | readSelection().onActiveRange(null); |
| 140 | clearHighlights(); |
| 141 | return; |
| 142 | } |
| 143 | |
| 144 | const cache = new Map<Element, readonly ThreadFindRange[]>(); |
| 145 | const paint = makeThreadFindHighlightPainter(container); |
| 146 | paintRef.current = paint; |
| 147 | const repaint = () => { |
| 148 | const rows = new Set(container.querySelectorAll("[data-timeline-row-id]")); |
| 149 | const ranges: ThreadFindRange[] = []; |
| 150 | for (const row of rows) { |
| 151 | let matches = cache.get(row); |
| 152 | if ( |
| 153 | !matches || |
| 154 | matches.some( |
| 155 | ({ range }) => !row.contains(range.startContainer) || !row.contains(range.endContainer), |
| 156 | ) |
| 157 | ) { |
| 158 | matches = collectThreadFindRanges(row as HTMLElement, query); |
| 159 | cache.set(row, matches); |
| 160 | } |
| 161 | for (const match of matches) ranges.push(match); |
| 162 | } |
| 163 | for (const row of cache.keys()) if (!rows.has(row)) cache.delete(row); |
| 164 | rangesRef.current = ranges; |
| 165 | paint.update(cache, ranges, readSelection()); |
| 166 | }; |
| 167 | let frame: number | null = null; |
| 168 | let dirty = false; |
| 169 | const schedule = () => { |
| 170 | if (frame !== null) return; |
| 171 | frame = requestAnimationFrame(() => { |
| 172 | frame = null; |
| 173 | if (dirty) repaint(); |
| 174 | else paint.place(cache); |
| 175 | dirty = false; |
| 176 | }); |
| 177 | }; |
| 178 | const observer = new MutationObserver((mutations) => { |
| 179 | // Ignore timer and status mutations outside searchable text and folds. |
| 180 | const relevant = mutations.filter(affectsSearchableText); |
| 181 | if (relevant.length === 0) return; |
| 182 | for (const mutation of relevant) { |
| 183 | const target = |
| 184 | mutation.target.nodeType === 1 |
| 185 | ? (mutation.target as Element) |
| 186 | : mutation.target.parentElement; |
| 187 | const row = target?.closest("[data-timeline-row-id]"); |
| 188 | if (row) cache.delete(row); |
| 189 | // A hidden wrapper around rows changes their runs, which are cached with their matches. |
| 190 | if (mutation.attributeName === "hidden" && target) |
| 191 | for (const cached of cache.keys()) if (target.contains(cached)) cache.delete(cached); |
| 192 | } |
| 193 | dirty = true; |
| 194 | schedule(); |
| 195 | }); |
| 196 | observer.observe(container, { |
| 197 | subtree: true, |
| 198 | childList: true, |
| 199 | characterData: true, |
| 200 | attributes: true, |
| 201 | attributeFilter: [ |
| 202 | "data-wrap", |
| 203 | "hidden", |
| 204 | "data-thread-find-fold", |
| 205 | "data-timeline-row-id", |
| 206 | "data-thread-find-text", |
| 207 | "data-thread-find-ignore", |
| 208 | ], |
| 209 | }); |
| 210 | container.addEventListener("scroll", schedule, { passive: true }); |
| 211 | const stopResize = observeResize(container, schedule); |
| 212 | // Revealing the first match can synchronously mount or recycle list rows. |
| 213 | repaint(); |
| 214 | return () => { |
| 215 | observer.disconnect(); |
| 216 | stopResize(); |
| 217 | container.removeEventListener("scroll", schedule); |
| 218 | if (frame !== null) cancelAnimationFrame(frame); |
| 219 | cache.clear(); |
| 220 | paintRef.current = null; |
| 221 | rangesRef.current = []; |
| 222 | clearHighlights(); |
| 223 | }; |
| 224 | }, [container, query]); |
| 225 | |
| 226 | // onActiveRange is read at paint time: its identity follows the caller's |
| 227 | // layout inputs, and repainting the active highlight for those is wasted work. |
| 228 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- repaints the active CSS Highlight range when the selected match changes |
| 229 | useEffect(() => { |
| 230 | paintRef.current?.select({ |
| 231 | activeRowId, |
| 232 | activeOccurrence, |
| 233 | onActiveRange: readSelection().onActiveRange, |
| 234 | }); |
| 235 | }, [activeOccurrence, activeRowId]); |
| 236 | } |
| 237 | |
| 238 | type ThreadFindSelection = Pick< |
| 239 | Parameters<typeof useThreadFindHighlights>[0], |
| 240 | "activeRowId" | "activeOccurrence" | "onActiveRange" |
| 241 | >; |
| 242 | |
| 243 | interface TextRun { |
| 244 | readonly start: number; |
| 245 | end: number; |
| 246 | readonly box: Element; |
| 247 | readonly item: Node | null; |
| 248 | readonly ordered: boolean; |
| 249 | readonly hidden: boolean; |
| 250 | } |
| 251 | |
| 252 | const INLINE_DISPLAYS = new Set(["inline", "contents"]); |
| 253 | const textRunsByMatches = new WeakMap<readonly ThreadFindRange[], readonly TextRun[]>(); |
| 254 | |
| 255 | // Splits a row's matches into runs that each lie in one inline formatting context, |
| 256 | // where a later match is never higher on screen. Cells, flex and grid items, and |
| 257 | // inline blocks each start a run, since their text can sit beside earlier text. |
| 258 | function textRuns(row: Element, matches: readonly ThreadFindRange[]): readonly TextRun[] { |
| 259 | const cached = textRunsByMatches.get(matches); |
| 260 | if (cached) return cached; |
| 261 | const displays = new Map<Element, string>(); |
| 262 | const displayOf = (element: Element) => { |
| 263 | let display = displays.get(element); |
| 264 | if (display === undefined) { |
| 265 | display = getComputedStyle(element).display; |
| 266 | displays.set(element, display); |
| 267 | } |
| 268 | return display; |
| 269 | }; |
| 270 | const columns = new Map<Element, boolean>(); |
| 271 | const inColumns = (element: Element): boolean => { |
| 272 | let multicol = columns.get(element); |
| 273 | if (multicol === undefined) { |
| 274 | const style = getComputedStyle(element); |
| 275 | multicol = |
| 276 | style.columnCount !== "auto" || |
| 277 | style.columnWidth !== "auto" || |
| 278 | (element !== row && element.parentElement !== null && inColumns(element.parentElement)); |
| 279 | columns.set(element, multicol); |
| 280 | } |
| 281 | return multicol; |
| 282 | }; |
| 283 | const runs: TextRun[] = []; |
| 284 | let text: Node | null = null; |
| 285 | for (const [index, { range }] of matches.entries()) { |
| 286 | const last = runs.at(-1); |
| 287 | if (last && range.startContainer === text) { |
| 288 | last.end = index + 1; |
| 289 | continue; |
| 290 | } |
| 291 | const parent = range.startContainer.parentElement; |
| 292 | if (!parent) continue; |
| 293 | text = range.startContainer; |
| 294 | let box = parent; |
| 295 | while (box !== row && box.parentElement && INLINE_DISPLAYS.has(displayOf(box))) |
| 296 | box = box.parentElement; |
| 297 | // Text directly inside a flex or grid container is an anonymous item of its own. |
| 298 | const item = /flex|grid/.test(displayOf(box)) ? text : null; |
| 299 | const hidden = parent.closest("[hidden]") !== null; |
| 300 | if (last?.end === index && last.box === box && last.item === item && last.hidden === hidden) { |
| 301 | last.end = index + 1; |
| 302 | continue; |
| 303 | } |
| 304 | runs.push({ start: index, end: index + 1, box, item, hidden, ordered: !inColumns(box) }); |
| 305 | } |
| 306 | textRunsByMatches.set(matches, runs); |
| 307 | return runs; |
| 308 | } |
| 309 | |
| 310 | // Blink rebuilds every registered highlight Range on any DOM or style change, so |
| 311 | // only matches within a screen of the viewport are painted; the active one always is. |
| 312 | function matchesInZone( |
| 313 | row: Element, |
| 314 | matches: readonly ThreadFindRange[], |
| 315 | zone: { top: number; bottom: number }, |
| 316 | shown: Set<Range>, |
| 317 | ): void { |
| 318 | const rowBox = row.getBoundingClientRect(); |
| 319 | if (matches.length === 0 || rowBox.bottom < zone.top || rowBox.top > zone.bottom) return; |
| 320 | const intersects = (rect: DOMRect) => rect.bottom >= zone.top && rect.top <= zone.bottom; |
| 321 | for (const run of textRuns(row, matches)) { |
| 322 | if (run.hidden) continue; |
| 323 | const boxes = run.box.getClientRects(); |
| 324 | if (boxes.length === 0 || ![...boxes].some(intersects)) continue; |
| 325 | if (!run.ordered) { |
| 326 | for (let index = run.start; index < run.end; index++) |
| 327 | if (intersects(matches[index]!.range.getBoundingClientRect())) |
| 328 | shown.add(matches[index]!.range); |
| 329 | continue; |
| 330 | } |
| 331 | const firstShown = (index: number, high: number): [number, DOMRect | null] => { |
| 332 | for (; index < high; index++) { |
| 333 | const rect = matches[index]!.range.getBoundingClientRect(); |
| 334 | if (rect.height > 0) return [index, rect]; |
| 335 | } |
| 336 | return [high, null]; |
| 337 | }; |
| 338 | const firstWhere = (isPast: (rect: DOMRect) => boolean) => { |
| 339 | let low = run.start; |
| 340 | let high = run.end; |
| 341 | while (low < high) { |
| 342 | const mid = (low + high) >>> 1; |
| 343 | const [probe, rect] = firstShown(mid, high); |
| 344 | if (!rect || isPast(rect)) high = mid; |
| 345 | else low = probe + 1; |
| 346 | } |
| 347 | return low; |
| 348 | }; |
| 349 | const end = firstWhere((rect) => rect.top > zone.bottom); |
| 350 | for (let index = firstWhere((rect) => rect.bottom >= zone.top); index < end; index++) |
| 351 | shown.add(matches[index]!.range); |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | function makeThreadFindHighlightPainter(container: HTMLElement) { |
| 356 | const inactive = new Highlight(); |
| 357 | const active = new Highlight(); |
| 358 | const zoned = new Set<Range>(); |
| 359 | const windows = new Map<Element, Set<Range>>(); |
| 360 | const rangesByRow = new Map<string, Range[]>(); |
| 361 | let selected: Range | null = null; |
| 362 | CSS.highlights.set(THREAD_FIND_HIGHLIGHT_NAME, inactive); |
| 363 | CSS.highlights.set(THREAD_FIND_ACTIVE_HIGHLIGHT_NAME, active); |
| 364 | const show = (range: Range) => { |
| 365 | zoned.add(range); |
| 366 | if (range !== selected && foldsHiding(range, container).length === 0) inactive.add(range); |
| 367 | }; |
| 368 | const hide = (range: Range) => { |
| 369 | zoned.delete(range); |
| 370 | inactive.delete(range); |
| 371 | }; |
| 372 | const place = (rows: ReadonlyMap<Element, readonly ThreadFindRange[]>) => { |
| 373 | const viewport = container.getBoundingClientRect(); |
| 374 | const zone = { top: viewport.top - viewport.height, bottom: viewport.bottom + viewport.height }; |
| 375 | for (const [row, previous] of windows) { |
| 376 | if (rows.has(row)) continue; |
| 377 | for (const range of previous) hide(range); |
| 378 | windows.delete(row); |
| 379 | } |
| 380 | for (const [row, matches] of rows) { |
| 381 | const shown = new Set<Range>(); |
| 382 | matchesInZone(row, matches, zone, shown); |
| 383 | const previous = windows.get(row); |
| 384 | if (previous) for (const range of previous) if (!shown.has(range)) hide(range); |
| 385 | for (const range of shown) if (!previous?.has(range)) show(range); |
| 386 | windows.set(row, shown); |
| 387 | } |
| 388 | }; |
| 389 | const select = (selection: ThreadFindSelection) => { |
| 390 | const next = |
| 391 | selection.activeRowId === null |
| 392 | ? null |
| 393 | : (rangesByRow.get(selection.activeRowId)?.[selection.activeOccurrence] ?? null); |
| 394 | if (selected && selected !== next && zoned.has(selected)) { |
| 395 | if (foldsHiding(selected, container).length === 0) inactive.add(selected); |
| 396 | } |
| 397 | selected = next; |
| 398 | active.clear(); |
| 399 | if (next) inactive.delete(next); |
| 400 | if (next && revealFolded(next, container)) { |
| 401 | selection.onActiveRange(null); |
| 402 | } else { |
| 403 | if (next) active.add(next); |
| 404 | selection.onActiveRange(next); |
| 405 | } |
| 406 | }; |
| 407 | const update = ( |
| 408 | rows: ReadonlyMap<Element, readonly ThreadFindRange[]>, |
| 409 | ranges: readonly ThreadFindRange[], |
| 410 | selection: ThreadFindSelection, |
| 411 | ) => { |
| 412 | rangesByRow.clear(); |
| 413 | for (const match of ranges) { |
| 414 | const row = rangesByRow.get(match.rowId) ?? []; |
| 415 | row[match.occurrence] = match.range; |
| 416 | rangesByRow.set(match.rowId, row); |
| 417 | } |
| 418 | place(rows); |
| 419 | select(selection); |
| 420 | }; |
| 421 | return { update, place, select }; |
| 422 | } |