Open History to see the last commit
1import { type TurnId } from "@t3tools/contracts";
2import { 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 {
23 changedFileName,
24 selectChangedFilePreview,
25 summarizeChangedFileScopes,
26} from "./changedFilesPresentation";
27
28const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
29
30export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
31 turnId: TurnId;
32 files: ReadonlyArray<TurnDiffFileChange>;
33 expanded: boolean;
34 showCompactPreview: boolean;
35 allDirectoriesExpanded: boolean;
36 resolvedTheme: "light" | "dark";
37 onExpandedChange: (expanded: boolean) => void;
38 onToggleAllDirectories: () => void;
39 onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
40}) {
41 const {
42 turnId,
43 files,
44 expanded,
45 showCompactPreview,
46 allDirectoriesExpanded,
47 resolvedTheme,
48 onExpandedChange,
49 onToggleAllDirectories,
50 onOpenTurnDiff,
51 } = props;
52 const summaryStat = useMemo(() => summarizeTurnDiffStats(files), [files]);
53 const scopeSummary = useMemo(() => summarizeChangedFileScopes(files), [files]);
54 const previewFiles = useMemo(() => selectChangedFilePreview(files), [files]);
55 const compactPreviewVisible = showCompactPreview && !expanded;
56
57 return (
58 <div
59 className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 dark:border-transparent dark:bg-input/32"
60 data-changed-files-state={
61 expanded ? "expanded" : compactPreviewVisible ? "preview" : "collapsed"
62 }
63 >
64 <div
65 className={cn(
66 "flex items-center justify-between gap-2 rounded-xl px-1",
67 expanded &&
68 "sticky top-2 z-10 mb-2 bg-secondary dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]",
69 )}
70 >
71 <button
72 type="button"
73 aria-expanded={expanded}
74 data-scroll-anchor-ignore
75 className="group flex min-w-0 flex-1 items-center gap-1.5 rounded-lg px-1 py-1.5 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
76 onClick={() => onExpandedChange(!expanded)}
77 >
78 <ChevronRightIcon
79 aria-hidden="true"
80 className={cn(
81 "size-3.5 shrink-0 text-muted-foreground transition-transform",
82 expanded && "rotate-90",
83 )}
84 />
85 <span className="flex min-w-0 items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
86 <span>
87 {files.length} changed file{files.length === 1 ? "" : "s"}
88 </span>
89 {hasNonZeroStat(summaryStat) && (
90 <DiffStatLabel
91 additions={summaryStat.additions}
92 className="text-xs leading-4"
93 deletions={summaryStat.deletions}
94 layout="inline"
95 />
96 )}
97 </span>
98 <span className="ml-1 hidden truncate text-[11px] text-muted-foreground group-hover:text-foreground/80 sm:inline">
99 {expanded ? "Hide files" : "Show files"}
100 </span>
101 </button>
102 <div className="flex items-center gap-1.5">
103 {expanded ? (
104 <Tooltip>
105 <TooltipTrigger
106 render={
107 <Button
108 type="button"
109 size="icon-xs"
110 variant="outline"
111 className="!size-[22px]"
112 aria-label={
113 allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"
114 }
115 data-scroll-anchor-ignore
116 onClick={onToggleAllDirectories}
117 />
118 }
119 >
120 {allDirectoriesExpanded ? (
121 <ChevronsDownUpIcon className="size-3" />
122 ) : (
123 <ChevronsUpDownIcon className="size-3" />
124 )}
125 </TooltipTrigger>
126 <TooltipPopup side="top">
127 {allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
128 </TooltipPopup>
129 </Tooltip>
130 ) : null}
131 <Tooltip>
132 <TooltipTrigger
133 render={
134 <Button
135 type="button"
136 size="xs"
137 variant="outline"
138 aria-label="Open diff"
139 onClick={() => onOpenTurnDiff(turnId, files[0]?.path)}
140 />
141 }
142 >
143 <FileDiffIcon className="size-3" />
144 <span className="hidden sm:inline">Open diff</span>
145 </TooltipTrigger>
146 <TooltipPopup side="top">Open the full diff</TooltipPopup>
147 </Tooltip>
148 </div>
149 </div>
150 {expanded ? (
151 <ChangedFilesTree
152 key={`changed-files-tree:${turnId}`}
153 turnId={turnId}
154 files={files}
155 allDirectoriesExpanded={allDirectoriesExpanded}
156 resolvedTheme={resolvedTheme}
157 onOpenTurnDiff={onOpenTurnDiff}
158 />
159 ) : compactPreviewVisible ? (
160 <div className="px-2 pb-1.5 pt-1">
161 <p className="flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[11px] text-muted-foreground">
162 {scopeSummary.map((scope, index) => (
163 <span key={scope.label} className="inline-flex items-center gap-1">
164 {index > 0 ? <span aria-hidden="true">·</span> : null}
165 <span className="font-mono text-foreground/75">{scope.label}</span>
166 <span>
167 {scope.fileCount} file{scope.fileCount === 1 ? "" : "s"}
168 </span>
169 </span>
170 ))}
171 </p>
172 <div className="mt-2 flex flex-wrap items-center gap-1.5">
173 {previewFiles.map((file) => (
174 <button
175 key={file.path}
176 type="button"
177 title={file.path}
178 className="inline-flex max-w-48 items-center gap-1 rounded-md border border-border/70 bg-background/45 px-1.5 py-1 font-mono text-[10px] text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
179 onClick={() => onOpenTurnDiff(turnId, file.path)}
180 >
181 <PierreEntryIcon
182 pathValue={file.path}
183 kind="file"
184 theme={resolvedTheme}
185 className="size-3 shrink-0 text-muted-foreground/70"
186 />
187 <span className="truncate">{changedFileName(file.path)}</span>
188 </button>
189 ))}
190 <button
191 type="button"
192 className="rounded-md px-1.5 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
193 onClick={() => onExpandedChange(true)}
194 >
195 Show all {files.length} files
196 </button>
197 </div>
198 </div>
199 ) : null}
200 </div>
201 );
202});
203
204export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
205 turnId: TurnId;
206 files: ReadonlyArray<TurnDiffFileChange>;
207 allDirectoriesExpanded: boolean;
208 resolvedTheme: "light" | "dark";
209 onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
210}) {
211 const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, turnId } = props;
212 const treeNodes = useMemo(() => buildTurnDiffTree(files), [files]);
213 const directoryPathsKey = useMemo(
214 () => collectDirectoryPaths(treeNodes).join("\u0000"),
215 [treeNodes],
216 );
217 const hasDirectoryNodes = directoryPathsKey.length > 0;
218 const expansionStateKey = `${allDirectoriesExpanded ? "expanded" : "collapsed"}\u0000${directoryPathsKey}`;
219 const [directoryExpansionState, setDirectoryExpansionState] = useState<{
220 key: string;
221 overrides: Record<string, boolean>;
222 }>(() => ({
223 key: expansionStateKey,
224 overrides: {},
225 }));
226 const expandedDirectories =
227 directoryExpansionState.key === expansionStateKey
228 ? directoryExpansionState.overrides
229 : EMPTY_DIRECTORY_OVERRIDES;
230
231 const toggleDirectory = useCallback(
232 (pathValue: string) => {
233 setDirectoryExpansionState((current) => {
234 const nextOverrides = current.key === expansionStateKey ? current.overrides : {};
235 return {
236 key: expansionStateKey,
237 overrides: {
238 ...nextOverrides,
239 [pathValue]: !(nextOverrides[pathValue] ?? allDirectoriesExpanded),
240 },
241 };
242 });
243 },
244 [allDirectoriesExpanded, expansionStateKey],
245 );
246
247 const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {
248 const leftPadding = 8 + depth * 14;
249 if (node.kind === "directory") {
250 const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded;
251 return (
252 <div key={`dir:${node.path}`}>
253 <button
254 type="button"
255 data-scroll-anchor-ignore
256 className="group flex w-full items-center gap-1.5 rounded-xl py-1 pr-3 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"
257 style={{ paddingLeft: `${leftPadding}px` }}
258 onClick={() => toggleDirectory(node.path)}
259 >
260 <ChevronRightIcon
261 aria-hidden="true"
262 className={cn(
263 "size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
264 isExpanded && "rotate-90",
265 )}
266 />
267 {isExpanded ? (
268 <FolderIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
269 ) : (
270 <FolderClosedIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
271 )}
272 <span className="truncate font-mono text-[11px] text-muted-foreground/90 group-hover:text-foreground/90">
273 {node.name}
274 </span>
275 {hasNonZeroStat(node.stat) && (
276 <span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
277 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
278 </span>
279 )}
280 </button>
281 {isExpanded && (
282 <div className="space-y-0.5">
283 {node.children.map((childNode) => renderTreeNode(childNode, depth + 1))}
284 </div>
285 )}
286 </div>
287 );
288 }
289
290 return (
291 <button
292 key={`file:${node.path}`}
293 type="button"
294 className="group flex w-full items-center gap-1.5 rounded-xl py-1 pr-3 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"
295 style={{ paddingLeft: `${leftPadding}px` }}
296 onClick={() => onOpenTurnDiff(turnId, node.path)}
297 >
298 {hasDirectoryNodes || depth > 0 ? (
299 <span aria-hidden="true" className="size-3.5 shrink-0" />
300 ) : null}
301 <PierreEntryIcon
302 pathValue={node.path}
303 kind="file"
304 theme={resolvedTheme}
305 className="size-3.5 text-muted-foreground/70"
306 />
307 <span className="truncate font-mono text-[11px] text-muted-foreground/80 group-hover:text-foreground/90">
308 {node.name}
309 </span>
310 {node.stat && (
311 <span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
312 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
313 </span>
314 )}
315 </button>
316 );
317 };
318
319 return <div className="space-y-0.5">{treeNodes.map((node) => renderTreeNode(node, 0))}</div>;
320});
321
322function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {
323 const paths: string[] = [];
324 for (const node of nodes) {
325 if (node.kind !== "directory") continue;
326 paths.push(node.path);
327 paths.push(...collectDirectoryPaths(node.children));
328 }
329 return paths;
330}