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