diff --git a/apps/web/src/components/chat/threadFindHighlights.browser.test.tsx b/apps/web/src/components/chat/threadFindHighlights.browser.test.tsx index a04507ef9c2c2..d7a3647d9c2cd 100644 --- a/apps/web/src/components/chat/threadFindHighlights.browser.test.tsx +++ b/apps/web/src/components/chat/threadFindHighlights.browser.test.tsx @@ -29,19 +29,148 @@ function Highlights(props: Parameters[0]) { return null; } -it("paints every match when one row has more matches than a call can take as arguments", async () => { +function mountTimeline(html: string) { + const container = document.createElement("div"); + container.style.cssText = "height: 200px; width: 300px; overflow: auto"; + container.innerHTML = html; + document.body.append(container); + return { container, [Symbol.dispose]: () => container.remove() }; +} + +const painted = () => [...(CSS.highlights.get("t3-thread-find") ?? [])] as Range[]; +const paintedIn = (element: Element) => + painted().filter((range) => element.contains(range.startContainer)).length; + +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 () => { const count = 200_000; const onActiveRange = vi.fn<(range: Range | null) => void>(); + using timeline = mountTimeline( + `
${"e x".repeat(count)}
`, + ); await using _screen = await render( , ); - expect(CSS.highlights.get("t3-thread-find")?.size).toBe(count - 1); + const visible = painted(); + expect(visible.length).toBeGreaterThan(0); + expect(visible.length).toBeLessThan(5_000); + expect(Math.max(...visible.map((range) => range.startOffset))).toBeLessThan(count); expect(CSS.highlights.get("t3-thread-find-active")?.size).toBe(1); expect(onActiveRange.mock.lastCall?.[0]?.startOffset).toBe((count - 1) * 3); + + timeline.container.scrollTop = timeline.container.scrollHeight; + await vi.waitFor(() => + expect(Math.max(...painted().map((range) => range.startOffset))).toBe((count - 2) * 3), + ); + expect(painted().length).toBeLessThan(5_000); +}); + +it("paints every match near the viewport when cells lay text out in a different order than the DOM", async () => { + using timeline = mountTimeline( + `
+ + +
${"e x ".repeat(5_000)}${"e x ".repeat(5_000)}
`, + ); + const cells = [...timeline.container.querySelectorAll("td")]; + const ranges = collectThreadFindRanges(timeline.container, "e"); + const key = (range: Range) => + `${cells.indexOf(range.startContainer.parentElement as HTMLTableCellElement)}:${range.startOffset}`; + const missing = () => { + const viewport = timeline.container.getBoundingClientRect(); + const [top, bottom] = [viewport.top - viewport.height, viewport.bottom + viewport.height]; + const shown = new Set(painted().map(key)); + return ranges.filter(({ range }) => { + const rect = range.getBoundingClientRect(); + return rect.bottom >= top && rect.top <= bottom && !shown.has(key(range)); + }).length; + }; + await using _screen = await render( + {}} + />, + ); + expect(missing()).toBe(0); + + timeline.container.scrollTop = 1_000; + await vi.waitFor(() => expect(missing()).toBe(0)); + expect(painted().length).toBeLessThan(ranges.length / 2); +}); + +it("skips a hidden block's matches without measuring each one", async () => { + using timeline = mountTimeline( + `
+
${"e x ".repeat(10_000)}

e

+
`, + ); + const visible = timeline.container.querySelector("p")!; + using measure = vi.spyOn(Range.prototype, "getBoundingClientRect"); + await using _screen = await render( + {}} + />, + ); + expect([painted().length, paintedIn(visible)]).toEqual([1, 1]); + expect(measure.mock.calls.length).toBeLessThan(100); +}); + +it("registers a row's matches only while it is near the viewport, and again after its text changes", async () => { + using timeline = mountTimeline( + `
e e e
+
+
e e
`, + ); + const [near, far] = [...timeline.container.querySelectorAll("[data-thread-find-text]")]; + const onActiveRange = vi.fn<(range: Range | null) => void>(); + await using _screen = await render( + , + ); + expect([paintedIn(near!), paintedIn(far!)]).toEqual([3, 0]); + expect(CSS.highlights.get("t3-thread-find-active")?.size).toBe(1); + expect(far!.contains(onActiveRange.mock.lastCall?.[0]?.startContainer ?? null)).toBe(true); + + near!.append(" e"); + await vi.waitFor(() => expect(paintedIn(near!)).toBe(4)); + + timeline.container.scrollTop = timeline.container.scrollHeight; + await vi.waitFor(() => expect([paintedIn(near!), paintedIn(far!)]).toEqual([0, 1])); +}); + +it("paints a row's matches once the hidden wrapper around it is revealed", async () => { + using timeline = mountTimeline( + ``, + ); + const text = timeline.container.querySelector("[data-thread-find-text]")!; + await using _screen = await render( + {}} + />, + ); + expect(paintedIn(text)).toBe(0); + + timeline.container.querySelector("#wrap")!.removeAttribute("hidden"); + await vi.waitFor(() => expect(paintedIn(text)).toBe(2)); }); diff --git a/apps/web/src/components/chat/threadFindHighlights.ts b/apps/web/src/components/chat/threadFindHighlights.ts index 54ee159e1b286..c8ce0b31b9c9e 100644 --- a/apps/web/src/components/chat/threadFindHighlights.ts +++ b/apps/web/src/components/chat/threadFindHighlights.ts @@ -2,6 +2,8 @@ import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { useEffect, useEffectEvent, useRef } from "react"; import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindText"; +import { observeResize } from "~/lib/observeResize"; + const THREAD_FIND_HIGHLIGHT_NAME = "t3-thread-find"; const THREAD_FIND_ACTIVE_HIGHLIGHT_NAME = "t3-thread-find-active"; @@ -160,9 +162,19 @@ export function useThreadFindHighlights(input: { } for (const row of cache.keys()) if (!rows.has(row)) cache.delete(row); rangesRef.current = ranges; - paint(ranges, readSelection()); + paint.update(cache, ranges, readSelection()); }; let frame: number | null = null; + let dirty = false; + const schedule = () => { + if (frame !== null) return; + frame = requestAnimationFrame(() => { + frame = null; + if (dirty) repaint(); + else paint.place(cache); + dirty = false; + }); + }; const observer = new MutationObserver((mutations) => { // Ignore timer and status mutations outside searchable text and folds. const relevant = mutations.filter(affectsSearchableText); @@ -174,12 +186,12 @@ export function useThreadFindHighlights(input: { : mutation.target.parentElement; const row = target?.closest("[data-timeline-row-id]"); if (row) cache.delete(row); + // A hidden wrapper around rows changes their runs, which are cached with their matches. + if (mutation.attributeName === "hidden" && target) + for (const cached of cache.keys()) if (target.contains(cached)) cache.delete(cached); } - if (frame !== null) return; - frame = requestAnimationFrame(() => { - frame = null; - repaint(); - }); + dirty = true; + schedule(); }); observer.observe(container, { subtree: true, @@ -195,10 +207,14 @@ export function useThreadFindHighlights(input: { "data-thread-find-ignore", ], }); + container.addEventListener("scroll", schedule, { passive: true }); + const stopResize = observeResize(container, schedule); // Revealing the first match can synchronously mount or recycle list rows. repaint(); return () => { observer.disconnect(); + stopResize(); + container.removeEventListener("scroll", schedule); if (frame !== null) cancelAnimationFrame(frame); cache.clear(); paintRef.current = null; @@ -211,7 +227,7 @@ export function useThreadFindHighlights(input: { // layout inputs, and repainting the active highlight for those is wasted work. // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- repaints the active CSS Highlight range when the selected match changes useEffect(() => { - paintRef.current?.(rangesRef.current, { + paintRef.current?.select({ activeRowId, activeOccurrence, onActiveRange: readSelection().onActiveRange, @@ -219,47 +235,188 @@ export function useThreadFindHighlights(input: { }, [activeOccurrence, activeRowId]); } +type ThreadFindSelection = Pick< + Parameters[0], + "activeRowId" | "activeOccurrence" | "onActiveRange" +>; + +interface TextRun { + readonly start: number; + end: number; + readonly box: Element; + readonly item: Node | null; + readonly ordered: boolean; + readonly hidden: boolean; +} + +const INLINE_DISPLAYS = new Set(["inline", "contents"]); +const textRunsByMatches = new WeakMap(); + +// Splits a row's matches into runs that each lie in one inline formatting context, +// where a later match is never higher on screen. Cells, flex and grid items, and +// inline blocks each start a run, since their text can sit beside earlier text. +function textRuns(row: Element, matches: readonly ThreadFindRange[]): readonly TextRun[] { + const cached = textRunsByMatches.get(matches); + if (cached) return cached; + const displays = new Map(); + const displayOf = (element: Element) => { + let display = displays.get(element); + if (display === undefined) { + display = getComputedStyle(element).display; + displays.set(element, display); + } + return display; + }; + const columns = new Map(); + const inColumns = (element: Element): boolean => { + let multicol = columns.get(element); + if (multicol === undefined) { + const style = getComputedStyle(element); + multicol = + style.columnCount !== "auto" || + style.columnWidth !== "auto" || + (element !== row && element.parentElement !== null && inColumns(element.parentElement)); + columns.set(element, multicol); + } + return multicol; + }; + const runs: TextRun[] = []; + let text: Node | null = null; + for (const [index, { range }] of matches.entries()) { + const last = runs.at(-1); + if (last && range.startContainer === text) { + last.end = index + 1; + continue; + } + const parent = range.startContainer.parentElement; + if (!parent) continue; + text = range.startContainer; + let box = parent; + while (box !== row && box.parentElement && INLINE_DISPLAYS.has(displayOf(box))) + box = box.parentElement; + // Text directly inside a flex or grid container is an anonymous item of its own. + const item = /flex|grid/.test(displayOf(box)) ? text : null; + const hidden = parent.closest("[hidden]") !== null; + if (last?.end === index && last.box === box && last.item === item && last.hidden === hidden) { + last.end = index + 1; + continue; + } + runs.push({ start: index, end: index + 1, box, item, hidden, ordered: !inColumns(box) }); + } + textRunsByMatches.set(matches, runs); + return runs; +} + +// Blink rebuilds every registered highlight Range on any DOM or style change, so +// only matches within a screen of the viewport are painted; the active one always is. +function matchesInZone( + row: Element, + matches: readonly ThreadFindRange[], + zone: { top: number; bottom: number }, + shown: Set, +): void { + const rowBox = row.getBoundingClientRect(); + if (matches.length === 0 || rowBox.bottom < zone.top || rowBox.top > zone.bottom) return; + const intersects = (rect: DOMRect) => rect.bottom >= zone.top && rect.top <= zone.bottom; + for (const run of textRuns(row, matches)) { + if (run.hidden) continue; + const boxes = run.box.getClientRects(); + if (boxes.length === 0 || ![...boxes].some(intersects)) continue; + if (!run.ordered) { + for (let index = run.start; index < run.end; index++) + if (intersects(matches[index]!.range.getBoundingClientRect())) + shown.add(matches[index]!.range); + continue; + } + const firstShown = (index: number, high: number): [number, DOMRect | null] => { + for (; index < high; index++) { + const rect = matches[index]!.range.getBoundingClientRect(); + if (rect.height > 0) return [index, rect]; + } + return [high, null]; + }; + const firstWhere = (isPast: (rect: DOMRect) => boolean) => { + let low = run.start; + let high = run.end; + while (low < high) { + const mid = (low + high) >>> 1; + const [probe, rect] = firstShown(mid, high); + if (!rect || isPast(rect)) high = mid; + else low = probe + 1; + } + return low; + }; + const end = firstWhere((rect) => rect.top > zone.bottom); + for (let index = firstWhere((rect) => rect.bottom >= zone.top); index < end; index++) + shown.add(matches[index]!.range); + } +} + function makeThreadFindHighlightPainter(container: HTMLElement) { - let previousRanges: readonly ThreadFindRange[] | null = null; - const rangesByRow = new Map(); const inactive = new Highlight(); const active = new Highlight(); - let previousActive: Range | null = null; + const zoned = new Set(); + const windows = new Map>(); + const rangesByRow = new Map(); + let selected: Range | null = null; CSS.highlights.set(THREAD_FIND_HIGHLIGHT_NAME, inactive); CSS.highlights.set(THREAD_FIND_ACTIVE_HIGHLIGHT_NAME, active); - return ( - ranges: readonly ThreadFindRange[], - selection: Pick< - Parameters[0], - "activeRowId" | "activeOccurrence" | "onActiveRange" - >, - ) => { - if (previousRanges !== ranges) { - previousRanges = ranges; - previousActive = null; - rangesByRow.clear(); - inactive.clear(); - for (const match of ranges) { - const row = rangesByRow.get(match.rowId) ?? []; - row[match.occurrence] = match.range; - rangesByRow.set(match.rowId, row); - if (foldsHiding(match.range, container).length === 0) inactive.add(match.range); - } + const show = (range: Range) => { + zoned.add(range); + if (range !== selected && foldsHiding(range, container).length === 0) inactive.add(range); + }; + const hide = (range: Range) => { + zoned.delete(range); + inactive.delete(range); + }; + const place = (rows: ReadonlyMap) => { + const viewport = container.getBoundingClientRect(); + const zone = { top: viewport.top - viewport.height, bottom: viewport.bottom + viewport.height }; + for (const [row, previous] of windows) { + if (rows.has(row)) continue; + for (const range of previous) hide(range); + windows.delete(row); + } + for (const [row, matches] of rows) { + const shown = new Set(); + matchesInZone(row, matches, zone, shown); + const previous = windows.get(row); + if (previous) for (const range of previous) if (!shown.has(range)) hide(range); + for (const range of shown) if (!previous?.has(range)) show(range); + windows.set(row, shown); } - if (previousActive && foldsHiding(previousActive, container).length === 0) - inactive.add(previousActive); - const selected = + }; + const select = (selection: ThreadFindSelection) => { + const next = selection.activeRowId === null ? null : (rangesByRow.get(selection.activeRowId)?.[selection.activeOccurrence] ?? null); + if (selected && selected !== next && zoned.has(selected)) { + if (foldsHiding(selected, container).length === 0) inactive.add(selected); + } + selected = next; active.clear(); - if (selected) inactive.delete(selected); - previousActive = selected; - if (selected && revealFolded(selected, container)) { + if (next) inactive.delete(next); + if (next && revealFolded(next, container)) { selection.onActiveRange(null); } else { - if (selected) active.add(selected); - selection.onActiveRange(selected); + if (next) active.add(next); + selection.onActiveRange(next); + } + }; + const update = ( + rows: ReadonlyMap, + ranges: readonly ThreadFindRange[], + selection: ThreadFindSelection, + ) => { + rangesByRow.clear(); + for (const match of ranges) { + const row = rangesByRow.get(match.rowId) ?? []; + row[match.occurrence] = match.range; + rangesByRow.set(match.rowId, row); } + place(rows); + select(selection); }; + return { update, place, select }; } diff --git a/scripts/scenarios/thread-find-paint-bound.e2e.ts b/scripts/scenarios/thread-find-paint-bound.e2e.ts new file mode 100644 index 0000000000000..9c0be796fcdca --- /dev/null +++ b/scripts/scenarios/thread-find-paint-bound.e2e.ts @@ -0,0 +1,75 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +// The thread CLI takes at most 120,000 characters per message: 3,000 lines of ten "the". +const SEEDED_MATCHES = 30_000; +const LONG_MESSAGE = Array.from({ length: SEEDED_MATCHES / 10 }, () => + "the ".repeat(10).trim(), +).join("\n"); + +const findTotal = `(() => { + const label = document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? ""; + const match = /^\\d+\\/(\\d+)$/.exec(label.trim()); + return match ? Number(match[1]) : 0; +})()`; + +const paint = `(() => { + const inactive = CSS.highlights.get("t3-thread-find"); + const active = CSS.highlights.get("t3-thread-find-active"); + let onScreen = 0; + for (const highlight of [inactive, active]) + for (const range of highlight ?? []) { + const rect = range.getBoundingClientRect(); + if (rect.height > 0 && rect.bottom >= 0 && rect.top <= innerHeight) onScreen++; + } + return { + registered: (inactive?.size ?? 0) + (active?.size ?? 0), + active: active?.size ?? 0, + onScreen, + }; +})()`; + +test( + "Find paints only matches near the viewport of a message with 30,000 matches", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("find-paint"); + const thread = await t3.thread({ + project, + title: "Paint bound proof", + messages: [LONG_MESSAGE], + }); + await t3.open(thread); + await expect(screen.getByText("first fixture turn complete", { exact: false })).toBeVisible({ + timeout: 120_000, + }); + + // The CLI's message folds to one line; find unfolds it to reach the first match. + await browser.keyboard.press("Control+f"); + const find = screen.getByRole("searchbox", "Find in thread"); + await expect(find).toBeVisible(); + await find.fill("the"); + // The count is the server's: every match in the thread, whatever is painted. + await expect + .poll(() => browser.evaluate(findTotal), { timeout: 60_000 }) + .toBeGreaterThanOrEqual(SEEDED_MATCHES); + await expect + .poll(async () => (await browser.evaluate<{ active: number }>(paint)).active, { + timeout: 30_000, + }) + .toBe(1); + + try { + const painted = await browser.evaluate<{ + registered: number; + active: number; + onScreen: number; + }>(paint); + expect(painted.onScreen).toBeGreaterThan(0); + expect(painted.registered).toBeLessThan(5_000); + } finally { + await app.screenshot("find-open-paint"); + } + }, +);