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

ChangedFilesTree.tsx

333 lines12.8 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 <button
178 key={file.path}
179 type="button"
180 title={file.path}
181 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"
182 onClick={() => onOpenTurnDiff(turnId, file.path)}
183 >
184 <PierreEntryIcon
185 pathValue={file.path}
186 kind="file"
187 theme={resolvedTheme}
188 className="size-3 shrink-0 text-muted-foreground/70"
189 />
190 <span className="truncate">{changedFileName(file.path)}</span>
191 </button>
192 ))}
193 <button
194 type="button"
195 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"
196 onClick={() => onExpandedChange(true)}
197 >
198 Show all {files.length} files
199 </button>
200 </div>
201 </div>
202 ) : null}
203 </div>
204 );
205});
206​
207export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
208 turnId: TurnId;
209 files: ReadonlyArray<TurnDiffFileChange>;
210 allDirectoriesExpanded: boolean;
211 resolvedTheme: "light" | "dark";
212 onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
213}) {
214 const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, turnId } = props;
215 const treeNodes = useMemo(() => buildTurnDiffTree(files), [files]);
216 const directoryPathsKey = useMemo(
217 () => collectDirectoryPaths(treeNodes).join("\u0000"),
218 [treeNodes],
219 );
220 const hasDirectoryNodes = directoryPathsKey.length > 0;
221 const expansionStateKey = `${allDirectoriesExpanded ? "expanded" : "collapsed"}\u0000${directoryPathsKey}`;
222 const [directoryExpansionState, setDirectoryExpansionState] = useState<{
223 key: string;
224 overrides: Record<string, boolean>;
225 }>(() => ({
226 key: expansionStateKey,
227 overrides: {},
228 }));
229 const expandedDirectories =
230 directoryExpansionState.key === expansionStateKey
231 ? directoryExpansionState.overrides
232 : EMPTY_DIRECTORY_OVERRIDES;
233​
234 const toggleDirectory = useCallback(
235 (pathValue: string) => {
236 setDirectoryExpansionState((current) => {
237 const nextOverrides = current.key === expansionStateKey ? current.overrides : {};
238 return {
239 key: expansionStateKey,
240 overrides: {
241 ...nextOverrides,
242 [pathValue]: !(nextOverrides[pathValue] ?? allDirectoriesExpanded),
243 },
244 };
245 });
246 },
247 [allDirectoriesExpanded, expansionStateKey],
248 );
249​
250 const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {
251 const leftPadding = 8 + depth * 14;
252 if (node.kind === "directory") {
253 const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded;
254 return (
255 <div key={`dir:${node.path}`}>
256 <button
257 type="button"
258 data-scroll-anchor-ignore
259 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"
260 style={{ paddingLeft: `${leftPadding}px` }}
261 onClick={() => toggleDirectory(node.path)}
262 >
263 <ChevronRightIcon
264 aria-hidden="true"
265 className={cn(
266 "size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
267 isExpanded && "rotate-90",
268 )}
269 />
270 {isExpanded ? (
271 <FolderIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
272 ) : (
273 <FolderClosedIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
274 )}
275 <span className="truncate font-mono text-[11px] text-muted-foreground/90 group-hover:text-foreground/90">
276 {node.name}
277 </span>
278 {hasNonZeroStat(node.stat) && (
279 <span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
280 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
281 </span>
282 )}
283 </button>
284 {isExpanded && (
285 <div className="space-y-0.5">
286 {node.children.map((childNode) => renderTreeNode(childNode, depth + 1))}
287 </div>
288 )}
289 </div>
290 );
291 }
292​
293 return (
294 <button
295 key={`file:${node.path}`}
296 type="button"
297 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"
298 style={{ paddingLeft: `${leftPadding}px` }}
299 onClick={() => onOpenTurnDiff(turnId, node.path)}
300 >
301 {hasDirectoryNodes || depth > 0 ? (
302 <span aria-hidden="true" className="size-3.5 shrink-0" />
303 ) : null}
304 <PierreEntryIcon
305 pathValue={node.path}
306 kind="file"
307 theme={resolvedTheme}
308 className="size-3.5 text-muted-foreground/70"
309 />
310 <span className="truncate font-mono text-[11px] text-muted-foreground/80 group-hover:text-foreground/90">
311 {node.name}
312 </span>
313 {node.stat && (
314 <span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
315 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
316 </span>
317 )}
318 </button>
319 );
320 };
321​
322 return <div className="space-y-0.5">{treeNodes.map((node) => renderTreeNode(node, 0))}</div>;
323});
324​
325function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {
326 const paths: string[] = [];
327 for (const node of nodes) {
328 if (node.kind !== "directory") continue;
329 paths.push(node.path);
330 paths.push(...collectDirectoryPaths(node.children));
331 }
332 return paths;