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, useMemo, useRef, useState, type ReactNode } from "react";
5
6import { useTheme } from "~/hooks/useTheme";
7import { cn } from "~/lib/utils";
8import { T3_PIERRE_ICONS } from "~/pierre-icons";
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 diffFileTreePositions,
19 type DiffFileTreeEntry,
20} from "./diffFileTree.logic";
21
22export type { DiffFileTreeEntry } from "./diffFileTree.logic";
23
24interface DiffFileTreeProps {
25 readonly entries: ReadonlyArray<DiffFileTreeEntry>;
26 /** Called with the file's path when the reader picks a file row. */
27 readonly onSelectFile: (path: string) => void;
28 /**
29 * The file the diff is currently showing, kept selected in the tree. Bump `revealRequestId` to
30 * scroll the tree to the same path again.
31 */
32 readonly selectedPath?: string | null;
33 readonly revealRequestId?: number;
34 readonly ariaLabel: string;
35 /** Right-aligned content in the header row, after the file count. */
36 readonly headerAccessory?: ReactNode;
37 /** Rendered under the tree, for a host that still has files to fetch. */
38 readonly footer?: ReactNode;
39 readonly className?: string;
40}
41
42/**
43 * A directory tree of the files in a diff. Every directory starts open: a diff is a short list
44 * compared to a workspace, and the reader came for the files, not the folders.
45 */
46export function DiffFileTree({
47 entries,
48 onSelectFile,
49 selectedPath = null,
50 revealRequestId = 0,
51 ariaLabel,
52 headerAccessory,
53 footer,
54 className,
55}: DiffFileTreeProps) {
56 const { resolvedTheme } = useTheme();
57 const paths = useMemo(() => entries.map((entry) => entry.path), [entries]);
58 const directoryPaths = useMemo(() => collectDirectoryPaths(paths), [paths]);
59 const positions = useMemo(() => diffFileTreePositions(paths), [paths]);
60 const [ordering] = useState(() => {
61 let currentPositions: ReadonlyMap<string, number> = new Map();
62 return {
63 sort: compareDiffFileTreeEntries(() => currentPositions),
64 update: (nextPositions: ReadonlyMap<string, number>) => {
65 currentPositions = nextPositions;
66 },
67 };
68 });
69 const gitStatus = useMemo<ReadonlyArray<GitStatusEntry>>(
70 () => entries.map((entry) => ({ path: entry.path, status: entry.status })),
71 [entries],
72 );
73 const filePathsRef = useRef<ReadonlySet<string>>(new Set(paths));
74 const onSelectFileRef = useRef(onSelectFile);
75 // Selection driven by `selectedPath` below is an echo of a file already on screen, not a
76 // request to scroll to it again.
77 const syncingSelectionRef = useRef(false);
78 const handledRevealRef = useRef<{ path: string; revealRequestId: number } | null>(null);
79 const mountedPathsRef = useRef<ReadonlyArray<string> | null>(null);
80
81 useEffect(() => {
82 filePathsRef.current = new Set(paths);
83 onSelectFileRef.current = onSelectFile;
84 }, [onSelectFile, paths]);
85
86 const { model } = useFileTree({
87 density: "compact",
88 flattenEmptyDirectories: true,
89 initialExpansion: "open",
90 icons: T3_PIERRE_ICONS,
91 onSelectionChange: (selectedPaths) => {
92 if (syncingSelectionRef.current) return;
93 const path = selectedPaths.at(-1)?.replace(/\/$/, "");
94 if (path && filePathsRef.current.has(path)) onSelectFileRef.current(path);
95 },
96 paths: [],
97 search: false,
98 sort: ordering.sort,
99 unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
100 });
101 const allDirectoriesExpanded = useFileTreeSelector(model, (currentModel) =>
102 areAllDirectoriesExpanded(currentModel, directoryPaths),
103 );
104
105 useEffect(() => {
106 ordering.update(positions);
107 const mountedPaths = mountedPathsRef.current;
108 if (mountedPaths === paths) return;
109 mountedPathsRef.current = paths;
110 if (mountedPaths === null) {
111 model.resetPaths(paths);
112 } else if (mountedPaths.every((path, index) => paths[index] === path)) {
113 // PR slices only append files, so keep the existing tree and its open folders.
114 const updates = buildDiffFileTreeUpdates(mountedPaths, paths);
115 if (updates.length > 0) model.batch(updates);
116 } else {
117 // A refreshed diff can change the rank of existing siblings. Mutations do not reorder
118 // those rows, so rebuild while carrying the reader's folder expansion forward.
119 const collapsedDirectories = directoryPaths.filter((path) => {
120 const directory = model.getItem(path);
121 return directory !== null && "isExpanded" in directory && !directory.isExpanded();
122 });
123 model.resetPaths(paths);
124 for (const path of collapsedDirectories) {
125 const directory = model.getItem(path);
126 if (directory !== null && "collapse" in directory) directory.collapse();
127 }
128 }
129 model.setGitStatus(gitStatus);
130 }, [directoryPaths, gitStatus, model, ordering, paths, positions]);
131
132 useEffect(() => {
133 if (selectedPath === null) {
134 handledRevealRef.current = null;
135 return;
136 }
137 // A path list that changes under an already-revealed file (a refresh, a later slice) must
138 // not pull the tree back to it over whatever the reader has picked since.
139 const item = model.getItem(selectedPath);
140 if (item === null || item.isDirectory()) {
141 // A file that left the diff has to be revealed again when it comes back.
142 handledRevealRef.current = null;
143 return;
144 }
145 const handled = handledRevealRef.current;
146 if (handled?.path === selectedPath && handled.revealRequestId === revealRequestId) return;
147 handledRevealRef.current = { path: selectedPath, revealRequestId };
148 syncingSelectionRef.current = true;
149 for (const path of model.getSelectedPaths()) {
150 if (path !== selectedPath) model.getItem(path)?.deselect();
151 }
152 let ancestor = "";
153 for (const segment of selectedPath.split("/").slice(0, -1)) {
154 ancestor += `${segment}/`;
155 const directory = model.getItem(ancestor);
156 if (directory !== null && "expand" in directory) directory.expand();
157 }
158 item.select();
159 model.scrollToPath(selectedPath, { offset: "nearest" });
160 queueMicrotask(() => {
161 syncingSelectionRef.current = false;
162 });
163 // `paths` is a dependency so a file that arrives after it was asked for is still revealed.
164 }, [model, paths, revealRequestId, selectedPath]);
165
166 return (
167 <div className={cn("flex min-h-0 flex-1 flex-col bg-background", className)}>
168 <div
169 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"
170 data-surface-subheader
171 >
172 <span className="px-1 font-medium text-foreground">Files</span>
173 <span className="ml-auto tabular-nums">{entries.length}</span>
174 {headerAccessory}
175 {directoryPaths.length > 0 ? (
176 <Tooltip>
177 <TooltipTrigger
178 render={
179 <Button
180 type="button"
181 size="icon-xs"
182 variant="ghost"
183 aria-label={
184 allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"
185 }
186 onClick={() =>
187 setAllDirectoriesExpanded(model, directoryPaths, !allDirectoriesExpanded)
188 }
189 />
190 }
191 >
192 {allDirectoriesExpanded ? (
193 <ChevronsDownUpIcon className="size-3.5" />
194 ) : (
195 <ChevronsUpDownIcon className="size-3.5" />
196 )}
197 </TooltipTrigger>
198 <TooltipPopup>
199 {allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
200 </TooltipPopup>
201 </Tooltip>
202 ) : null}
203 </div>
204 <FileTree
205 model={model}
206 aria-label={ariaLabel}
207 onClickCapture={(event) => {
208 if (
209 event.defaultPrevented ||
210 event.button !== 0 ||
211 event.ctrlKey ||
212 event.metaKey ||
213 event.shiftKey ||
214 event.altKey
215 ) {
216 return;
217 }
218 // Pierre does not emit a selection change for its sole selected row.
219 // Read selection before the row handles the click so new selections reveal only once.
220 const selected = model.getSelectedPaths();
221 const path = selected.length === 1 ? selected[0] : undefined;
222 if (!path || !filePathsRef.current.has(path)) return;
223 const clickedSelectedRow = event.nativeEvent
224 .composedPath()
225 .some(
226 (node) => node instanceof HTMLElement && node.getAttribute("data-item-path") === path,
227 );
228 if (clickedSelectedRow) onSelectFileRef.current(path);
229 }}
230 className="min-h-0 flex-1 overflow-hidden"
231 style={pierreTreeStyle(resolvedTheme)}
232 />
233 {footer}
234 </div>
235 );
236}