Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ChangedFilesTree.tsx

400 lines14.7 KB

1import { type RunId } from "@t3tools/contracts";
2import { type MouseEvent, type ReactNode, memo, useLayoutEffect, useRef, useState } from "react";
3import { type TurnDiffFileChange } from "../../types";
4import {
5 buildTurnDiffTree,
6 summarizeTurnDiffStats,
7 type TurnDiffTreeNode,
8} from "../../lib/turnDiffTree";
9import { ChevronRightIcon, FileDiffIcon } from "lucide-react";
10import { ChevronsDownUp, ChevronsUpDown, Folder, FolderClosed } from "lucide";
11import { cn } from "~/lib/utils";
12import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
13import { PierreEntryIcon } from "./PierreEntryIcon";
14import { Button } from "../ui/button";
15import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
16import { MiddleTruncate } from "../ui/middle-truncate";
17import { MorphIcon } from "~/components/MorphIcon";
18import { observeResize } from "~/lib/observeResize";
19​
20const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
21const VIRTUALIZE_AFTER_ROWS = 250;
22const ROW_OVERSCAN = 8;
23​
24interface ChangedFileRow {
25 node: TurnDiffTreeNode;
26 depth: number;
28​
29export type ChangedFileContextMenuHandler = (filePath: string, event: MouseEvent) => void;
30​
31export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
32 runId: RunId;
33 files: ReadonlyArray<TurnDiffFileChange>;
34 allDirectoriesExpanded: boolean;
35 resolvedTheme: "light" | "dark";
36 onToggleAllDirectories: () => void;
37 onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
38 onFileContextMenu?: ChangedFileContextMenuHandler | undefined;
39}) {
40 const {
41 runId,
42 files,
43 allDirectoriesExpanded,
44 resolvedTheme,
45 onToggleAllDirectories,
46 onOpenTurnDiff,
47 onFileContextMenu,
48 } = props;
49 const summaryStat = summarizeTurnDiffStats(files);
50 const hasDirectories = files.some((file) => /[/\\]/.test(file.path));
51​
52 return (
53 <div
54 className="@container/changed-files mt-4 rounded-lg bg-secondary dark:bg-input/20"
55 data-changed-files-state="tree"
56 >
57 <div
58 data-changed-files-header=""
59 className="sticky top-2 z-10 flex items-center justify-between gap-2 rounded-t-lg bg-secondary px-3 py-2 dark:bg-background dark:bg-linear-to-b dark:from-input/20 dark:to-input/20"
60 >
61 <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-xs font-medium text-foreground">
62 <span>
63 {files.length} changed file{files.length === 1 ? "" : "s"}
64 </span>
65 {hasNonZeroStat(summaryStat) && (
66 <DiffStatLabel
67 additions={summaryStat.additions}
68 deletions={summaryStat.deletions}
69 layout="inline"
70 className="text-xs leading-4"
71 />
72 )}
73 </div>
74 <div className="flex shrink-0 items-center gap-1">
75 {hasDirectories && (
76 <Tooltip>
77 <TooltipTrigger
78 render={
79 <Button
80 type="button"
81 size="icon-xs"
82 variant="ghost-muted"
83 aria-label={
84 allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"
85 }
86 data-scroll-anchor-ignore
87 onClick={onToggleAllDirectories}
88 />
89 }
90 >
91 <MorphIcon
92 className="size-3"
93 icon={allDirectoriesExpanded ? ChevronsDownUp : ChevronsUpDown}
94 />
95 </TooltipTrigger>
96 <TooltipPopup side="top">
97 {allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
98 </TooltipPopup>
99 </Tooltip>
100 )}
101 <Tooltip>
102 <TooltipTrigger
103 render={
104 <Button
105 type="button"
106 size="xs"
107 variant="ghost-muted"
108 aria-label="Open diff"
109 onClick={() => onOpenTurnDiff(runId, files[0]?.path)}
110 />
111 }
112 >
113 <FileDiffIcon className="size-3" />
114 <span className="hidden @[24rem]/changed-files:inline">Open diff</span>
115 </TooltipTrigger>
116 <TooltipPopup side="top">Open the full diff</TooltipPopup>
117 </Tooltip>
118 </div>
119 </div>
120 <ChangedFilesTree
121 key={`${runId}:${allDirectoriesExpanded}`}
122 runId={runId}
123 files={files}
124 allDirectoriesExpanded={allDirectoriesExpanded}
125 resolvedTheme={resolvedTheme}
126 onOpenTurnDiff={onOpenTurnDiff}
127 onFileContextMenu={onFileContextMenu}
128 />
129 </div>
130 );
131});
132​
133export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
134 runId: RunId;
135 files: ReadonlyArray<TurnDiffFileChange>;
136 allDirectoriesExpanded: boolean;
137 resolvedTheme: "light" | "dark";
138 onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
139 onFileContextMenu?: ChangedFileContextMenuHandler | undefined;
140}) {
141 const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, runId, onFileContextMenu } =
142 props;
143 // Overrides apply only while their key matches the current one, so starting from no key is
144 // the same as starting with no overrides. That lets this hook run before the tree is built,
145 // and the compiler caches the tree on `files`.
146 const [directoryExpansionState, setDirectoryExpansionState] = useState<{
147 key: string | null;
148 overrides: Record<string, boolean>;
149 }>({ key: null, overrides: {} });
150 const treeNodes = buildTurnDiffTree(files);
151 const directoryPathsKey = collectDirectoryPaths(treeNodes).join("\u0000");
152 const hasDirectoryNodes = directoryPathsKey.length > 0;
153 const expansionStateKey = `${allDirectoriesExpanded ? "expanded" : "collapsed"}\u0000${directoryPathsKey}`;
154 const expandedDirectories =
155 directoryExpansionState.key === expansionStateKey
156 ? directoryExpansionState.overrides
157 : EMPTY_DIRECTORY_OVERRIDES;
158​
159 const toggleDirectory = (pathValue: string) => {
160 setDirectoryExpansionState((current) => {
161 const nextOverrides = current.key === expansionStateKey ? current.overrides : {};
162 return {
163 key: expansionStateKey,
164 overrides: {
165 ...nextOverrides,
166 [pathValue]: !(nextOverrides[pathValue] ?? allDirectoriesExpanded),
167 },
168 };
169 });
170 };
171​
172 const rows = collectExpandedRows(treeNodes, expandedDirectories, allDirectoriesExpanded);
173 const virtualized = rows.length > VIRTUALIZE_AFTER_ROWS;
174​
175 const renderRow = ({ node, depth }: ChangedFileRow) => {
176 const leftPadding = 8 + depth * 14;
177 if (node.kind === "directory") {
178 const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded;
179 return (
180 <button
181 key={`dir:${node.path}`}
182 type="button"
183 data-scroll-anchor-ignore
184 aria-expanded={isExpanded}
185 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"
186 style={{ paddingLeft: `${leftPadding}px` }}
187 onClick={() => toggleDirectory(node.path)}
188 >
189 <ChevronRightIcon
190 aria-hidden="true"
191 className={cn(
192 "size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
193 isExpanded && "rotate-90",
194 )}
195 />
196 <MorphIcon
197 className="size-3.5 shrink-0 text-muted-foreground/75"
198 icon={isExpanded ? Folder : FolderClosed}
199 />
200 <span className="truncate font-mono text-2xs text-muted-foreground/90 group-hover:text-foreground/90">
201 {node.name}
202 </span>
203 {hasNonZeroStat(node.stat) && (
204 <span className="ml-auto shrink-0 font-mono text-3xs tabular-nums">
205 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
206 </span>
207 )}
208 </button>
209 );
210 }
211​
212 return (
213 <button
214 key={`file:${node.path}`}
215 type="button"
216 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"
217 style={{ paddingLeft: `${leftPadding}px` }}
218 onClick={() => onOpenTurnDiff(runId, node.path)}
219 onContextMenu={
220 onFileContextMenu
221 ? (event) => {
222 event.preventDefault();
223 onFileContextMenu(node.path, event);
224 }
225 : undefined
226 }
227 >
228 {hasDirectoryNodes || depth > 0 ? (
229 <span aria-hidden="true" className="size-3.5 shrink-0" />
230 ) : null}
231 <PierreEntryIcon
232 pathValue={node.path}
233 kind="file"
234 theme={resolvedTheme}
235 className="size-3.5 text-muted-foreground/70"
236 />
237 <span className="flex min-w-0 font-mono text-xs text-foreground/85 group-hover:text-foreground">
238 <MiddleTruncate value={node.name} />
239 </span>
240 {node.stat && (
241 <span className="ml-auto shrink-0 font-mono text-3xs tabular-nums">
242 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
243 </span>
244 )}
245 </button>
246 );
247 };
248​
249 return <ChangedFilesRows rows={rows} renderRow={renderRow} virtualized={virtualized} />;
250});
251​
252function ChangedFilesRows({
253 rows,
254 renderRow,
255 virtualized,
256}: {
257 rows: ReadonlyArray<ChangedFileRow>;
258 renderRow: (row: ChangedFileRow) => ReactNode;
259 virtualized: boolean;
260}) {
261 const containerRef = useRef<HTMLDivElement>(null);
262 const rowSizeRef = useRef<HTMLDivElement>(null);
263 const [range, setRange] = useState({ start: 0, end: 40, rowHeight: 28 });
264 const [focusedPath, setFocusedPath] = useState<string | null>(null);
265​
266 useLayoutEffect(() => {
267 const container = containerRef.current;
268 const rowSize = rowSizeRef.current;
269 if (!virtualized || !container || !rowSize) return;
270​
271 // The card is inside a virtualized timeline item, so its own scrollTop is always zero.
272 // Observe its ancestors too: streaming text and timeline layout can move the card.
273 const ancestors: HTMLElement[] = [container, rowSize];
274 let scrollElement: HTMLElement | null = null;
275 for (let parent = container.parentElement; parent; parent = parent.parentElement) {
276 ancestors.push(parent);
277 if (/auto|scroll/.test(getComputedStyle(parent).overflowY)) {
278 scrollElement = parent;
279 break;
280 }
281 }
282​
283 const measure = () => {
284 const rowHeight = rowSize.getBoundingClientRect().height;
285 if (rowHeight <= 0) return;
286 const listTop = container.getBoundingClientRect().top;
287 const viewportTop = scrollElement
288 ? scrollElement.getBoundingClientRect().top + scrollElement.clientTop
289 : 0;
290 const viewportHeight = scrollElement?.clientHeight ?? document.documentElement.clientHeight;
291 const start = Math.max(
292 0,
293 Math.min(rows.length, Math.floor((viewportTop - listTop) / rowHeight) - ROW_OVERSCAN),
294 );
295 const end = Math.max(
296 start,
297 Math.min(
298 rows.length,
299 Math.ceil((viewportTop + viewportHeight - listTop) / rowHeight) + ROW_OVERSCAN,
300 ),
301 );
302 setRange((current) =>
303 current.start === start && current.end === end && current.rowHeight === rowHeight
304 ? current
305 : { start, end, rowHeight },
306 );
307 };
308 measure();
309 const scrollTarget = scrollElement ?? globalThis.window;
310 let frame = 0;
311 const onScroll = () => {
312 if (frame) return;
313 frame = requestAnimationFrame(() => {
314 frame = 0;
315 measure();
316 });
317 };
318 scrollTarget.addEventListener("scroll", onScroll, { passive: true });
319 globalThis.window.addEventListener("resize", onScroll);
320 const stopObserving = observeResize(ancestors, measure);
321 return () => {
322 scrollTarget.removeEventListener("scroll", onScroll);
323 globalThis.window.removeEventListener("resize", onScroll);
324 if (frame) cancelAnimationFrame(frame);
325 stopObserving();
326 };
327 }, [virtualized, rows.length]);
328​
329 const focusedIndex =
330 focusedPath === null ? -1 : rows.findIndex((row) => row.node.path === focusedPath);
331 const start = virtualized ? range.start : 0;
332 const end = virtualized ? Math.min(rows.length, range.end) : rows.length;
333 const indices = Array.from({ length: Math.max(0, end - start) }, (_, index) => start + index);
334 // Keep keyboard focus on its row when mouse scrolling moves it outside the render window.
335 if (focusedIndex >= 0 && focusedIndex < start) indices.unshift(focusedIndex);
336 if (focusedIndex >= end) indices.push(focusedIndex);
337 return (
338 <div className="p-2">
339 <div
340 ref={containerRef}
341 className="relative"
342 style={virtualized ? { height: rows.length * range.rowHeight } : undefined}
343 onFocusCapture={(event) => {
344 const row = event.target.closest<HTMLElement>("[data-changed-file-row]");
345 setFocusedPath(row?.dataset.changedFileRow ?? null);
346 }}
347 onBlurCapture={(event) => {
348 if (!event.currentTarget.contains(event.relatedTarget)) setFocusedPath(null);
349 }}
350 >
351 {virtualized && (
352 <div
353 ref={rowSizeRef}
354 aria-hidden="true"
355 className="pointer-events-none invisible absolute h-7"
356 />
357 )}
358 {indices.map((index) => {
359 const row = rows[index]!;
360 return (
361 <div
362 key={`${row.node.kind}:${row.node.path}`}
363 data-changed-file-row={row.node.path}
364 className={virtualized ? "absolute inset-x-0" : undefined}
365 style={virtualized ? { top: index * range.rowHeight } : undefined}
366 >
367 {renderRow(row)}
368 </div>
369 );
370 })}
371 </div>
372 </div>
373 );
375​
376function collectExpandedRows(
377 nodes: ReadonlyArray<TurnDiffTreeNode>,
378 overrides: Readonly<Record<string, boolean>>,
379 allDirectoriesExpanded: boolean,
380 depth = 0,
381 rows: ChangedFileRow[] = [],
382): ChangedFileRow[] {
383 for (const node of nodes) {
384 rows.push({ node, depth });
385 if (node.kind === "directory" && (overrides[node.path] ?? allDirectoriesExpanded)) {
386 collectExpandedRows(node.children, overrides, allDirectoriesExpanded, depth + 1, rows);
387 }
388 }
389 return rows;
391​
392function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {
393 const paths: string[] = [];
394 for (const node of nodes) {
395 if (node.kind !== "directory") continue;
396 paths.push(node.path);
397 paths.push(...collectDirectoryPaths(node.children));
398 }
399 return paths;