Open History to see the last commit
1import { type TurnId } 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 turnId: TurnId;
30 files: ReadonlyArray<TurnDiffFileChange>;
31 allDirectoriesExpanded: boolean;
32 resolvedTheme: "light" | "dark";
33 onToggleAllDirectories: () => void;
34 onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
35 onFileContextMenu?: ChangedFileContextMenuHandler | undefined;
36}) {
37 const {
38 turnId,
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(turnId, 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={`${turnId}:${allDirectoriesExpanded}`}
120 turnId={turnId}
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 turnId: TurnId;
133 files: ReadonlyArray<TurnDiffFileChange>;
134 allDirectoriesExpanded: boolean;
135 resolvedTheme: "light" | "dark";
136 onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
137 onFileContextMenu?: ChangedFileContextMenuHandler | undefined;
138}) {
139 const {
140 files,
141 allDirectoriesExpanded,
142 onOpenTurnDiff,
143 resolvedTheme,
144 turnId,
145 onFileContextMenu,
146 } = props;
147 const treeNodes = useMemo(() => buildTurnDiffTree(files), [files]);
148 const directoryPathsKey = useMemo(
149 () => collectDirectoryPaths(treeNodes).join("\u0000"),
150 [treeNodes],
151 );
152 const hasDirectoryNodes = directoryPathsKey.length > 0;
153 const expansionStateKey = `${allDirectoriesExpanded ? "expanded" : "collapsed"}\u0000${directoryPathsKey}`;
154 const [directoryExpansionState, setDirectoryExpansionState] = useState<{
155 key: string;
156 overrides: Record<string, boolean>;
157 }>(() => ({
158 key: expansionStateKey,
159 overrides: {},
160 }));
161 const expandedDirectories =
162 directoryExpansionState.key === expansionStateKey
163 ? directoryExpansionState.overrides
164 : EMPTY_DIRECTORY_OVERRIDES;
165
166 const toggleDirectory = useCallback(
167 (pathValue: string) => {
168 setDirectoryExpansionState((current) => {
169 const nextOverrides = current.key === expansionStateKey ? current.overrides : {};
170 return {
171 key: expansionStateKey,
172 overrides: {
173 ...nextOverrides,
174 [pathValue]: !(nextOverrides[pathValue] ?? allDirectoriesExpanded),
175 },
176 };
177 });
178 },
179 [allDirectoriesExpanded, expansionStateKey],
180 );
181
182 const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {
183 const leftPadding = 8 + depth * 14;
184 if (node.kind === "directory") {
185 const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded;
186 return (
187 <div key={`dir:${node.path}`}>
188 <button
189 type="button"
190 data-scroll-anchor-ignore
191 aria-expanded={isExpanded}
192 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"
193 style={{ paddingLeft: `${leftPadding}px` }}
194 onClick={() => toggleDirectory(node.path)}
195 >
196 <ChevronRightIcon
197 aria-hidden="true"
198 className={cn(
199 "size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
200 isExpanded && "rotate-90",
201 )}
202 />
203 {isExpanded ? (
204 <FolderIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
205 ) : (
206 <FolderClosedIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
207 )}
208 <span className="truncate font-mono text-[11px] text-muted-foreground/90 group-hover:text-foreground/90">
209 {node.name}
210 </span>
211 {hasNonZeroStat(node.stat) && (
212 <span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
213 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
214 </span>
215 )}
216 </button>
217 {isExpanded && (
218 <div>{node.children.map((childNode) => renderTreeNode(childNode, depth + 1))}</div>
219 )}
220 </div>
221 );
222 }
223
224 return (
225 <button
226 key={`file:${node.path}`}
227 type="button"
228 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"
229 style={{ paddingLeft: `${leftPadding}px` }}
230 onClick={() => onOpenTurnDiff(turnId, node.path)}
231 onContextMenu={
232 onFileContextMenu
233 ? (event) => {
234 event.preventDefault();
235 onFileContextMenu(node.path, event);
236 }
237 : undefined
238 }
239 >
240 {hasDirectoryNodes || depth > 0 ? (
241 <span aria-hidden="true" className="size-3.5 shrink-0" />
242 ) : null}
243 <PierreEntryIcon
244 pathValue={node.path}
245 kind="file"
246 theme={resolvedTheme}
247 className="size-3.5 text-muted-foreground/70"
248 />
249 <span className="truncate font-mono text-xs text-foreground/85 group-hover:text-foreground">
250 {node.name}
251 </span>
252 {node.stat && (
253 <span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
254 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
255 </span>
256 )}
257 </button>
258 );
259 };
260
261 return <div className="p-2">{treeNodes.map((node) => renderTreeNode(node, 0))}</div>;
262});
263
264function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {
265 const paths: string[] = [];
266 for (const node of nodes) {
267 if (node.kind !== "directory") continue;
268 paths.push(node.path);
269 paths.push(...collectDirectoryPaths(node.children));
270 }
271 return paths;
272}