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