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

ChangedFilesTree.tsx

260 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​
125// Building the tree walks every file, and the compiler would redo it each render
126// because the expansion state hook runs after it.
127function useTurnDiffTree(files: ReadonlyArray<TurnDiffFileChange>) {
128 "use memo";
129 const treeNodes = buildTurnDiffTree(files);
130 return { treeNodes, directoryPathsKey: collectDirectoryPaths(treeNodes).join("\u0000") };
132​
133export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
134 runId: RunId;
135 files: ReadonlyArray<TurnDiffFileChange>;
136 allDirectoriesExpanded: boolean;
137 resolvedTheme: "light" | "dark";
138 onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
139 onFileContextMenu?: ChangedFileContextMenuHandler | undefined;
140}) {
141 const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, runId, onFileContextMenu } =
142 props;
143 const { treeNodes, directoryPathsKey } = useTurnDiffTree(files);
144 const hasDirectoryNodes = directoryPathsKey.length > 0;
145 const expansionStateKey = `${allDirectoriesExpanded ? "expanded" : "collapsed"}\u0000${directoryPathsKey}`;
146 const [directoryExpansionState, setDirectoryExpansionState] = useState<{
147 key: string;
148 overrides: Record<string, boolean>;
149 }>(() => ({
150 key: expansionStateKey,
151 overrides: {},
152 }));
153 const expandedDirectories =
154 directoryExpansionState.key === expansionStateKey
155 ? directoryExpansionState.overrides
156 : EMPTY_DIRECTORY_OVERRIDES;
157​
158 const toggleDirectory = (pathValue: string) => {
159 setDirectoryExpansionState((current) => {
160 const nextOverrides = current.key === expansionStateKey ? current.overrides : {};
161 return {
162 key: expansionStateKey,
163 overrides: {
164 ...nextOverrides,
165 [pathValue]: !(nextOverrides[pathValue] ?? allDirectoriesExpanded),
166 },
167 };
168 });
169 };
170​
171 const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {
172 const leftPadding = 8 + depth * 14;
173 if (node.kind === "directory") {
174 const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded;
175 return (
176 <div key={`dir:${node.path}`}>
177 <button
178 type="button"
179 data-scroll-anchor-ignore
180 aria-expanded={isExpanded}
181 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"
182 style={{ paddingLeft: `${leftPadding}px` }}
183 onClick={() => toggleDirectory(node.path)}
184 >
185 <ChevronRightIcon
186 aria-hidden="true"
187 className={cn(
188 "size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
189 isExpanded && "rotate-90",
190 )}
191 />
192 <MorphIcon
193 className="size-3.5 shrink-0 text-muted-foreground/75"
194 icon={isExpanded ? Folder : FolderClosed}
195 />
196 <span className="truncate font-mono text-2xs text-muted-foreground/90 group-hover:text-foreground/90">
197 {node.name}
198 </span>
199 {hasNonZeroStat(node.stat) && (
200 <span className="ml-auto shrink-0 font-mono text-3xs tabular-nums">
201 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
202 </span>
203 )}
204 </button>
205 {isExpanded && (
206 <div>{node.children.map((childNode) => renderTreeNode(childNode, depth + 1))}</div>
207 )}
208 </div>
209 );
210 }
211​
212 return (
213 <button
214 key={`file:${node.path}`}
215 type="button"
216 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"
217 style={{ paddingLeft: `${leftPadding}px` }}
218 onClick={() => onOpenTurnDiff(runId, node.path)}
219 onContextMenu={
220 onFileContextMenu
221 ? (event) => {
222 event.preventDefault();
223 onFileContextMenu(node.path, event);
224 }
225 : undefined
226 }
227 >
228 {hasDirectoryNodes || depth > 0 ? (
229 <span aria-hidden="true" className="size-3.5 shrink-0" />
230 ) : null}
231 <PierreEntryIcon
232 pathValue={node.path}
233 kind="file"
234 theme={resolvedTheme}
235 className="size-3.5 text-muted-foreground/70"
236 />
237 <span className="flex min-w-0 font-mono text-xs text-foreground/85 group-hover:text-foreground">
238 <MiddleTruncate value={node.name} />
239 </span>
240 {node.stat && (
241 <span className="ml-auto shrink-0 font-mono text-3xs tabular-nums">
242 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
243 </span>
244 )}
245 </button>
246 );
247 };
248​
249 return <div className="p-2">{treeNodes.map((node) => renderTreeNode(node, 0))}</div>;
250});
251​
252function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {
253 const paths: string[] = [];
254 for (const node of nodes) {
255 if (node.kind !== "directory") continue;
256 paths.push(node.path);
257 paths.push(...collectDirectoryPaths(node.children));
258 }
259 return paths;