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, 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 collectDirectoryPaths,
17 type DiffFileTreeEntry,
18} from "./diffFileTree.logic";
19
20export type { DiffFileTreeEntry } from "./diffFileTree.logic";
21
22interface DiffFileTreeProps {
23 readonly entries: ReadonlyArray<DiffFileTreeEntry>;
24 /** Called with the file's path when the reader picks a file row. */
25 readonly onSelectFile: (path: string) => void;
26 /**
27 * The file the diff is currently showing, kept selected in the tree. Bump `revealRequestId` to
28 * scroll the tree to the same path again.
29 */
30 readonly selectedPath?: string | null;
31 readonly revealRequestId?: number;
32 readonly ariaLabel: string;
33 /** Right-aligned content in the header row, after the file count. */
34 readonly headerAccessory?: ReactNode;
35 /** Rendered under the tree, for a host that still has files to fetch. */
36 readonly footer?: ReactNode;
37 readonly className?: string;
38}
39
40/**
41 * A directory tree of the files in a diff. Every directory starts open: a diff is a short list
42 * compared to a workspace, and the reader came for the files, not the folders.
43 */
44export function DiffFileTree({
45 entries,
46 onSelectFile,
47 selectedPath = null,
48 revealRequestId = 0,
49 ariaLabel,
50 headerAccessory,
51 footer,
52 className,
53}: DiffFileTreeProps) {
54 const { resolvedTheme } = useTheme();
55 const paths = useMemo(() => entries.map((entry) => entry.path), [entries]);
56 const directoryPaths = useMemo(() => collectDirectoryPaths(paths), [paths]);
57 const gitStatus = useMemo<ReadonlyArray<GitStatusEntry>>(
58 () => entries.map((entry) => ({ path: entry.path, status: entry.status })),
59 [entries],
60 );
61 const filePathsRef = useRef<ReadonlySet<string>>(new Set(paths));
62 const onSelectFileRef = useRef(onSelectFile);
63 // Selection driven by `selectedPath` below is an echo of a file already on screen, not a
64 // request to scroll to it again.
65 const syncingSelectionRef = useRef(false);
66 const handledRevealRef = useRef<{ path: string; revealRequestId: number } | null>(null);
67 const mountedPathsRef = useRef<ReadonlyArray<string> | null>(null);
68
69 useEffect(() => {
70 filePathsRef.current = new Set(paths);
71 onSelectFileRef.current = onSelectFile;
72 }, [onSelectFile, paths]);
73
74 const { model } = useFileTree({
75 density: "compact",
76 flattenEmptyDirectories: true,
77 initialExpansion: "open",
78 icons: T3_PIERRE_ICONS,
79 onSelectionChange: (selectedPaths) => {
80 if (syncingSelectionRef.current) return;
81 const path = selectedPaths.at(-1)?.replace(/\/$/, "");
82 if (path && filePathsRef.current.has(path)) onSelectFileRef.current(path);
83 },
84 paths: [],
85 search: false,
86 unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
87 });
88 const allDirectoriesExpanded = useFileTreeSelector(model, (currentModel) =>
89 areAllDirectoriesExpanded(currentModel, directoryPaths),
90 );
91
92 useEffect(() => {
93 const mountedPaths = mountedPathsRef.current;
94 if (mountedPaths === paths) return;
95 mountedPathsRef.current = paths;
96 if (mountedPaths === null) {
97 model.resetPaths(paths);
98 } else {
99 const updates = buildDiffFileTreeUpdates(mountedPaths, paths);
100 if (updates.length > 0) model.batch(updates);
101 }
102 model.setGitStatus(gitStatus);
103 }, [gitStatus, model, paths]);
104
105 useEffect(() => {
106 if (selectedPath === null) {
107 handledRevealRef.current = null;
108 return;
109 }
110 // A path list that changes under an already-revealed file (a refresh, a later slice) must
111 // not pull the tree back to it over whatever the reader has picked since.
112 const item = model.getItem(selectedPath);
113 if (item === null || item.isDirectory()) {
114 // A file that left the diff has to be revealed again when it comes back.
115 handledRevealRef.current = null;
116 return;
117 }
118 const handled = handledRevealRef.current;
119 if (handled?.path === selectedPath && handled.revealRequestId === revealRequestId) return;
120 handledRevealRef.current = { path: selectedPath, revealRequestId };
121 syncingSelectionRef.current = true;
122 for (const path of model.getSelectedPaths()) {
123 if (path !== selectedPath) model.getItem(path)?.deselect();
124 }
125 let ancestor = "";
126 for (const segment of selectedPath.split("/").slice(0, -1)) {
127 ancestor += `${segment}/`;
128 const directory = model.getItem(ancestor);
129 if (directory !== null && "expand" in directory) directory.expand();
130 }
131 item.select();
132 model.scrollToPath(selectedPath, { offset: "nearest" });
133 queueMicrotask(() => {
134 syncingSelectionRef.current = false;
135 });
136 // `paths` is a dependency so a file that arrives after it was asked for is still revealed.
137 }, [model, paths, revealRequestId, selectedPath]);
138
139 return (
140 <div className={cn("flex min-h-0 flex-1 flex-col bg-background", className)}>
141 <div
142 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"
143 data-surface-subheader
144 >
145 <span className="px-1 font-medium text-foreground">Files</span>
146 <span className="ml-auto tabular-nums">{entries.length}</span>
147 {headerAccessory}
148 {directoryPaths.length > 0 ? (
149 <Tooltip>
150 <TooltipTrigger
151 render={
152 <Button
153 type="button"
154 size="icon-xs"
155 variant="ghost"
156 aria-label={
157 allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"
158 }
159 onClick={() =>
160 setAllDirectoriesExpanded(model, directoryPaths, !allDirectoriesExpanded)
161 }
162 />
163 }
164 >
165 {allDirectoriesExpanded ? (
166 <ChevronsDownUpIcon className="size-3.5" />
167 ) : (
168 <ChevronsUpDownIcon className="size-3.5" />
169 )}
170 </TooltipTrigger>
171 <TooltipPopup>
172 {allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
173 </TooltipPopup>
174 </Tooltip>
175 ) : null}
176 </div>
177 <FileTree
178 model={model}
179 aria-label={ariaLabel}
180 className="min-h-0 flex-1 overflow-hidden"
181 style={pierreTreeStyle(resolvedTheme)}
182 />
183 {footer}
184 </div>
185 );
186}