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

ChangedFilesTree.tsx

398 lines14.6 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​
133const 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 // Place state before tree derivation to preserve its compiler cache.
144 const [directoryExpansionState, setDirectoryExpansionState] = useState<{
145 key: string | null;
146 overrides: Record<string, boolean>;
147 }>({ key: null, overrides: {} });
148 const treeNodes = buildTurnDiffTree(files);
149 const directoryPathsKey = collectDirectoryPaths(treeNodes).join("\u0000");
150 const hasDirectoryNodes = directoryPathsKey.length > 0;
151 const expansionStateKey = `${allDirectoriesExpanded ? "expanded" : "collapsed"}\u0000${directoryPathsKey}`;
152 const expandedDirectories =
153 directoryExpansionState.key === expansionStateKey
154 ? directoryExpansionState.overrides
155 : EMPTY_DIRECTORY_OVERRIDES;
156​
157 const toggleDirectory = (pathValue: string) => {
158 setDirectoryExpansionState((current) => {
159 const nextOverrides = current.key === expansionStateKey ? current.overrides : {};
160 return {
161 key: expansionStateKey,
162 overrides: {
163 ...nextOverrides,
164 [pathValue]: !(nextOverrides[pathValue] ?? allDirectoriesExpanded),
165 },
166 };
167 });
168 };
169​
170 const rows = collectExpandedRows(treeNodes, expandedDirectories, allDirectoriesExpanded);
171 const virtualized = rows.length > VIRTUALIZE_AFTER_ROWS;
172​
173 const renderRow = ({ node, depth }: ChangedFileRow) => {
174 const leftPadding = 8 + depth * 14;
175 if (node.kind === "directory") {
176 const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded;
177 return (
178 <button
179 key={`dir:${node.path}`}
180 type="button"
181 data-scroll-anchor-ignore
182 aria-expanded={isExpanded}
183 className="group flex h-7 w-full cursor-pointer 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"
184 style={{ paddingLeft: `${leftPadding}px` }}
185 onClick={() => toggleDirectory(node.path)}
186 >
187 <ChevronRightIcon
188 aria-hidden="true"
189 className={cn(
190 "size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
191 isExpanded && "rotate-90",
192 )}
193 />
194 <MorphIcon
195 className="size-3.5 shrink-0 text-muted-foreground/75"
196 icon={isExpanded ? Folder : FolderClosed}
197 />
198 <span className="truncate font-mono text-2xs text-muted-foreground/90 group-hover:text-foreground/90">
199 {node.name}
200 </span>
201 {hasNonZeroStat(node.stat) && (
202 <span className="ml-auto shrink-0 font-mono text-3xs tabular-nums">
203 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
204 </span>
205 )}
206 </button>
207 );
208 }
209​
210 return (
211 <button
212 key={`file:${node.path}`}
213 type="button"
214 className="group flex h-7 w-full cursor-pointer 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"
215 style={{ paddingLeft: `${leftPadding}px` }}
216 onClick={() => onOpenTurnDiff(runId, node.path)}
217 onContextMenu={
218 onFileContextMenu
219 ? (event) => {
220 event.preventDefault();
221 onFileContextMenu(node.path, event);
222 }
223 : undefined
224 }
225 >
226 {hasDirectoryNodes || depth > 0 ? (
227 <span aria-hidden="true" className="size-3.5 shrink-0" />
228 ) : null}
229 <PierreEntryIcon
230 pathValue={node.path}
231 kind="file"
232 theme={resolvedTheme}
233 className="size-3.5 text-muted-foreground/70"
234 />
235 <span className="flex min-w-0 font-mono text-xs text-foreground/85 group-hover:text-foreground">
236 <MiddleTruncate value={node.name} />
237 </span>
238 {node.stat && (
239 <span className="ml-auto shrink-0 font-mono text-3xs tabular-nums">
240 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
241 </span>
242 )}
243 </button>
244 );
245 };
246​
247 return <ChangedFilesRows rows={rows} renderRow={renderRow} virtualized={virtualized} />;
248});
249​
250function ChangedFilesRows({
251 rows,
252 renderRow,
253 virtualized,
254}: {
255 rows: ReadonlyArray<ChangedFileRow>;
256 renderRow: (row: ChangedFileRow) => ReactNode;
257 virtualized: boolean;
258}) {
259 const containerRef = useRef<HTMLDivElement>(null);
260 const rowSizeRef = useRef<HTMLDivElement>(null);
261 const [range, setRange] = useState({ start: 0, end: 40, rowHeight: 28 });
262 const [focusedPath, setFocusedPath] = useState<string | null>(null);
263​
264 useLayoutEffect(() => {
265 const container = containerRef.current;
266 const rowSize = rowSizeRef.current;
267 if (!virtualized || !container || !rowSize) return;
268​
269 // The card is inside a virtualized timeline item, so its own scrollTop is always zero.
270 // Observe its ancestors too: streaming text and timeline layout can move the card.
271 const ancestors: HTMLElement[] = [container, rowSize];
272 let scrollElement: HTMLElement | null = null;
273 for (let parent = container.parentElement; parent; parent = parent.parentElement) {
274 ancestors.push(parent);
275 if (/auto|scroll/.test(getComputedStyle(parent).overflowY)) {
276 scrollElement = parent;
277 break;
278 }
279 }
280​
281 const measure = () => {
282 const rowHeight = rowSize.getBoundingClientRect().height;
283 if (rowHeight <= 0) return;
284 const listTop = container.getBoundingClientRect().top;
285 const viewportTop = scrollElement
286 ? scrollElement.getBoundingClientRect().top + scrollElement.clientTop
287 : 0;
288 const viewportHeight = scrollElement?.clientHeight ?? document.documentElement.clientHeight;
289 const start = Math.max(
290 0,
291 Math.min(rows.length, Math.floor((viewportTop - listTop) / rowHeight) - ROW_OVERSCAN),
292 );
293 const end = Math.max(
294 start,
295 Math.min(
296 rows.length,
297 Math.ceil((viewportTop + viewportHeight - listTop) / rowHeight) + ROW_OVERSCAN,
298 ),
299 );
300 setRange((current) =>
301 current.start === start && current.end === end && current.rowHeight === rowHeight
302 ? current
303 : { start, end, rowHeight },
304 );
305 };
306 measure();
307 const scrollTarget = scrollElement ?? globalThis.window;
308 let frame = 0;
309 const onScroll = () => {
310 if (frame) return;
311 frame = requestAnimationFrame(() => {
312 frame = 0;
313 measure();
314 });
315 };
316 scrollTarget.addEventListener("scroll", onScroll, { passive: true });
317 globalThis.window.addEventListener("resize", onScroll);
318 const stopObserving = observeResize(ancestors, measure);
319 return () => {
320 scrollTarget.removeEventListener("scroll", onScroll);
321 globalThis.window.removeEventListener("resize", onScroll);
322 if (frame) cancelAnimationFrame(frame);
323 stopObserving();
324 };
325 }, [virtualized, rows.length]);
326​
327 const focusedIndex =
328 focusedPath === null ? -1 : rows.findIndex((row) => row.node.path === focusedPath);
329 const start = virtualized ? range.start : 0;
330 const end = virtualized ? Math.min(rows.length, range.end) : rows.length;
331 const indices = Array.from({ length: Math.max(0, end - start) }, (_, index) => start + index);
332 // Keep keyboard focus on its row when mouse scrolling moves it outside the render window.
333 if (focusedIndex >= 0 && focusedIndex < start) indices.unshift(focusedIndex);
334 if (focusedIndex >= end) indices.push(focusedIndex);
335 return (
336 <div className="p-2">
337 <div
338 ref={containerRef}
339 className="relative"
340 style={virtualized ? { height: rows.length * range.rowHeight } : undefined}
341 onFocusCapture={(event) => {
342 const row = event.target.closest<HTMLElement>("[data-changed-file-row]");
343 setFocusedPath(row?.dataset.changedFileRow ?? null);
344 }}
345 onBlurCapture={(event) => {
346 if (!event.currentTarget.contains(event.relatedTarget)) setFocusedPath(null);
347 }}
348 >
349 {virtualized && (
350 <div
351 ref={rowSizeRef}
352 aria-hidden="true"
353 className="pointer-events-none invisible absolute h-7"
354 />
355 )}
356 {indices.map((index) => {
357 const row = rows[index]!;
358 return (
359 <div
360 key={`${row.node.kind}:${row.node.path}`}
361 data-changed-file-row={row.node.path}
362 className={virtualized ? "absolute inset-x-0" : undefined}
363 style={virtualized ? { top: index * range.rowHeight } : undefined}
364 >
365 {renderRow(row)}
366 </div>
367 );
368 })}
369 </div>
370 </div>
371 );
373​
374function collectExpandedRows(
375 nodes: ReadonlyArray<TurnDiffTreeNode>,
376 overrides: Readonly<Record<string, boolean>>,
377 allDirectoriesExpanded: boolean,
378 depth = 0,
379 rows: ChangedFileRow[] = [],
380): ChangedFileRow[] {
381 for (const node of nodes) {
382 rows.push({ node, depth });
383 if (node.kind === "directory" && (overrides[node.path] ?? allDirectoriesExpanded)) {
384 collectExpandedRows(node.children, overrides, allDirectoriesExpanded, depth + 1, rows);
385 }
386 }
387 return rows;
389​
390function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {
391 const paths: string[] = [];
392 for (const node of nodes) {
393 if (node.kind !== "directory") continue;
394 paths.push(node.path);
395 paths.push(...collectDirectoryPaths(node.children));
396 }
397 return paths;