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

DiffFileTree.tsx

265 lines9.9 KB

1import type { GitStatusEntry } from "@pierre/trees";
2import { FileTree, useFileTree } from "@pierre/trees/react";
3import { T, useGT } from "gt-react";
4import { ChevronsDownUpIcon, ChevronsUpDownIcon } from "lucide-react";
5import { useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
6​
7import { useStableCallback } from "~/hooks/useStableCallback";
8import { useTheme } from "~/hooks/useTheme";
9import { cn } from "~/lib/utils";
10import {
11 PIERRE_TREE_UNSAFE_CSS,
12 pierreTreeStyle,
13 titleClippedPierreTreeRow,
14} from "~/pierre-tree-theme";
15​
16import {
17 areAllDirectoriesExpanded,
18 setAllDirectoriesExpanded,
19 subscribeOncePerTask,
20} from "../files/fileTreeExpansion";
21import { Button } from "../ui/button";
22import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
23import {
24 buildDiffFileTreeUpdates,
25 compareDiffFileTreeEntries,
26 collectDirectoryPaths,
27 diffFileTreeModel,
28 type DiffFileTreeEntry,
29} from "./diffFileTree.logic";
30import { diffFileTreePositions } from "@t3tools/client-runtime/diff-file-order";
31​
32export type { DiffFileTreeEntry } from "./diffFileTree.logic";
33​
34interface DiffFileTreeProps {
35 readonly entries: ReadonlyArray<DiffFileTreeEntry>;
36 readonly onSelectFile: (path: string) => void;
37 readonly selectedPath?: string | null;
38 readonly revealRequestId?: number;
39 readonly ariaLabel: string;
40 readonly headerAccessory?: ReactNode;
41 readonly footer?: ReactNode;
42 readonly className?: string;
44​
45export function DiffFileTree({
46 entries,
47 onSelectFile,
48 selectedPath = null,
49 revealRequestId = 0,
50 ariaLabel,
51 headerAccessory,
52 footer,
53 className,
54}: DiffFileTreeProps) {
55 const gt = useGT();
56 const { resolvedTheme } = useTheme();
57 const paths = entries.map((entry) => entry.path);
58 const presented = diffFileTreeModel(paths);
59 const modelPaths = presented.paths;
60 const icons = presented.icons;
61 const directoryPaths = collectDirectoryPaths(modelPaths);
62 const positions = diffFileTreePositions(modelPaths);
63 const [ordering] = useState(() => {
64 let currentPositions: ReadonlyMap<string, number> = new Map();
65 return {
66 sort: compareDiffFileTreeEntries(() => currentPositions),
67 update: (nextPositions: ReadonlyMap<string, number>) => {
68 currentPositions = nextPositions;
69 },
70 };
71 });
72 const gitStatus: ReadonlyArray<GitStatusEntry> = entries.map((entry) => ({
73 path: presented.modelPath(entry.path),
74 status: entry.status,
75 }));
76 const syncingSelectionRef = useRef(false);
77 const handledRevealRef = useRef<{
78 path: string;
79 revealRequestId: number;
80 } | null>(null);
81 const mountedPresentationRef = useRef<ReturnType<typeof diffFileTreeModel> | null>(null);
82​
83 // The tree model keeps the first selection handler it was given.
84 const handleSelectionChange = useStableCallback((selectedPaths: ReadonlyArray<string>) => {
85 if (syncingSelectionRef.current) return;
86 const modelPath = selectedPaths.at(-1);
87 if (modelPath && modelPaths.includes(modelPath)) {
88 onSelectFile(presented.selectionPath(modelPath));
89 }
90 });
91​
92 const { model } = useFileTree({
93 density: "compact",
94 flattenEmptyDirectories: true,
95 initialExpansion: "open",
96 icons,
97 onSelectionChange: handleSelectionChange,
98 paths: [],
99 search: false,
100 sort: ordering.sort,
101 unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
102 });
103 const allDirectoriesExpanded = useSyncExternalStore(
104 (listener) => subscribeOncePerTask(model, listener),
105 () => areAllDirectoriesExpanded(model, directoryPaths),
106 );
107​
108 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes the icon set into the imperative Pierre file tree model
109 useEffect(() => {
110 model.setIcons(icons);
111 }, [icons, model]);
112​
113 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- applies path updates, ordering and git status to the imperative Pierre file tree model
114 useEffect(() => {
115 ordering.update(positions);
116 const mounted = mountedPresentationRef.current;
117 if (mounted?.paths === modelPaths) return;
118 mountedPresentationRef.current = presented;
119 if (mounted === null) {
120 model.resetPaths(modelPaths);
121 } else if (mounted.paths.every((path, index) => modelPaths[index] === path)) {
122 const updates = buildDiffFileTreeUpdates(mounted.paths, modelPaths);
123 if (updates.length > 0) model.batch(updates);
124 } else {
125 // A reset can turn a file path into a directory. Carry selection and focus
126 // through real paths so paging keeps the same file without revealing it again.
127 const focusedPath = model.getFocusedPath();
128 const nextFocusedPath =
129 focusedPath === null ? null : presented.modelPath(mounted.selectionPath(focusedPath));
130 const selectedPaths = model
131 .getSelectedPaths()
132 .map((path) => presented.modelPath(mounted.selectionPath(path)))
133 .filter((path) => path.endsWith("/") || modelPaths.includes(path));
134 const collapsedDirectories = directoryPaths.filter((path) => {
135 const directory = model.getItem(path);
136 return directory !== null && "isExpanded" in directory && !directory.isExpanded();
137 });
138 syncingSelectionRef.current = true;
139 model.resetPaths(modelPaths);
140 for (const path of model.getSelectedPaths()) model.getItem(path)?.deselect();
141 for (const path of selectedPaths) model.getItem(path)?.select();
142 queueMicrotask(() => {
143 syncingSelectionRef.current = false;
144 });
145 for (const path of collapsedDirectories) {
146 const directory = model.getItem(path);
147 if (directory !== null && "collapse" in directory) directory.collapse();
148 }
149 if (
150 nextFocusedPath !== null &&
151 (modelPaths.includes(nextFocusedPath) || directoryPaths.includes(nextFocusedPath))
152 ) {
153 model.focusPath(nextFocusedPath);
154 }
155 }
156 model.setGitStatus(gitStatus);
157 }, [directoryPaths, gitStatus, model, modelPaths, ordering, positions, presented]);
158​
159 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- expands ancestors, selects and scrolls to the requested file in the Pierre tree model
160 useEffect(() => {
161 if (selectedPath === null) {
162 handledRevealRef.current = null;
163 return;
164 }
165 const modelPath = presented.modelPath(selectedPath);
166 const item = model.getItem(modelPath);
167 if (item === null || item.isDirectory()) {
168 handledRevealRef.current = null;
169 return;
170 }
171 const handled = handledRevealRef.current;
172 if (handled?.path === selectedPath && handled.revealRequestId === revealRequestId) {
173 return;
174 }
175 handledRevealRef.current = { path: selectedPath, revealRequestId };
176 syncingSelectionRef.current = true;
177 for (const path of model.getSelectedPaths()) {
178 if (path !== modelPath) model.getItem(path)?.deselect();
179 }
180 let ancestor = "";
181 for (const segment of modelPath.split("/").slice(0, -1)) {
182 ancestor += `${segment}/`;
183 const directory = model.getItem(ancestor);
184 if (directory !== null && "expand" in directory) directory.expand();
185 }
186 item.select();
187 model.scrollToPath(modelPath, { offset: "nearest" });
188 queueMicrotask(() => {
189 syncingSelectionRef.current = false;
190 });
191 }, [model, presented, revealRequestId, selectedPath]);
192​
193 return (
194 <div className={cn("flex min-h-0 flex-1 flex-col bg-background", className)}>
195 <div
196 className="flex h-10 min-h-10 shrink-0 items-center gap-1 border-b border-border/60 bg-background px-2 text-xs text-muted-foreground in-data-[preview-panel-mode=inline]:mb-3 in-data-[preview-panel-mode=inline]:h-7 in-data-[preview-panel-mode=inline]:min-h-7 in-data-[preview-panel-mode=inline]:border-b-transparent"
197 data-surface-subheader
198 >
199 <span className="px-1 font-medium text-foreground">
200 <T>Files</T>
201 </span>
202 <span className="ml-auto tabular-nums">{entries.length}</span>
203 {headerAccessory}
204 {directoryPaths.length > 0 ? (
205 <Tooltip>
206 <TooltipTrigger
207 render={
208 <Button
209 type="button"
210 size="icon-xs"
211 variant="ghost"
212 aria-label={
213 allDirectoriesExpanded ? gt("Collapse all folders") : gt("Expand all folders")
214 }
215 onClick={() =>
216 setAllDirectoriesExpanded(model, directoryPaths, !allDirectoriesExpanded)
217 }
218 />
219 }
220 >
221 {allDirectoriesExpanded ? (
222 <ChevronsDownUpIcon className="size-3.5" />
223 ) : (
224 <ChevronsUpDownIcon className="size-3.5" />
225 )}
226 </TooltipTrigger>
227 <TooltipPopup>
228 {allDirectoriesExpanded ? gt("Collapse all folders") : gt("Expand all folders")}
229 </TooltipPopup>
230 </Tooltip>
231 ) : null}
232 </div>
233 <FileTree
234 model={model}
235 aria-label={ariaLabel}
236 onClickCapture={(event) => {
237 if (
238 event.defaultPrevented ||
239 event.button !== 0 ||
240 event.ctrlKey ||
241 event.metaKey ||
242 event.shiftKey ||
243 event.altKey
244 ) {
245 return;
246 }
247 // Pierre emits no change for its sole selected row; read before the click to avoid double reveals.
248 const selected = model.getSelectedPaths();
249 const path = selected.length === 1 ? selected[0] : undefined;
250 if (!path || !modelPaths.includes(path)) return;
251 const clickedSelectedRow = event.nativeEvent
252 .composedPath()
253 .some(
254 (node) => node instanceof HTMLElement && node.getAttribute("data-item-path") === path,
255 );
256 if (clickedSelectedRow) onSelectFile(presented.selectionPath(path));
257 }}
258 className="min-h-0 flex-1 overflow-hidden"
259 style={pierreTreeStyle(resolvedTheme)}
260 onPointerOver={titleClippedPierreTreeRow}
261 />
262 {footer}
263 </div>
264 );