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

ChangedFilesTree.tsx

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