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