@devries-cameron20 / t3code-1 / commits / 009966d073
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(web): find in thread paints only matches near the viewport (#38329)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

shivam committed Nov 18, 2026 at 03:25 UTC 009966d073aa093832ed39278f524e9870adffd6
3 files changed +400 -39
apps/web/src/components/chat/threadFindHighlights.browser.test.tsx
+132 -3
@@ -29,19 +29,148 @@ function Highlights(props: Parameters<typeof useThreadFindHighlights>[0]) {
29 return null;
30 }
31
32 -it("paints every match when one row has more matches than a call can take as arguments", async () => {
32 +function mountTimeline(html: string) {
33 + const container = document.createElement("div");
34 + container.style.cssText = "height: 200px; width: 300px; overflow: auto";
35 + container.innerHTML = html;
36 + document.body.append(container);
37 + return { container, [Symbol.dispose]: () => container.remove() };
38 +}
39 +
40 +const painted = () => [...(CSS.highlights.get("t3-thread-find") ?? [])] as Range[];
41 +const paintedIn = (element: Element) =>
42 + painted().filter((range) => element.contains(range.startContainer)).length;
43 +
44 +it("paints only matches near the viewport plus the active one, in a row with more matches than a call can take as arguments", async () => {
45 const count = 200_000;
46 const onActiveRange = vi.fn<(range: Range | null) => void>();
47 + using timeline = mountTimeline(
48 + `<div data-timeline-row-id="row"><div data-thread-find-text>${"e x".repeat(count)}</div></div>`,
49 + );
50 await using _screen = await render(
51 <Highlights
37 - container={row("e x".repeat(count))}
52 + container={timeline.container}
53 query="e"
54 activeRowId="row"
55 activeOccurrence={count - 1}
56 onActiveRange={onActiveRange}
57 />,
58 );
44 - expect(CSS.highlights.get("t3-thread-find")?.size).toBe(count - 1);
59 + const visible = painted();
60 + expect(visible.length).toBeGreaterThan(0);
61 + expect(visible.length).toBeLessThan(5_000);
62 + expect(Math.max(...visible.map((range) => range.startOffset))).toBeLessThan(count);
63 expect(CSS.highlights.get("t3-thread-find-active")?.size).toBe(1);
64 expect(onActiveRange.mock.lastCall?.[0]?.startOffset).toBe((count - 1) * 3);
65 +
66 + timeline.container.scrollTop = timeline.container.scrollHeight;
67 + await vi.waitFor(() =>
68 + expect(Math.max(...painted().map((range) => range.startOffset))).toBe((count - 2) * 3),
69 + );
70 + expect(painted().length).toBeLessThan(5_000);
71 +});
72 +
73 +it("paints every match near the viewport when cells lay text out in a different order than the DOM", async () => {
74 + using timeline = mountTimeline(
75 + `<div data-timeline-row-id="row"><div data-thread-find-text><table style="width: 100%"><tr>
76 + <td style="vertical-align: top">${"e x ".repeat(5_000)}</td>
77 + <td style="vertical-align: top">${"e x ".repeat(5_000)}</td>
78 + </tr></table></div></div>`,
79 + );
80 + const cells = [...timeline.container.querySelectorAll("td")];
81 + const ranges = collectThreadFindRanges(timeline.container, "e");
82 + const key = (range: Range) =>
83 + `${cells.indexOf(range.startContainer.parentElement as HTMLTableCellElement)}:${range.startOffset}`;
84 + const missing = () => {
85 + const viewport = timeline.container.getBoundingClientRect();
86 + const [top, bottom] = [viewport.top - viewport.height, viewport.bottom + viewport.height];
87 + const shown = new Set(painted().map(key));
88 + return ranges.filter(({ range }) => {
89 + const rect = range.getBoundingClientRect();
90 + return rect.bottom >= top && rect.top <= bottom && !shown.has(key(range));
91 + }).length;
92 + };
93 + await using _screen = await render(
94 + <Highlights
95 + container={timeline.container}
96 + query="e"
97 + activeRowId={null}
98 + activeOccurrence={0}
99 + onActiveRange={() => {}}
100 + />,
101 + );
102 + expect(missing()).toBe(0);
103 +
104 + timeline.container.scrollTop = 1_000;
105 + await vi.waitFor(() => expect(missing()).toBe(0));
106 + expect(painted().length).toBeLessThan(ranges.length / 2);
107 +});
108 +
109 +it("skips a hidden block's matches without measuring each one", async () => {
110 + using timeline = mountTimeline(
111 + `<div data-timeline-row-id="row"><div data-thread-find-text>
112 + <div style="display: none">${"e x ".repeat(10_000)}</div><p>e</p>
113 + </div></div>`,
114 + );
115 + const visible = timeline.container.querySelector("p")!;
116 + using measure = vi.spyOn(Range.prototype, "getBoundingClientRect");
117 + await using _screen = await render(
118 + <Highlights
119 + container={timeline.container}
120 + query="e"
121 + activeRowId={null}
122 + activeOccurrence={0}
123 + onActiveRange={() => {}}
124 + />,
125 + );
126 + expect([painted().length, paintedIn(visible)]).toEqual([1, 1]);
127 + expect(measure.mock.calls.length).toBeLessThan(100);
128 +});
129 +
130 +it("registers a row's matches only while it is near the viewport, and again after its text changes", async () => {
131 + using timeline = mountTimeline(
132 + `<div data-timeline-row-id="near"><div data-thread-find-text>e e e</div></div>
133 + <div style="height: 5000px"></div>
134 + <div data-timeline-row-id="far"><div data-thread-find-text>e e</div></div>`,
135 + );
136 + const [near, far] = [...timeline.container.querySelectorAll("[data-thread-find-text]")];
137 + const onActiveRange = vi.fn<(range: Range | null) => void>();
138 + await using _screen = await render(
139 + <Highlights
140 + container={timeline.container}
141 + query="e"
142 + activeRowId="far"
143 + activeOccurrence={1}
144 + onActiveRange={onActiveRange}
145 + />,
146 + );
147 + expect([paintedIn(near!), paintedIn(far!)]).toEqual([3, 0]);
148 + expect(CSS.highlights.get("t3-thread-find-active")?.size).toBe(1);
149 + expect(far!.contains(onActiveRange.mock.lastCall?.[0]?.startContainer ?? null)).toBe(true);
150 +
151 + near!.append(" e");
152 + await vi.waitFor(() => expect(paintedIn(near!)).toBe(4));
153 +
154 + timeline.container.scrollTop = timeline.container.scrollHeight;
155 + await vi.waitFor(() => expect([paintedIn(near!), paintedIn(far!)]).toEqual([0, 1]));
156 +});
157 +
158 +it("paints a row's matches once the hidden wrapper around it is revealed", async () => {
159 + using timeline = mountTimeline(
160 + `<div id="wrap" hidden><div data-timeline-row-id="row"><div data-thread-find-text>e e</div></div></div>`,
161 + );
162 + const text = timeline.container.querySelector("[data-thread-find-text]")!;
163 + await using _screen = await render(
164 + <Highlights
165 + container={timeline.container}
166 + query="e"
167 + activeRowId={null}
168 + activeOccurrence={0}
169 + onActiveRange={() => {}}
170 + />,
171 + );
172 + expect(paintedIn(text)).toBe(0);
173 +
174 + timeline.container.querySelector("#wrap")!.removeAttribute("hidden");
175 + await vi.waitFor(() => expect(paintedIn(text)).toBe(2));
176 });
apps/web/src/components/chat/threadFindHighlights.ts
+193 -36
@@ -2,6 +2,8 @@ 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
@@ -160,9 +162,19 @@ export function useThreadFindHighlights(input: {
162 }
163 for (const row of cache.keys()) if (!rows.has(row)) cache.delete(row);
164 rangesRef.current = ranges;
163 - paint(ranges, readSelection());
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);
@@ -174,12 +186,12 @@ export function useThreadFindHighlights(input: {
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 }
178 - if (frame !== null) return;
179 - frame = requestAnimationFrame(() => {
180 - frame = null;
181 - repaint();
182 - });
193 + dirty = true;
194 + schedule();
195 });
196 observer.observe(container, {
197 subtree: true,
@@ -195,10 +207,14 @@ export function useThreadFindHighlights(input: {
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;
@@ -211,7 +227,7 @@ export function useThreadFindHighlights(input: {
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(() => {
214 - paintRef.current?.(rangesRef.current, {
230 + paintRef.current?.select({
231 activeRowId,
232 activeOccurrence,
233 onActiveRange: readSelection().onActiveRange,
@@ -219,47 +235,188 @@ export function useThreadFindHighlights(input: {
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) {
223 - let previousRanges: readonly ThreadFindRange[] | null = null;
224 - const rangesByRow = new Map<string, Range[]>();
356 const inactive = new Highlight();
357 const active = new Highlight();
227 - let previousActive: Range | null = null;
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);
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 - }
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 }
249 - if (previousActive && foldsHiding(previousActive, container).length === 0)
250 - inactive.add(previousActive);
251 - const selected =
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();
256 - if (selected) inactive.delete(selected);
257 - previousActive = selected;
258 - if (selected && revealFolded(selected, container)) {
399 + if (next) inactive.delete(next);
400 + if (next && revealFolded(next, container)) {
401 selection.onActiveRange(null);
402 } else {
261 - if (selected) active.add(selected);
262 - selection.onActiveRange(selected);
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 }
scripts/scenarios/thread-find-paint-bound.e2e.ts new
+75
@@ -0,0 +1,75 @@
1 +import { expect } from "e2e";
2 +
3 +import { test, WEB } from "./t3.ts";
4 +
5 +// The thread CLI takes at most 120,000 characters per message: 3,000 lines of ten "the".
6 +const SEEDED_MATCHES = 30_000;
7 +const LONG_MESSAGE = Array.from({ length: SEEDED_MATCHES / 10 }, () =>
8 + "the ".repeat(10).trim(),
9 +).join("\n");
10 +
11 +const findTotal = `(() => {
12 + const label = document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? "";
13 + const match = /^\\d+\\/(\\d+)$/.exec(label.trim());
14 + return match ? Number(match[1]) : 0;
15 +})()`;
16 +
17 +const paint = `(() => {
18 + const inactive = CSS.highlights.get("t3-thread-find");
19 + const active = CSS.highlights.get("t3-thread-find-active");
20 + let onScreen = 0;
21 + for (const highlight of [inactive, active])
22 + for (const range of highlight ?? []) {
23 + const rect = range.getBoundingClientRect();
24 + if (rect.height > 0 && rect.bottom >= 0 && rect.top <= innerHeight) onScreen++;
25 + }
26 + return {
27 + registered: (inactive?.size ?? 0) + (active?.size ?? 0),
28 + active: active?.size ?? 0,
29 + onScreen,
30 + };
31 +})()`;
32 +
33 +test(
34 + "Find paints only matches near the viewport of a message with 30,000 matches",
35 + WEB,
36 + async ({ t3, app, screen, browser }) => {
37 + const project = await t3.project("find-paint");
38 + const thread = await t3.thread({
39 + project,
40 + title: "Paint bound proof",
41 + messages: [LONG_MESSAGE],
42 + });
43 + await t3.open(thread);
44 + await expect(screen.getByText("first fixture turn complete", { exact: false })).toBeVisible({
45 + timeout: 120_000,
46 + });
47 +
48 + // The CLI's message folds to one line; find unfolds it to reach the first match.
49 + await browser.keyboard.press("Control+f");
50 + const find = screen.getByRole("searchbox", "Find in thread");
51 + await expect(find).toBeVisible();
52 + await find.fill("the");
53 + // The count is the server's: every match in the thread, whatever is painted.
54 + await expect
55 + .poll(() => browser.evaluate<number>(findTotal), { timeout: 60_000 })
56 + .toBeGreaterThanOrEqual(SEEDED_MATCHES);
57 + await expect
58 + .poll(async () => (await browser.evaluate<{ active: number }>(paint)).active, {
59 + timeout: 30_000,
60 + })
61 + .toBe(1);
62 +
63 + try {
64 + const painted = await browser.evaluate<{
65 + registered: number;
66 + active: number;
67 + onScreen: number;
68 + }>(paint);
69 + expect(painted.onScreen).toBeGreaterThan(0);
70 + expect(painted.registered).toBeLessThan(5_000);
71 + } finally {
72 + await app.screenshot("find-open-paint");
73 + }
74 + },
75 +);