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

ChangedFilesTree.tsx

250 lines9.0 KB

1import { type RunId } 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";
22​
23const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
24​
25export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
26 runId: RunId;
27 files: ReadonlyArray<TurnDiffFileChange>;
28 allDirectoriesExpanded: boolean;
29 resolvedTheme: "light" | "dark";
30 onToggleAllDirectories: () => void;
31 onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
32}) {
33 const {
34 runId,
35 files,
36 allDirectoriesExpanded,
37 resolvedTheme,
38 onToggleAllDirectories,
39 onOpenTurnDiff,
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-[color-mix(in_srgb,var(--input)_20%,var(--background))]"
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 {allDirectoriesExpanded ? (
84 <ChevronsDownUpIcon className="size-3" />
85 ) : (
86 <ChevronsUpDownIcon className="size-3" />
87 )}
88 </TooltipTrigger>
89 <TooltipPopup side="top">
90 {allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
91 </TooltipPopup>
92 </Tooltip>
93 )}
94 <Tooltip>
95 <TooltipTrigger
96 render={
97 <Button
98 type="button"
99 size="xs"
100 variant="ghost-muted"
101 aria-label="Open diff"
102 onClick={() => onOpenTurnDiff(runId, files[0]?.path)}
103 />
104 }
105 >
106 <FileDiffIcon className="size-3" />
107 <span className="hidden @[24rem]/changed-files:inline">Open diff</span>
108 </TooltipTrigger>
109 <TooltipPopup side="top">Open the full diff</TooltipPopup>
110 </Tooltip>
111 </div>
112 </div>
113 <ChangedFilesTree
114 key={`${runId}:${allDirectoriesExpanded}`}
115 runId={runId}
116 files={files}
117 allDirectoriesExpanded={allDirectoriesExpanded}
118 resolvedTheme={resolvedTheme}
119 onOpenTurnDiff={onOpenTurnDiff}
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}) {
132 const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, runId } = props;
133 const treeNodes = useMemo(() => buildTurnDiffTree(files), [files]);
134 const directoryPathsKey = useMemo(
135 () => collectDirectoryPaths(treeNodes).join("\u0000"),
136 [treeNodes],
137 );
138 const hasDirectoryNodes = directoryPathsKey.length > 0;
139 const expansionStateKey = `${allDirectoriesExpanded ? "expanded" : "collapsed"}\u0000${directoryPathsKey}`;
140 const [directoryExpansionState, setDirectoryExpansionState] = useState<{
141 key: string;
142 overrides: Record<string, boolean>;
143 }>(() => ({
144 key: expansionStateKey,
145 overrides: {},
146 }));
147 const expandedDirectories =
148 directoryExpansionState.key === expansionStateKey
149 ? directoryExpansionState.overrides
150 : EMPTY_DIRECTORY_OVERRIDES;
151​
152 const toggleDirectory = useCallback(
153 (pathValue: string) => {
154 setDirectoryExpansionState((current) => {
155 const nextOverrides = current.key === expansionStateKey ? current.overrides : {};
156 return {
157 key: expansionStateKey,
158 overrides: {
159 ...nextOverrides,
160 [pathValue]: !(nextOverrides[pathValue] ?? allDirectoriesExpanded),
161 },
162 };
163 });
164 },
165 [allDirectoriesExpanded, expansionStateKey],
166 );
167​
168 const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {
169 const leftPadding = 8 + depth * 14;
170 if (node.kind === "directory") {
171 const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded;
172 return (
173 <div key={`dir:${node.path}`}>
174 <button
175 type="button"
176 data-scroll-anchor-ignore
177 aria-expanded={isExpanded}
178 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"
179 style={{ paddingLeft: `${leftPadding}px` }}
180 onClick={() => toggleDirectory(node.path)}
181 >
182 <ChevronRightIcon
183 aria-hidden="true"
184 className={cn(
185 "size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
186 isExpanded && "rotate-90",
187 )}
188 />
189 {isExpanded ? (
190 <FolderIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
191 ) : (
192 <FolderClosedIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
193 )}
194 <span className="truncate font-mono text-[11px] text-muted-foreground/90 group-hover:text-foreground/90">
195 {node.name}
196 </span>
197 {hasNonZeroStat(node.stat) && (
198 <span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
199 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
200 </span>
201 )}
202 </button>
203 {isExpanded && (
204 <div>{node.children.map((childNode) => renderTreeNode(childNode, depth + 1))}</div>
205 )}
206 </div>
207 );
208 }
209​
210 return (
211 <button
212 key={`file:${node.path}`}
213 type="button"
214 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"
215 style={{ paddingLeft: `${leftPadding}px` }}
216 onClick={() => onOpenTurnDiff(runId, node.path)}
217 >
218 {hasDirectoryNodes || depth > 0 ? (
219 <span aria-hidden="true" className="size-3.5 shrink-0" />
220 ) : null}
221 <PierreEntryIcon
222 pathValue={node.path}
223 kind="file"
224 theme={resolvedTheme}
225 className="size-3.5 text-muted-foreground/70"
226 />
227 <span className="truncate font-mono text-xs text-foreground/85 group-hover:text-foreground">
228 {node.name}
229 </span>
230 {node.stat && (
231 <span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
232 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
233 </span>
234 )}
235 </button>
236 );
237 };
238​
239 return <div className="p-2">{treeNodes.map((node) => renderTreeNode(node, 0))}</div>;
240});
241​
242function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {
243 const paths: string[] = [];
244 for (const node of nodes) {
245 if (node.kind !== "directory") continue;
246 paths.push(node.path);
247 paths.push(...collectDirectoryPaths(node.children));
248 }
249 return paths;