Repository navigation
Expand file tree
/
Copy pathDiffFileTree.tsx
More file actions
251 lines (240 loc) · 9.57 KB
/
Copy pathDiffFileTree.tsx
File metadata and controls
251 lines (240 loc) · 9.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import type { GitStatusEntry } from "@pierre/trees";
import { FileTree, useFileTree, useFileTreeSelector } from "@pierre/trees/react";
import { ChevronsDownUpIcon, ChevronsUpDownIcon } from "lucide-react";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { useStableCallback } from "~/hooks/useStableCallback";
import { useTheme } from "~/hooks/useTheme";
import { cn } from "~/lib/utils";
import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme";
import { areAllDirectoriesExpanded, setAllDirectoriesExpanded } from "../files/fileTreeExpansion";
import { Button } from "../ui/button";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import {
buildDiffFileTreeUpdates,
compareDiffFileTreeEntries,
collectDirectoryPaths,
diffFileTreeModel,
diffFileTreePositions,
type DiffFileTreeEntry,
} from "./diffFileTree.logic";
export type { DiffFileTreeEntry } from "./diffFileTree.logic";
interface DiffFileTreeProps {
readonly entries: ReadonlyArray<DiffFileTreeEntry>;
readonly onSelectFile: (path: string) => void;
readonly selectedPath?: string | null;
readonly revealRequestId?: number;
readonly ariaLabel: string;
readonly headerAccessory?: ReactNode;
readonly footer?: ReactNode;
readonly className?: string;
}
export function DiffFileTree({
entries,
onSelectFile,
selectedPath = null,
revealRequestId = 0,
ariaLabel,
headerAccessory,
footer,
className,
}: DiffFileTreeProps) {
const { resolvedTheme } = useTheme();
const paths = entries.map((entry) => entry.path);
const presented = diffFileTreeModel(paths);
const modelPaths = presented.paths;
const icons = presented.icons;
const directoryPaths = collectDirectoryPaths(modelPaths);
const positions = diffFileTreePositions(modelPaths);
const [ordering] = useState(() => {
let currentPositions: ReadonlyMap<string, number> = new Map();
return {
sort: compareDiffFileTreeEntries(() => currentPositions),
update: (nextPositions: ReadonlyMap<string, number>) => {
currentPositions = nextPositions;
},
};
});
const gitStatus: ReadonlyArray<GitStatusEntry> = entries.map((entry) => ({
path: presented.modelPath(entry.path),
status: entry.status,
}));
const syncingSelectionRef = useRef(false);
const handledRevealRef = useRef<{
path: string;
revealRequestId: number;
} | null>(null);
const mountedPresentationRef = useRef<ReturnType<typeof diffFileTreeModel> | null>(null);
// The tree model keeps the first selection handler it was given.
const handleSelectionChange = useStableCallback((selectedPaths: ReadonlyArray<string>) => {
if (syncingSelectionRef.current) return;
const modelPath = selectedPaths.at(-1);
if (modelPath && modelPaths.includes(modelPath)) {
onSelectFile(presented.selectionPath(modelPath));
}
});
const { model } = useFileTree({
density: "compact",
flattenEmptyDirectories: true,
initialExpansion: "open",
icons,
onSelectionChange: handleSelectionChange,
paths: [],
search: false,
sort: ordering.sort,
unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
});
const allDirectoriesExpanded = useFileTreeSelector(model, (currentModel) =>
areAllDirectoriesExpanded(currentModel, directoryPaths),
);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes the icon set into the imperative Pierre file tree model
useEffect(() => {
model.setIcons(icons);
}, [icons, model]);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- applies path updates, ordering and git status to the imperative Pierre file tree model
useEffect(() => {
ordering.update(positions);
const mounted = mountedPresentationRef.current;
if (mounted?.paths === modelPaths) return;
mountedPresentationRef.current = presented;
if (mounted === null) {
model.resetPaths(modelPaths);
} else if (mounted.paths.every((path, index) => modelPaths[index] === path)) {
const updates = buildDiffFileTreeUpdates(mounted.paths, modelPaths);
if (updates.length > 0) model.batch(updates);
} else {
// A reset can turn a file path into a directory. Carry selection and focus
// through real paths so paging keeps the same file without revealing it again.
const focusedPath = model.getFocusedPath();
const nextFocusedPath =
focusedPath === null ? null : presented.modelPath(mounted.selectionPath(focusedPath));
const selectedPaths = model
.getSelectedPaths()
.map((path) => presented.modelPath(mounted.selectionPath(path)))
.filter((path) => path.endsWith("/") || modelPaths.includes(path));
const collapsedDirectories = directoryPaths.filter((path) => {
const directory = model.getItem(path);
return directory !== null && "isExpanded" in directory && !directory.isExpanded();
});
syncingSelectionRef.current = true;
model.resetPaths(modelPaths);
for (const path of model.getSelectedPaths()) model.getItem(path)?.deselect();
for (const path of selectedPaths) model.getItem(path)?.select();
queueMicrotask(() => {
syncingSelectionRef.current = false;
});
for (const path of collapsedDirectories) {
const directory = model.getItem(path);
if (directory !== null && "collapse" in directory) directory.collapse();
}
if (
nextFocusedPath !== null &&
(modelPaths.includes(nextFocusedPath) || directoryPaths.includes(nextFocusedPath))
) {
model.focusPath(nextFocusedPath);
}
}
model.setGitStatus(gitStatus);
}, [directoryPaths, gitStatus, model, modelPaths, ordering, positions, presented]);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- expands ancestors, selects and scrolls to the requested file in the Pierre tree model
useEffect(() => {
if (selectedPath === null) {
handledRevealRef.current = null;
return;
}
const modelPath = presented.modelPath(selectedPath);
const item = model.getItem(modelPath);
if (item === null || item.isDirectory()) {
handledRevealRef.current = null;
return;
}
const handled = handledRevealRef.current;
if (handled?.path === selectedPath && handled.revealRequestId === revealRequestId) {
return;
}
handledRevealRef.current = { path: selectedPath, revealRequestId };
syncingSelectionRef.current = true;
for (const path of model.getSelectedPaths()) {
if (path !== modelPath) model.getItem(path)?.deselect();
}
let ancestor = "";
for (const segment of modelPath.split("/").slice(0, -1)) {
ancestor += `${segment}/`;
const directory = model.getItem(ancestor);
if (directory !== null && "expand" in directory) directory.expand();
}
item.select();
model.scrollToPath(modelPath, { offset: "nearest" });
queueMicrotask(() => {
syncingSelectionRef.current = false;
});
}, [model, presented, revealRequestId, selectedPath]);
return (
<div className={cn("flex min-h-0 flex-1 flex-col bg-background", className)}>
<div
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"
data-surface-subheader
>
<span className="px-1 font-medium text-foreground">Files</span>
<span className="ml-auto tabular-nums">{entries.length}</span>
{headerAccessory}
{directoryPaths.length > 0 ? (
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
size="icon-xs"
variant="ghost"
aria-label={
allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"
}
onClick={() =>
setAllDirectoriesExpanded(model, directoryPaths, !allDirectoriesExpanded)
}
/>
}
>
{allDirectoriesExpanded ? (
<ChevronsDownUpIcon className="size-3.5" />
) : (
<ChevronsUpDownIcon className="size-3.5" />
)}
</TooltipTrigger>
<TooltipPopup>
{allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
</TooltipPopup>
</Tooltip>
) : null}
</div>
<FileTree
model={model}
aria-label={ariaLabel}
onClickCapture={(event) => {
if (
event.defaultPrevented ||
event.button !== 0 ||
event.ctrlKey ||
event.metaKey ||
event.shiftKey ||
event.altKey
) {
return;
}
// Pierre emits no change for its sole selected row; read before the click to avoid double reveals.
const selected = model.getSelectedPaths();
const path = selected.length === 1 ? selected[0] : undefined;
if (!path || !modelPaths.includes(path)) return;
const clickedSelectedRow = event.nativeEvent
.composedPath()
.some(
(node) => node instanceof HTMLElement && node.getAttribute("data-item-path") === path,
);
if (clickedSelectedRow) onSelectFile(presented.selectionPath(path));
}}
className="min-h-0 flex-1 overflow-hidden"
style={pierreTreeStyle(resolvedTheme)}
/>
{footer}
</div>
);
}