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 { T3_PIERRE_ICONS } from "~/pierre-icons";
10import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme";
11
12import { areAllDirectoriesExpanded, setAllDirectoriesExpanded } from "../files/fileTreeExpansion";
13import { Button } from "../ui/button";
14import { MorphIcon } from "~/components/MorphIcon";
15import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
16import {
17 buildDiffFileTreeUpdates,
18 compareDiffFileTreeEntries,
19 collectDirectoryPaths,
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 directoryPaths = collectDirectoryPaths(paths);
50 const positions = diffFileTreePositions(paths);
51 const [ordering] = useState(() => {
52 let currentPositions: ReadonlyMap<string, number> = new Map();
53 return {
54 sort: compareDiffFileTreeEntries(() => currentPositions),
55 update: (nextPositions: ReadonlyMap<string, number>) => {
56 currentPositions = nextPositions;
57 },
58 };
59 });
60 const gitStatus: ReadonlyArray<GitStatusEntry> = entries.map((entry) => ({
61 path: entry.path,
62 status: entry.status,
63 }));
64 const syncingSelectionRef = useRef(false);
65 const handledRevealRef = useRef<{ path: string; revealRequestId: number } | null>(null);
66 const mountedPathsRef = useRef<ReadonlyArray<string> | null>(null);
67
68 // The tree model keeps the first selection handler it was given.
69 const handleSelectionChange = useStableCallback((selectedPaths: ReadonlyArray<string>) => {
70 if (syncingSelectionRef.current) return;
71 const path = selectedPaths.at(-1)?.replace(/\/$/, "");
72 if (path && paths.includes(path)) onSelectFile(path);
73 });
74
75 const { model } = useFileTree({
76 density: "compact",
77 flattenEmptyDirectories: true,
78 initialExpansion: "open",
79 icons: T3_PIERRE_ICONS,
80 onSelectionChange: handleSelectionChange,
81 paths: [],
82 search: false,
83 sort: ordering.sort,
84 unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
85 });
86 const allDirectoriesExpanded = useFileTreeSelector(model, (currentModel) =>
87 areAllDirectoriesExpanded(currentModel, directoryPaths),
88 );
89
90 useEffect(() => {
91 ordering.update(positions);
92 const mountedPaths = mountedPathsRef.current;
93 if (mountedPaths === paths) return;
94 mountedPathsRef.current = paths;
95 if (mountedPaths === null) {
96 model.resetPaths(paths);
97 } else if (mountedPaths.every((path, index) => paths[index] === path)) {
98 const updates = buildDiffFileTreeUpdates(mountedPaths, paths);
99 if (updates.length > 0) model.batch(updates);
100 } else {
101 // A refreshed diff can change the rank of existing siblings. Mutations do not reorder
102 // those rows, so rebuild while carrying the reader's folder expansion forward.
103 const collapsedDirectories = directoryPaths.filter((path) => {
104 const directory = model.getItem(path);
105 return directory !== null && "isExpanded" in directory && !directory.isExpanded();
106 });
107 model.resetPaths(paths);
108 for (const path of collapsedDirectories) {
109 const directory = model.getItem(path);
110 if (directory !== null && "collapse" in directory) directory.collapse();
111 }
112 }
113 model.setGitStatus(gitStatus);
114 }, [directoryPaths, gitStatus, model, ordering, paths, positions]);
115
116 useEffect(() => {
117 if (selectedPath === null) {
118 handledRevealRef.current = null;
119 return;
120 }
121 const item = model.getItem(selectedPath);
122 if (item === null || item.isDirectory()) {
123 handledRevealRef.current = null;
124 return;
125 }
126 const handled = handledRevealRef.current;
127 if (handled?.path === selectedPath && handled.revealRequestId === revealRequestId) return;
128 handledRevealRef.current = { path: selectedPath, revealRequestId };
129 syncingSelectionRef.current = true;
130 for (const path of model.getSelectedPaths()) {
131 if (path !== selectedPath) model.getItem(path)?.deselect();
132 }
133 let ancestor = "";
134 for (const segment of selectedPath.split("/").slice(0, -1)) {
135 ancestor += `${segment}/`;
136 const directory = model.getItem(ancestor);
137 if (directory !== null && "expand" in directory) directory.expand();
138 }
139 item.select();
140 model.scrollToPath(selectedPath, { offset: "nearest" });
141 queueMicrotask(() => {
142 syncingSelectionRef.current = false;
143 });
144 }, [
145 model,
146 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A file that arrives after it was asked for is still revealed.
147 paths,
148 revealRequestId,
149 selectedPath,
150 ]);
151
152 return (
153 <div className={cn("flex min-h-0 flex-1 flex-col bg-background", className)}>
154 <div
155 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"
156 data-surface-subheader
157 >
158 <span className="px-1 font-medium text-foreground">Files</span>
159 <span className="ml-auto tabular-nums">{entries.length}</span>
160 {headerAccessory}
161 {directoryPaths.length > 0 ? (
162 <Tooltip>
163 <TooltipTrigger
164 render={
165 <Button
166 type="button"
167 size="icon-xs"
168 variant="ghost"
169 aria-label={
170 allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"
171 }
172 onClick={() =>
173 setAllDirectoriesExpanded(model, directoryPaths, !allDirectoriesExpanded)
174 }
175 />
176 }
177 >
178 <MorphIcon
179 className="size-3.5"
180 icon={allDirectoriesExpanded ? ChevronsDownUp : ChevronsUpDown}
181 />
182 </TooltipTrigger>
183 <TooltipPopup>
184 {allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
185 </TooltipPopup>
186 </Tooltip>
187 ) : null}
188 </div>
189 <FileTree
190 model={model}
191 aria-label={ariaLabel}
192 onClickCapture={(event) => {
193 if (
194 event.defaultPrevented ||
195 event.button !== 0 ||
196 event.ctrlKey ||
197 event.metaKey ||
198 event.shiftKey ||
199 event.altKey
200 ) {
201 return;
202 }
203 // Pierre does not emit a selection change for its sole selected row.
204 // Read selection before the row handles the click so new selections reveal only once.
205 const selected = model.getSelectedPaths();
206 const path = selected.length === 1 ? selected[0] : undefined;
207 if (!path || !paths.includes(path)) return;
208 const clickedSelectedRow = event.nativeEvent
209 .composedPath()
210 .some(
211 (node) => node instanceof HTMLElement && node.getAttribute("data-item-path") === path,
212 );
213 if (clickedSelectedRow) onSelectFile(path);
214 }}
215 className="min-h-0 flex-1 overflow-hidden"
216 style={pierreTreeStyle(resolvedTheme)}
217 />
218 {footer}
219 </div>
220 );
221}