Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DiffFileTree.tsx

219 lines8.3 KB

1import type { GitStatusEntry } from "@pierre/trees";
2import { FileTree, useFileTree, useFileTreeSelector } from "@pierre/trees/react";
3import { ChevronsDownUp, ChevronsUpDown } from "lucide";
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 { MorphIcon } from "~/components/MorphIcon";
14import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
15import {
16 buildDiffFileTreeUpdates,
17 compareDiffFileTreeEntries,
18 collectDirectoryPaths,
19 diffFileTreePositions,
20 type DiffFileTreeEntry,
21} from "./diffFileTree.logic";
22​
23export type { DiffFileTreeEntry } from "./diffFileTree.logic";
24​
25interface DiffFileTreeProps {
26 readonly entries: ReadonlyArray<DiffFileTreeEntry>;
27 readonly onSelectFile: (path: string) => void;
28 readonly selectedPath?: string | null;
29 readonly revealRequestId?: number;
30 readonly ariaLabel: string;
31 readonly headerAccessory?: ReactNode;
32 readonly footer?: ReactNode;
33 readonly className?: string;
35​
36export function DiffFileTree({
37 entries,
38 onSelectFile,
39 selectedPath = null,
40 revealRequestId = 0,
41 ariaLabel,
42 headerAccessory,
43 footer,
44 className,
45}: DiffFileTreeProps) {
46 const { resolvedTheme } = useTheme();
47 const paths = useMemo(() => entries.map((entry) => entry.path), [entries]);
48 const directoryPaths = useMemo(() => collectDirectoryPaths(paths), [paths]);
49 const positions = useMemo(() => diffFileTreePositions(paths), [paths]);
50 const [ordering] = useState(() => {
51 let currentPositions: ReadonlyMap<string, number> = new Map();
52 return {
53 sort: compareDiffFileTreeEntries(() => currentPositions),
54 update: (nextPositions: ReadonlyMap<string, number>) => {
55 currentPositions = nextPositions;
56 },
57 };
58 });
59 const gitStatus = useMemo<ReadonlyArray<GitStatusEntry>>(
60 () => entries.map((entry) => ({ path: entry.path, status: entry.status })),
61 [entries],
62 );
63 const filePathsRef = useRef<ReadonlySet<string>>(new Set(paths));
64 const onSelectFileRef = useRef(onSelectFile);
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 sort: ordering.sort,
87 unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
88 });
89 const allDirectoriesExpanded = useFileTreeSelector(model, (currentModel) =>
90 areAllDirectoriesExpanded(currentModel, directoryPaths),
91 );
92​
93 useEffect(() => {
94 ordering.update(positions);
95 const mountedPaths = mountedPathsRef.current;
96 if (mountedPaths === paths) return;
97 mountedPathsRef.current = paths;
98 if (mountedPaths === null) {
99 model.resetPaths(paths);
100 } else if (mountedPaths.every((path, index) => paths[index] === path)) {
101 const updates = buildDiffFileTreeUpdates(mountedPaths, paths);
102 if (updates.length > 0) model.batch(updates);
103 } else {
104 // A refreshed diff can change the rank of existing siblings. Mutations do not reorder
105 // those rows, so rebuild while carrying the reader's folder expansion forward.
106 const collapsedDirectories = directoryPaths.filter((path) => {
107 const directory = model.getItem(path);
108 return directory !== null && "isExpanded" in directory && !directory.isExpanded();
109 });
110 model.resetPaths(paths);
111 for (const path of collapsedDirectories) {
112 const directory = model.getItem(path);
113 if (directory !== null && "collapse" in directory) directory.collapse();
114 }
115 }
116 model.setGitStatus(gitStatus);
117 }, [directoryPaths, gitStatus, model, ordering, paths, positions]);
118​
119 useEffect(() => {
120 if (selectedPath === null) {
121 handledRevealRef.current = null;
122 return;
123 }
124 const item = model.getItem(selectedPath);
125 if (item === null || item.isDirectory()) {
126 handledRevealRef.current = null;
127 return;
128 }
129 const handled = handledRevealRef.current;
130 if (handled?.path === selectedPath && handled.revealRequestId === revealRequestId) return;
131 handledRevealRef.current = { path: selectedPath, revealRequestId };
132 syncingSelectionRef.current = true;
133 for (const path of model.getSelectedPaths()) {
134 if (path !== selectedPath) model.getItem(path)?.deselect();
135 }
136 let ancestor = "";
137 for (const segment of selectedPath.split("/").slice(0, -1)) {
138 ancestor += `${segment}/`;
139 const directory = model.getItem(ancestor);
140 if (directory !== null && "expand" in directory) directory.expand();
141 }
142 item.select();
143 model.scrollToPath(selectedPath, { offset: "nearest" });
144 queueMicrotask(() => {
145 syncingSelectionRef.current = false;
146 });
147 // `paths` is a dependency so a file that arrives after it was asked for is still revealed.
148 }, [model, paths, revealRequestId, selectedPath]);
149​
150 return (
151 <div className={cn("flex min-h-0 flex-1 flex-col bg-background", className)}>
152 <div
153 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"
154 data-surface-subheader
155 >
156 <span className="px-1 font-medium text-foreground">Files</span>
157 <span className="ml-auto tabular-nums">{entries.length}</span>
158 {headerAccessory}
159 {directoryPaths.length > 0 ? (
160 <Tooltip>
161 <TooltipTrigger
162 render={
163 <Button
164 type="button"
165 size="icon-xs"
166 variant="ghost"
167 aria-label={
168 allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"
169 }
170 onClick={() =>
171 setAllDirectoriesExpanded(model, directoryPaths, !allDirectoriesExpanded)
172 }
173 />
174 }
175 >
176 <MorphIcon
177 className="size-3.5"
178 icon={allDirectoriesExpanded ? ChevronsDownUp : ChevronsUpDown}
179 />
180 </TooltipTrigger>
181 <TooltipPopup>
182 {allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
183 </TooltipPopup>
184 </Tooltip>
185 ) : null}
186 </div>
187 <FileTree
188 model={model}
189 aria-label={ariaLabel}
190 onClickCapture={(event) => {
191 if (
192 event.defaultPrevented ||
193 event.button !== 0 ||
194 event.ctrlKey ||
195 event.metaKey ||
196 event.shiftKey ||
197 event.altKey
198 ) {
199 return;
200 }
201 // Pierre does not emit a selection change for its sole selected row.
202 // Read selection before the row handles the click so new selections reveal only once.
203 const selected = model.getSelectedPaths();
204 const path = selected.length === 1 ? selected[0] : undefined;
205 if (!path || !filePathsRef.current.has(path)) return;
206 const clickedSelectedRow = event.nativeEvent
207 .composedPath()
208 .some(
209 (node) => node instanceof HTMLElement && node.getAttribute("data-item-path") === path,
210 );
211 if (clickedSelectedRow) onSelectFileRef.current(path);
212 }}
213 className="min-h-0 flex-1 overflow-hidden"
214 style={pierreTreeStyle(resolvedTheme)}
215 />
216 {footer}
217 </div>
218 );