TypeScript
perf(web): virtualize large changed-file trees (#21482)
Yash Singhf36dadb782b8
diff --git a/apps/web/src/components/chat/ChangedFilesTree.browser.test.tsx b/apps/web/src/components/chat/ChangedFilesTree.browser.test.tsxindex 2b84755ece9..800e9e9cc78 100644--- a/apps/web/src/components/chat/ChangedFilesTree.browser.test.tsx+++ b/apps/web/src/components/chat/ChangedFilesTree.browser.test.tsx@@ -1,5 +1,8 @@+import "~/index.css";+import { RunId } from "@t3tools/contracts";-import { act, type ReactNode } from "react";+import { LegendList } from "@legendapp/list/react";+import { act, type ReactNode, useState } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";@@ -40,6 +43,14 @@ function buttonWithText(label: string) {return button!;}+async function scrollTo(element: HTMLElement, top: number) {+ await act(async () => {+ element.scrollTop = top;+ element.dispatchEvent(new Event("scroll"));+ await new Promise(requestAnimationFrame);+ });+}+describe("ChangedFilesCard", () => {it("summarizes a single file with a singular label", async () => {await render(@@ -92,6 +103,187 @@ describe("ChangedFilesCard", () => {});describe("ChangedFilesTree", () => {+ const manyFiles = Array.from({ length: 16_185 }, (_, index) =>+ file(`src/file-${index.toString().padStart(5, "0")}.ts`),+ );++ it("virtualizes above 250 expanded files and disables it when folders collapse below that count", async () => {+ await render(+ <div style={{ height: 280, overflowY: "auto" }}>+ <ChangedFilesTree+ runId={RunId.make("run-1")}+ files={[...manyFiles.slice(0, 250), file("extra/overflow.ts")]}+ allDirectoriesExpanded={false}+ resolvedTheme="light"+ onOpenTurnDiff={() => {}}+ />+ </div>,+ );+ expect(container.querySelectorAll("button").length).toBe(2);++ await act(async () => buttonWithText("src").click());+ expect(container.querySelectorAll("button").length).toBe(252);+ expect(text()).toContain("file-00249.ts");+ expect(text()).not.toContain("overflow.ts");++ await act(async () => buttonWithText("extra").click());+ expect(container.querySelectorAll("button").length).toBeLessThan(60);+ expect(text()).not.toContain("file-00249.ts");++ await act(async () => buttonWithText("extra").click());+ expect(container.querySelectorAll("button").length).toBe(252);+ expect(text()).toContain("file-00249.ts");+ expect(text()).not.toContain("overflow.ts");+ });++ it("keeps expand-all bounded and opens files after scrolling the surrounding viewport", async () => {+ const onOpenTurnDiff = vi.fn();+ const onFileContextMenu = vi.fn();+ function Card() {+ const [expanded, setExpanded] = useState(false);+ return (+ <ChangedFilesCard+ runId={RunId.make("run-1")}+ files={manyFiles}+ allDirectoriesExpanded={expanded}+ resolvedTheme="light"+ onToggleAllDirectories={() => setExpanded(!expanded)}+ onOpenTurnDiff={onOpenTurnDiff}+ onFileContextMenu={onFileContextMenu}+ />+ );+ }+ await render(+ <div style={{ height: 280, overflowY: "auto" }}>+ <div style={{ height: 420 }} />+ <Card />+ </div>,+ );+ const viewport = container.firstElementChild as HTMLElement;+ await scrollTo(viewport, 420);+ const collapsedHeight = viewport.scrollHeight;+ await act(async () =>+ container.querySelector<HTMLButtonElement>('[aria-label="Expand all folders"]')!.click(),+ );++ expect(container.querySelectorAll("button").length).toBeLessThan(60);+ expect(viewport.scrollHeight).toBeGreaterThan(collapsedHeight + 400_000);+ expect(text()).toContain("file-00000.ts");+ expect(text()).not.toContain("file-08000.ts");++ await scrollTo(viewport, 420 + 8_001 * 28);+ expect(text()).toContain("file-08000.ts");+ expect(text()).not.toContain("file-00000.ts");+ expect(container.querySelectorAll("button").length).toBeLessThan(60);++ await scrollTo(viewport, viewport.scrollHeight);+ expect(text()).toContain("file-16184.ts");+ await act(async () => buttonWithText("file-16184.ts").click());+ expect(onOpenTurnDiff).toHaveBeenCalledWith(RunId.make("run-1"), "src/file-16184.ts");+ await act(async () =>+ buttonWithText("file-16184.ts").dispatchEvent(+ new MouseEvent("contextmenu", { bubbles: true, cancelable: true }),+ ),+ );+ expect(onFileContextMenu).toHaveBeenCalledWith("src/file-16184.ts", expect.anything());++ await act(async () =>+ container.querySelector<HTMLButtonElement>('[aria-label="Collapse all folders"]')!.click(),+ );+ expect(viewport.scrollHeight).toBe(collapsedHeight);+ expect(text()).not.toContain("file-16184.ts");+ });++ it("virtualizes a single expanded folder inside a LegendList timeline item", async () => {+ await render(+ <LegendList+ data={["message", "files"]}+ keyExtractor={(item) => item}+ estimatedItemSize={280}+ style={{ height: 280 }}+ renderItem={({ item }) =>+ item === "message" ? (+ <div style={{ height: 420 }}>Earlier message</div>+ ) : (+ <ChangedFilesTree+ runId={RunId.make("run-1")}+ files={manyFiles}+ allDirectoriesExpanded={false}+ resolvedTheme="light"+ onOpenTurnDiff={() => {}}+ />+ )+ }+ />,+ );+ const viewport = container.firstElementChild as HTMLElement;+ await scrollTo(viewport, 420);+ await act(async () => buttonWithText("src").click());+ expect(container.querySelectorAll("button").length).toBeLessThan(60);++ await scrollTo(viewport, 420 + 8_001 * 28);+ expect(text()).toContain("file-08000.ts");+ expect(container.querySelectorAll("button").length).toBeLessThan(60);++ await scrollTo(viewport, viewport.scrollHeight);+ expect(text()).toContain("file-16184.ts");+ await scrollTo(viewport, 420);+ await act(async () => buttonWithText("src").click());+ expect(text()).not.toContain("file-00000.ts");+ expect(container.querySelectorAll("button").length).toBe(1);+ });++ it("keeps a focused file mounted when scrolling it out of view", async () => {+ await render(+ <div style={{ height: 280, overflowY: "auto" }}>+ <ChangedFilesTree+ runId={RunId.make("run-1")}+ files={manyFiles}+ allDirectoriesExpanded+ resolvedTheme="light"+ onOpenTurnDiff={() => {}}+ />+ </div>,+ );+ const viewport = container.firstElementChild as HTMLElement;+ const focusedFile = buttonWithText("file-00000.ts");+ await act(async () => focusedFile.focus());+ await scrollTo(viewport, 8_001 * 28);+ expect(text()).toContain("file-08000.ts");+ expect(document.activeElement).toBe(focusedFile);+ expect(container.querySelectorAll("button").length).toBeLessThan(60);++ await act(async () => focusedFile.blur());+ expect(text()).not.toContain("file-00000.ts");+ });++ it("remeasures the visible rows when the viewport or preceding content resizes", async () => {+ const content = (height: number, precedingHeight: number) => (+ <div style={{ height, overflowY: "auto" }}>+ <div>+ <div style={{ height: precedingHeight }} />+ <ChangedFilesTree+ runId={RunId.make("run-1")}+ files={manyFiles}+ allDirectoriesExpanded+ resolvedTheme="light"+ onOpenTurnDiff={() => {}}+ />+ </div>+ </div>+ );+ await render(content(140, 0));+ const viewport = container.firstElementChild as HTMLElement;+ await scrollTo(viewport, 8_001 * 28);+ const beforeResize = container.querySelectorAll("button").length;+ await render(content(560, 560));+ await expect+ .poll(() => container.querySelectorAll("button").length)+ .toBeGreaterThan(beforeResize);+ expect(text()).toContain("file-07980.ts");+ expect(container.querySelectorAll("button").length).toBeLessThan(60);+ });+const cases = [{name: "a compacted single-chain directory",diff --git a/apps/web/src/components/chat/ChangedFilesTree.tsx b/apps/web/src/components/chat/ChangedFilesTree.tsxindex 99f55f460e0..4550f9bf8e6 100644--- a/apps/web/src/components/chat/ChangedFilesTree.tsx+++ b/apps/web/src/components/chat/ChangedFilesTree.tsx@@ -1,5 +1,5 @@import { type RunId } from "@t3tools/contracts";-import { type MouseEvent, memo, useState } from "react";+import { type MouseEvent, type ReactNode, memo, useLayoutEffect, useRef, useState } from "react";import { type TurnDiffFileChange } from "../../types";import {buildTurnDiffTree,@@ -15,8 +15,16 @@ import { Button } from "../ui/button";import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";import { MiddleTruncate } from "../ui/middle-truncate";import { MorphIcon } from "~/components/MorphIcon";+import { observeResize } from "~/lib/observeResize";const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};+const VIRTUALIZE_AFTER_FILES = 250;+const ROW_OVERSCAN = 8;++interface ChangedFileRow {+ node: TurnDiffTreeNode;+ depth: number;+}export type ChangedFileContextMenuHandler = (filePath: string, event: MouseEvent) => void;@@ -161,44 +169,45 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {});};- const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {+ const rows = collectExpandedRows(treeNodes, expandedDirectories, allDirectoriesExpanded);+ const virtualized =+ rows.reduce((count, row) => count + (row.node.kind === "file" ? 1 : 0), 0) >+ VIRTUALIZE_AFTER_FILES;++ const renderRow = ({ node, depth }: ChangedFileRow) => {const leftPadding = 8 + depth * 14;if (node.kind === "directory") {const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded;return (- <div key={`dir:${node.path}`}>- <button- type="button"- data-scroll-anchor-ignore- aria-expanded={isExpanded}- className="group flex w-full items-center gap-2 rounded-md py-1.5 pr-2 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"- style={{ paddingLeft: `${leftPadding}px` }}- onClick={() => toggleDirectory(node.path)}- >- <ChevronRightIcon- aria-hidden="true"- className={cn(- "size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",- isExpanded && "rotate-90",- )}- />- <MorphIcon- className="size-3.5 shrink-0 text-muted-foreground/75"- icon={isExpanded ? Folder : FolderClosed}- />- <span className="truncate font-mono text-2xs text-muted-foreground/90 group-hover:text-foreground/90">- {node.name}- </span>- {hasNonZeroStat(node.stat) && (- <span className="ml-auto shrink-0 font-mono text-3xs tabular-nums">- <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />- </span>+ <button+ key={`dir:${node.path}`}+ type="button"+ data-scroll-anchor-ignore+ aria-expanded={isExpanded}+ className="group flex h-7 w-full items-center gap-2 rounded-md py-1.5 pr-2 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"+ style={{ paddingLeft: `${leftPadding}px` }}+ onClick={() => toggleDirectory(node.path)}+ >+ <ChevronRightIcon+ aria-hidden="true"+ className={cn(+ "size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",+ isExpanded && "rotate-90",)}- </button>- {isExpanded && (- <div>{node.children.map((childNode) => renderTreeNode(childNode, depth + 1))}</div>+ />+ <MorphIcon+ className="size-3.5 shrink-0 text-muted-foreground/75"+ icon={isExpanded ? Folder : FolderClosed}+ />+ <span className="truncate font-mono text-2xs text-muted-foreground/90 group-hover:text-foreground/90">+ {node.name}+ </span>+ {hasNonZeroStat(node.stat) && (+ <span className="ml-auto shrink-0 font-mono text-3xs tabular-nums">+ <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />+ </span>)}- </div>+ </button>);}@@ -206,7 +215,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {<buttonkey={`file:${node.path}`}type="button"- className="group flex w-full items-center gap-2 rounded-md py-1.5 pr-2 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"+ className="group flex h-7 w-full items-center gap-2 rounded-md py-1.5 pr-2 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"style={{ paddingLeft: `${leftPadding}px` }}onClick={() => onOpenTurnDiff(runId, node.path)}onContextMenu={@@ -239,9 +248,149 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {);};- return <div className="p-2">{treeNodes.map((node) => renderTreeNode(node, 0))}</div>;+ return <ChangedFilesRows rows={rows} renderRow={renderRow} virtualized={virtualized} />;});+function ChangedFilesRows({+ rows,+ renderRow,+ virtualized,+}: {+ rows: ReadonlyArray<ChangedFileRow>;+ renderRow: (row: ChangedFileRow) => ReactNode;+ virtualized: boolean;+}) {+ const containerRef = useRef<HTMLDivElement>(null);+ const rowSizeRef = useRef<HTMLDivElement>(null);+ const [range, setRange] = useState({ start: 0, end: 40, rowHeight: 28 });+ const [focusedPath, setFocusedPath] = useState<string | null>(null);++ useLayoutEffect(() => {+ const container = containerRef.current;+ const rowSize = rowSizeRef.current;+ if (!virtualized || !container || !rowSize) return;++ // The card is inside a virtualized timeline item, so its own scrollTop is always zero.+ // Observe its ancestors too: streaming text and timeline layout can move the card.+ const ancestors: HTMLElement[] = [container, rowSize];+ let scrollElement: HTMLElement | null = null;+ for (let parent = container.parentElement; parent; parent = parent.parentElement) {+ ancestors.push(parent);+ if (/auto|scroll/.test(getComputedStyle(parent).overflowY)) {+ scrollElement = parent;+ break;+ }+ }++ const measure = () => {+ const rowHeight = rowSize.getBoundingClientRect().height;+ if (rowHeight <= 0) return;+ const listTop = container.getBoundingClientRect().top;+ const viewportTop = scrollElement+ ? scrollElement.getBoundingClientRect().top + scrollElement.clientTop+ : 0;+ const viewportHeight = scrollElement?.clientHeight ?? document.documentElement.clientHeight;+ const start = Math.max(+ 0,+ Math.min(rows.length, Math.floor((viewportTop - listTop) / rowHeight) - ROW_OVERSCAN),+ );+ const end = Math.max(+ start,+ Math.min(+ rows.length,+ Math.ceil((viewportTop + viewportHeight - listTop) / rowHeight) + ROW_OVERSCAN,+ ),+ );+ setRange((current) =>+ current.start === start && current.end === end && current.rowHeight === rowHeight+ ? current+ : { start, end, rowHeight },+ );+ };+ measure();+ const scrollTarget = scrollElement ?? globalThis.window;+ let frame = 0;+ const onScroll = () => {+ if (frame) return;+ frame = requestAnimationFrame(() => {+ frame = 0;+ measure();+ });+ };+ scrollTarget.addEventListener("scroll", onScroll, { passive: true });+ globalThis.window.addEventListener("resize", onScroll);+ const stopObserving = observeResize(ancestors, measure);+ return () => {+ scrollTarget.removeEventListener("scroll", onScroll);+ globalThis.window.removeEventListener("resize", onScroll);+ if (frame) cancelAnimationFrame(frame);+ stopObserving();+ };+ }, [virtualized, rows.length]);++ const focusedIndex =+ focusedPath === null ? -1 : rows.findIndex((row) => row.node.path === focusedPath);+ const start = virtualized ? range.start : 0;+ const end = virtualized ? Math.min(rows.length, range.end) : rows.length;+ const indices = Array.from({ length: Math.max(0, end - start) }, (_, index) => start + index);+ // Keep keyboard focus on its row when mouse scrolling moves it outside the render window.+ if (focusedIndex >= 0 && focusedIndex < start) indices.unshift(focusedIndex);+ if (focusedIndex >= end) indices.push(focusedIndex);+ return (+ <div className="p-2">+ <div+ ref={containerRef}+ className="relative"+ style={virtualized ? { height: rows.length * range.rowHeight } : undefined}+ onFocusCapture={(event) => {+ const row = event.target.closest<HTMLElement>("[data-changed-file-row]");+ setFocusedPath(row?.dataset.changedFileRow ?? null);+ }}+ onBlurCapture={(event) => {+ if (!event.currentTarget.contains(event.relatedTarget)) setFocusedPath(null);+ }}+ >+ {virtualized && (+ <div+ ref={rowSizeRef}+ aria-hidden="true"+ className="pointer-events-none invisible absolute h-7"+ />+ )}+ {indices.map((index) => {+ const row = rows[index]!;+ return (+ <div+ key={`${row.node.kind}:${row.node.path}`}+ data-changed-file-row={row.node.path}+ className={virtualized ? "absolute inset-x-0" : undefined}+ style={virtualized ? { top: index * range.rowHeight } : undefined}+ >+ {renderRow(row)}+ </div>+ );+ })}+ </div>+ </div>+ );+}++function collectExpandedRows(+ nodes: ReadonlyArray<TurnDiffTreeNode>,+ overrides: Readonly<Record<string, boolean>>,+ allDirectoriesExpanded: boolean,+ depth = 0,+ rows: ChangedFileRow[] = [],+): ChangedFileRow[] {+ for (const node of nodes) {+ rows.push({ node, depth });+ if (node.kind === "directory" && (overrides[node.path] ?? allDirectoriesExpanded)) {+ collectExpandedRows(node.children, overrides, allDirectoriesExpanded, depth + 1, rows);+ }+ }+ return rows;+}+function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {const paths: string[] = [];for (const node of nodes) {