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 useEffect(() => {
99 model.setIcons(icons);
100 }, [icons, model]);
101
102 useEffect(() => {
103 ordering.update(positions);
104 const mounted = mountedPresentationRef.current;
105 if (mounted?.paths === modelPaths) return;
106 mountedPresentationRef.current = presented;
107 if (mounted === null) {
108 model.resetPaths(modelPaths);
109 } else if (mounted.paths.every((path, index) => modelPaths[index] === path)) {
110 const updates = buildDiffFileTreeUpdates(mounted.paths, modelPaths);
111 if (updates.length > 0) model.batch(updates);
112 } else {
113 // A reset can turn a file path into a directory. Carry selection and focus
114 // through real paths so paging keeps the same file without revealing it again.
115 const focusedPath = model.getFocusedPath();
116 const nextFocusedPath =
117 focusedPath === null ? null : presented.modelPath(mounted.selectionPath(focusedPath));
118 const selectedPaths = model
119 .getSelectedPaths()
120 .map((path) => presented.modelPath(mounted.selectionPath(path)))
121 .filter((path) => path.endsWith("/") || modelPaths.includes(path));
122 const collapsedDirectories = directoryPaths.filter((path) => {
123 const directory = model.getItem(path);
124 return directory !== null && "isExpanded" in directory && !directory.isExpanded();
125 });
126 syncingSelectionRef.current = true;
127 model.resetPaths(modelPaths);
128 for (const path of model.getSelectedPaths()) model.getItem(path)?.deselect();
129 for (const path of selectedPaths) model.getItem(path)?.select();
130 queueMicrotask(() => {
131 syncingSelectionRef.current = false;
132 });
133 for (const path of collapsedDirectories) {
134 const directory = model.getItem(path);
135 if (directory !== null && "collapse" in directory) directory.collapse();
136 }
137 if (
138 nextFocusedPath !== null &&
139 (modelPaths.includes(nextFocusedPath) || directoryPaths.includes(nextFocusedPath))
140 ) {
141 model.focusPath(nextFocusedPath);
142 }
143 }
144 model.setGitStatus(gitStatus);
145 }, [directoryPaths, gitStatus, model, modelPaths, ordering, positions, presented]);
146
147 useEffect(() => {
148 if (selectedPath === null) {
149 handledRevealRef.current = null;
150 return;
151 }
152 const modelPath = presented.modelPath(selectedPath);
153 const item = model.getItem(modelPath);
154 if (item === null || item.isDirectory()) {
155 handledRevealRef.current = null;
156 return;
157 }
158 const handled = handledRevealRef.current;
159 if (handled?.path === selectedPath && handled.revealRequestId === revealRequestId) {
160 return;
161 }
162 handledRevealRef.current = { path: selectedPath, revealRequestId };
163 syncingSelectionRef.current = true;
164 for (const path of model.getSelectedPaths()) {
165 if (path !== modelPath) model.getItem(path)?.deselect();
166 }
167 let ancestor = "";
168 for (const segment of modelPath.split("/").slice(0, -1)) {
169 ancestor += `${segment}/`;
170 const directory = model.getItem(ancestor);
171 if (directory !== null && "expand" in directory) directory.expand();
172 }
173 item.select();
174 model.scrollToPath(modelPath, { offset: "nearest" });
175 queueMicrotask(() => {
176 syncingSelectionRef.current = false;
177 });
178 }, [model, presented, revealRequestId, selectedPath]);
179
180 return (
181 <div className={cn("flex min-h-0 flex-1 flex-col bg-background", className)}>
182 <div
183 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"
184 data-surface-subheader
185 >
186 <span className="px-1 font-medium text-foreground">Files</span>
187 <span className="ml-auto tabular-nums">{entries.length}</span>
188 {headerAccessory}
189 {directoryPaths.length > 0 ? (
190 <Tooltip>
191 <TooltipTrigger
192 render={
193 <Button
194 type="button"
195 size="icon-xs"
196 variant="ghost"
197 aria-label={
198 allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"
199 }
200 onClick={() =>
201 setAllDirectoriesExpanded(model, directoryPaths, !allDirectoriesExpanded)
202 }
203 />
204 }
205 >
206 <MorphIcon
207 className="size-3.5"
208 icon={allDirectoriesExpanded ? ChevronsDownUp : ChevronsUpDown}
209 />
210 </TooltipTrigger>
211 <TooltipPopup>
212 {allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
213 </TooltipPopup>
214 </Tooltip>
215 ) : null}
216 </div>
217 <FileTree
218 model={model}
219 aria-label={ariaLabel}
220 onClickCapture={(event) => {
221 if (
222 event.defaultPrevented ||
223 event.button !== 0 ||
224 event.ctrlKey ||
225 event.metaKey ||
226 event.shiftKey ||
227 event.altKey
228 ) {
229 return;
230 }
231 // Pierre emits no change for its sole selected row; read before the click to avoid double reveals.
232 const selected = model.getSelectedPaths();
233 const path = selected.length === 1 ? selected[0] : undefined;
234 if (!path || !modelPaths.includes(path)) return;
235 const clickedSelectedRow = event.nativeEvent
236 .composedPath()
237 .some(
238 (node) => node instanceof HTMLElement && node.getAttribute("data-item-path") === path,
239 );
240 if (clickedSelectedRow) onSelectFile(presented.selectionPath(path));
241 }}
242 className="min-h-0 flex-1 overflow-hidden"
243 style={pierreTreeStyle(resolvedTheme)}
244 />
245 {footer}
246 </div>
247 );
248}