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