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

ChangedFilesTree.tsx

419 lines15.7 KB

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