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

ChangedFilesTree.tsx

338 lines13.0 KB

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