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

ChangedFilesTree.tsx

266 lines9.7 KB

1import { type RunId } from "@t3tools/contracts";
2import { type MouseEvent, memo, useCallback, useMemo, useState } from "react";
3import { type TurnDiffFileChange } from "../../types";
4import {
5 buildTurnDiffTree,
6 summarizeTurnDiffStats,
7 type TurnDiffTreeNode,
8} from "../../lib/turnDiffTree";
9import {
10 ChevronsDownUpIcon,
11 ChevronsUpDownIcon,
12 ChevronRightIcon,
13 FileDiffIcon,
14 FolderIcon,
15 FolderClosedIcon,
16} from "lucide-react";
17import { cn } from "~/lib/utils";
18import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
19import { PierreEntryIcon } from "./PierreEntryIcon";
20import { Button } from "../ui/button";
21import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
22​
23const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
24​
25/** Opens the OS-level context menu for a changed file (reveal in file manager, open in editor). */
26export type ChangedFileContextMenuHandler = (filePath: string, event: MouseEvent) => void;
27​
28export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
29 runId: RunId;
30 files: ReadonlyArray<TurnDiffFileChange>;
31 allDirectoriesExpanded: boolean;
32 resolvedTheme: "light" | "dark";
33 onToggleAllDirectories: () => void;
34 onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
35 onFileContextMenu?: ChangedFileContextMenuHandler | undefined;
36}) {
37 const {
38 runId,
39 files,
40 allDirectoriesExpanded,
41 resolvedTheme,
42 onToggleAllDirectories,
43 onOpenTurnDiff,
44 onFileContextMenu,
45 } = props;
46 const summaryStat = useMemo(() => summarizeTurnDiffStats(files), [files]);
47 const hasDirectories = files.some((file) => /[/\\]/.test(file.path));
48​
49 return (
50 <div
51 className="@container/changed-files mt-4 rounded-lg bg-secondary dark:bg-input/20"
52 data-changed-files-state="tree"
53 >
54 <div
55 data-changed-files-header=""
56 className="sticky top-2 z-10 flex items-center justify-between gap-2 rounded-t-lg bg-secondary px-3 py-2 dark:bg-[color-mix(in_srgb,var(--input)_20%,var(--background))]"
57 >
58 <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-xs font-medium text-foreground">
59 <span>
60 {files.length} changed file{files.length === 1 ? "" : "s"}
61 </span>
62 {hasNonZeroStat(summaryStat) && (
63 <DiffStatLabel
64 additions={summaryStat.additions}
65 deletions={summaryStat.deletions}
66 layout="inline"
67 className="text-xs leading-4"
68 />
69 )}
70 </div>
71 <div className="flex shrink-0 items-center gap-1">
72 {hasDirectories && (
73 <Tooltip>
74 <TooltipTrigger
75 render={
76 <Button
77 type="button"
78 size="icon-xs"
79 variant="ghost-muted"
80 aria-label={
81 allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"
82 }
83 data-scroll-anchor-ignore
84 onClick={onToggleAllDirectories}
85 />
86 }
87 >
88 {allDirectoriesExpanded ? (
89 <ChevronsDownUpIcon className="size-3" />
90 ) : (
91 <ChevronsUpDownIcon className="size-3" />
92 )}
93 </TooltipTrigger>
94 <TooltipPopup side="top">
95 {allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
96 </TooltipPopup>
97 </Tooltip>
98 )}
99 <Tooltip>
100 <TooltipTrigger
101 render={
102 <Button
103 type="button"
104 size="xs"
105 variant="ghost-muted"
106 aria-label="Open diff"
107 onClick={() => onOpenTurnDiff(runId, files[0]?.path)}
108 />
109 }
110 >
111 <FileDiffIcon className="size-3" />
112 <span className="hidden @[24rem]/changed-files:inline">Open diff</span>
113 </TooltipTrigger>
114 <TooltipPopup side="top">Open the full diff</TooltipPopup>
115 </Tooltip>
116 </div>
117 </div>
118 <ChangedFilesTree
119 key={`${runId}:${allDirectoriesExpanded}`}
120 runId={runId}
121 files={files}
122 allDirectoriesExpanded={allDirectoriesExpanded}
123 resolvedTheme={resolvedTheme}
124 onOpenTurnDiff={onOpenTurnDiff}
125 onFileContextMenu={onFileContextMenu}
126 />
127 </div>
128 );
129});
130​
131export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
132 runId: RunId;
133 files: ReadonlyArray<TurnDiffFileChange>;
134 allDirectoriesExpanded: boolean;
135 resolvedTheme: "light" | "dark";
136 onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
137 onFileContextMenu?: ChangedFileContextMenuHandler | undefined;
138}) {
139 const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, runId, onFileContextMenu } =
140 props;
141 const treeNodes = useMemo(() => buildTurnDiffTree(files), [files]);
142 const directoryPathsKey = useMemo(
143 () => collectDirectoryPaths(treeNodes).join("\u0000"),
144 [treeNodes],
145 );
146 const hasDirectoryNodes = directoryPathsKey.length > 0;
147 const expansionStateKey = `${allDirectoriesExpanded ? "expanded" : "collapsed"}\u0000${directoryPathsKey}`;
148 const [directoryExpansionState, setDirectoryExpansionState] = useState<{
149 key: string;
150 overrides: Record<string, boolean>;
151 }>(() => ({
152 key: expansionStateKey,
153 overrides: {},
154 }));
155 const expandedDirectories =
156 directoryExpansionState.key === expansionStateKey
157 ? directoryExpansionState.overrides
158 : EMPTY_DIRECTORY_OVERRIDES;
159​
160 const toggleDirectory = useCallback(
161 (pathValue: string) => {
162 setDirectoryExpansionState((current) => {
163 const nextOverrides = current.key === expansionStateKey ? current.overrides : {};
164 return {
165 key: expansionStateKey,
166 overrides: {
167 ...nextOverrides,
168 [pathValue]: !(nextOverrides[pathValue] ?? allDirectoriesExpanded),
169 },
170 };
171 });
172 },
173 [allDirectoriesExpanded, expansionStateKey],
174 );
175​
176 const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {
177 const leftPadding = 8 + depth * 14;
178 if (node.kind === "directory") {
179 const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded;
180 return (
181 <div key={`dir:${node.path}`}>
182 <button
183 type="button"
184 data-scroll-anchor-ignore
185 aria-expanded={isExpanded}
186 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-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"
187 style={{ paddingLeft: `${leftPadding}px` }}
188 onClick={() => toggleDirectory(node.path)}
189 >
190 <ChevronRightIcon
191 aria-hidden="true"
192 className={cn(
193 "size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
194 isExpanded && "rotate-90",
195 )}
196 />
197 {isExpanded ? (
198 <FolderIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
199 ) : (
200 <FolderClosedIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
201 )}
202 <span className="truncate font-mono text-[11px] text-muted-foreground/90 group-hover:text-foreground/90">
203 {node.name}
204 </span>
205 {hasNonZeroStat(node.stat) && (
206 <span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
207 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
208 </span>
209 )}
210 </button>
211 {isExpanded && (
212 <div>{node.children.map((childNode) => renderTreeNode(childNode, depth + 1))}</div>
213 )}
214 </div>
215 );
216 }
217​
218 return (
219 <button
220 key={`file:${node.path}`}
221 type="button"
222 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-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"
223 style={{ paddingLeft: `${leftPadding}px` }}
224 onClick={() => onOpenTurnDiff(runId, node.path)}
225 onContextMenu={
226 onFileContextMenu
227 ? (event) => {
228 event.preventDefault();
229 onFileContextMenu(node.path, event);
230 }
231 : undefined
232 }
233 >
234 {hasDirectoryNodes || depth > 0 ? (
235 <span aria-hidden="true" className="size-3.5 shrink-0" />
236 ) : null}
237 <PierreEntryIcon
238 pathValue={node.path}
239 kind="file"
240 theme={resolvedTheme}
241 className="size-3.5 text-muted-foreground/70"
242 />
243 <span className="truncate font-mono text-xs text-foreground/85 group-hover:text-foreground">
244 {node.name}
245 </span>
246 {node.stat && (
247 <span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
248 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
249 </span>
250 )}
251 </button>
252 );
253 };
254​
255 return <div className="p-2">{treeNodes.map((node) => renderTreeNode(node, 0))}</div>;
256});
257​
258function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {
259 const paths: string[] = [];
260 for (const node of nodes) {
261 if (node.kind !== "directory") continue;
262 paths.push(node.path);
263 paths.push(...collectDirectoryPaths(node.children));
264 }
265 return paths;