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

ChangedFilesTree.tsx

411 lines15.3 KB

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