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

ChangedFilesTree.tsx

253 lines9.7 KB

1import { type RunId } from "@t3tools/contracts";
2import { type MouseEvent, memo, useState } from "react";
3import { type TurnDiffFileChange } from "../../types";
4import {
5 buildTurnDiffTree,
6 summarizeTurnDiffStats,
7 type TurnDiffTreeNode,
8} from "../../lib/turnDiffTree";
9import { ChevronRightIcon, FileDiffIcon } from "lucide-react";
10import { ChevronsDownUp, ChevronsUpDown, Folder, FolderClosed } from "lucide";
11import { cn } from "~/lib/utils";
12import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
13import { PierreEntryIcon } from "./PierreEntryIcon";
14import { Button } from "../ui/button";
15import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
16import { MiddleTruncate } from "../ui/middle-truncate";
17import { MorphIcon } from "~/components/MorphIcon";
18​
19const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
20​
21export type ChangedFileContextMenuHandler = (filePath: string, event: MouseEvent) => void;
22​
23export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
24 runId: RunId;
25 files: ReadonlyArray<TurnDiffFileChange>;
26 allDirectoriesExpanded: boolean;
27 resolvedTheme: "light" | "dark";
28 onToggleAllDirectories: () => void;
29 onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
30 onFileContextMenu?: ChangedFileContextMenuHandler | undefined;
31}) {
32 const {
33 runId,
34 files,
35 allDirectoriesExpanded,
36 resolvedTheme,
37 onToggleAllDirectories,
38 onOpenTurnDiff,
39 onFileContextMenu,
40 } = props;
41 const summaryStat = summarizeTurnDiffStats(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-background dark:bg-linear-to-b dark:from-input/20 dark:to-input/20"
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 <MorphIcon
84 className="size-3"
85 icon={allDirectoriesExpanded ? ChevronsDownUp : ChevronsUpDown}
86 />
87 </TooltipTrigger>
88 <TooltipPopup side="top">
89 {allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
90 </TooltipPopup>
91 </Tooltip>
92 )}
93 <Tooltip>
94 <TooltipTrigger
95 render={
96 <Button
97 type="button"
98 size="xs"
99 variant="ghost-muted"
100 aria-label="Open diff"
101 onClick={() => onOpenTurnDiff(runId, files[0]?.path)}
102 />
103 }
104 >
105 <FileDiffIcon className="size-3" />
106 <span className="hidden @[24rem]/changed-files:inline">Open diff</span>
107 </TooltipTrigger>
108 <TooltipPopup side="top">Open the full diff</TooltipPopup>
109 </Tooltip>
110 </div>
111 </div>
112 <ChangedFilesTree
113 key={`${runId}:${allDirectoriesExpanded}`}
114 runId={runId}
115 files={files}
116 allDirectoriesExpanded={allDirectoriesExpanded}
117 resolvedTheme={resolvedTheme}
118 onOpenTurnDiff={onOpenTurnDiff}
119 onFileContextMenu={onFileContextMenu}
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 onFileContextMenu?: ChangedFileContextMenuHandler | undefined;
132}) {
133 const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, runId, onFileContextMenu } =
134 props;
135 // Overrides apply only while their key matches the current one, so starting from no key is
136 // the same as starting with no overrides. That lets this hook run before the tree is built,
137 // and the compiler caches the tree on `files`.
138 const [directoryExpansionState, setDirectoryExpansionState] = useState<{
139 key: string | null;
140 overrides: Record<string, boolean>;
141 }>({ key: null, overrides: {} });
142 const treeNodes = buildTurnDiffTree(files);
143 const directoryPathsKey = collectDirectoryPaths(treeNodes).join("\u0000");
144 const hasDirectoryNodes = directoryPathsKey.length > 0;
145 const expansionStateKey = `${allDirectoriesExpanded ? "expanded" : "collapsed"}\u0000${directoryPathsKey}`;
146 const expandedDirectories =
147 directoryExpansionState.key === expansionStateKey
148 ? directoryExpansionState.overrides
149 : EMPTY_DIRECTORY_OVERRIDES;
150​
151 const toggleDirectory = (pathValue: string) => {
152 setDirectoryExpansionState((current) => {
153 const nextOverrides = current.key === expansionStateKey ? current.overrides : {};
154 return {
155 key: expansionStateKey,
156 overrides: {
157 ...nextOverrides,
158 [pathValue]: !(nextOverrides[pathValue] ?? allDirectoriesExpanded),
159 },
160 };
161 });
162 };
163​
164 const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {
165 const leftPadding = 8 + depth * 14;
166 if (node.kind === "directory") {
167 const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded;
168 return (
169 <div key={`dir:${node.path}`}>
170 <button
171 type="button"
172 data-scroll-anchor-ignore
173 aria-expanded={isExpanded}
174 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-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"
175 style={{ paddingLeft: `${leftPadding}px` }}
176 onClick={() => toggleDirectory(node.path)}
177 >
178 <ChevronRightIcon
179 aria-hidden="true"
180 className={cn(
181 "size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
182 isExpanded && "rotate-90",
183 )}
184 />
185 <MorphIcon
186 className="size-3.5 shrink-0 text-muted-foreground/75"
187 icon={isExpanded ? Folder : FolderClosed}
188 />
189 <span className="truncate font-mono text-2xs text-muted-foreground/90 group-hover:text-foreground/90">
190 {node.name}
191 </span>
192 {hasNonZeroStat(node.stat) && (
193 <span className="ml-auto shrink-0 font-mono text-3xs tabular-nums">
194 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
195 </span>
196 )}
197 </button>
198 {isExpanded && (
199 <div>{node.children.map((childNode) => renderTreeNode(childNode, depth + 1))}</div>
200 )}
201 </div>
202 );
203 }
204​
205 return (
206 <button
207 key={`file:${node.path}`}
208 type="button"
209 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-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"
210 style={{ paddingLeft: `${leftPadding}px` }}
211 onClick={() => onOpenTurnDiff(runId, node.path)}
212 onContextMenu={
213 onFileContextMenu
214 ? (event) => {
215 event.preventDefault();
216 onFileContextMenu(node.path, event);
217 }
218 : undefined
219 }
220 >
221 {hasDirectoryNodes || depth > 0 ? (
222 <span aria-hidden="true" className="size-3.5 shrink-0" />
223 ) : null}
224 <PierreEntryIcon
225 pathValue={node.path}
226 kind="file"
227 theme={resolvedTheme}
228 className="size-3.5 text-muted-foreground/70"
229 />
230 <span className="flex min-w-0 font-mono text-xs text-foreground/85 group-hover:text-foreground">
231 <MiddleTruncate value={node.name} />
232 </span>
233 {node.stat && (
234 <span className="ml-auto shrink-0 font-mono text-3xs tabular-nums">
235 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
236 </span>
237 )}
238 </button>
239 );
240 };
241​
242 return <div className="p-2">{treeNodes.map((node) => renderTreeNode(node, 0))}</div>;
243});
244​
245function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {
246 const paths: string[] = [];
247 for (const node of nodes) {
248 if (node.kind !== "directory") continue;
249 paths.push(node.path);
250 paths.push(...collectDirectoryPaths(node.children));
251 }
252 return paths;