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

FileBrowserPanel.tsx

426 lines15.6 KB

1import { RefreshIcon } from "~/components/ui/refresh-icon";
2import type {
3 ContextMenuItem as TreeContextMenuItem,
4 ContextMenuOpenContext as TreeContextMenuOpenContext,
5} from "@pierre/trees";
6import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
7import { FileTree, useFileTree, useFileTreeSearch, useFileTreeSelector } from "@pierre/trees/react";
8import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
9import { ChevronsDownUpIcon, ChevronsUpDownIcon } from "lucide-react";
10import { useEffect, useMemo, useRef } from "react";
11​
12import { Button } from "~/components/ui/button";
13import { InputGroup, InputGroupInput } from "~/components/ui/input-group";
14import { toastManager } from "~/components/ui/toast";
15import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
16import { useComposerHandleContext } from "~/composerHandleContext";
17import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
18import { useTheme } from "~/hooks/useTheme";
19import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";
20import { readLocalApi } from "~/localApi";
21import { T3_PIERRE_ICONS } from "~/pierre-icons";
22import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme";
23​
24import { createFileTreeDragMentionController } from "./fileTreeDragMention";
25import { areAllDirectoriesExpanded, setAllDirectoriesExpanded } from "./fileTreeExpansion";
26import { buildFileTreePathUpdates } from "./fileTreePathReconciliation";
27import { useProjectEntriesQuery } from "./projectFilesQueryState";
28​
29interface FileBrowserPanelProps {
30 environmentId: EnvironmentId;
31 cwd: string;
32 projectName: string;
33 /** File currently open in the preview pane; revealed and selected in the tree. */
34 selectedPath: string | null;
35 /** Bumped when the same path should be revealed again (e.g. re-opened from search). */
36 selectedPathRevealId: number;
37 onOpenFile: (relativePath: string) => void;
38 onRefreshSelectedFile?: () => void;
39 workspaceMutationId: string | null;
41​
42function treePath(entry: ProjectEntry): string {
43 return entry.kind === "directory" ? `${entry.path}/` : entry.path;
45​
46function RefreshFilesButton(props: { isPending: boolean; onRefresh: () => void }) {
47 return (
48 <Tooltip>
49 <TooltipTrigger
50 render={
51 <Button
52 type="button"
53 variant="ghost"
54 size="icon-xs"
55 aria-label="Refresh workspace files"
56 onClick={props.onRefresh}
57 />
58 }
59 >
60 <RefreshIcon refreshing={props.isPending} />
61 </TooltipTrigger>
62 <TooltipPopup>{props.isPending ? "Refreshing…" : "Refresh files"}</TooltipPopup>
63 </Tooltip>
64 );
66​
67function FileSearchField(props: {
68 ariaLabel: string;
69 name: string;
70 onClose: () => void;
71 onValueChange: (value: string) => void;
72 value: string;
73}) {
74 return (
75 <InputGroup variant="ghost" className="h-7 min-w-0 flex-1">
76 <InputGroupInput
77 type="search"
78 name={props.name}
79 size="sm"
80 value={props.value}
81 aria-label={props.ariaLabel}
82 placeholder="Search files"
83 spellCheck={false}
84 onChange={(event) => props.onValueChange(event.target.value)}
85 onKeyDown={(event) => {
86 if (event.key !== "Escape") return;
87 props.onClose();
88 event.currentTarget.blur();
89 }}
90 />
91 </InputGroup>
92 );
94​
95export default function FileBrowserPanel({
96 environmentId,
97 cwd,
98 projectName,
99 selectedPath,
100 selectedPathRevealId,
101 onOpenFile,
102 onRefreshSelectedFile,
103 workspaceMutationId,
104}: FileBrowserPanelProps) {
105 const { resolvedTheme } = useTheme();
106 const composerRef = useComposerHandleContext();
107 const entriesQuery = useProjectEntriesQuery(environmentId, cwd);
108 const entries = entriesQuery.data?.entries ?? [];
109 const entryKinds = useMemo(
110 () => new Map(entries.map((entry) => [entry.path, entry.kind] as const)),
111 [entries],
112 );
113 const entryKindsRef = useRef<ReadonlyMap<string, ProjectEntry["kind"]>>(entryKinds);
114 const treePaths = useMemo(() => entries.map(treePath), [entries]);
115 const directoryPaths = useMemo(
116 () => entries.filter((entry) => entry.kind === "directory").map(treePath),
117 [entries],
118 );
119 const previousTreePathsRef = useRef<readonly string[] | null>(null);
120 const syncingSelectionRef = useRef(false);
121 const treeSelectionPathRef = useRef<string | null>(null);
122 const handledRevealRef = useRef<{ path: string; revealId: number } | null>(null);
123​
124 // The tree renders rows in shadow DOM and its anchor rect is unreliable, so
125 // capture the right-click position ourselves; contextmenu is a composed
126 // event, so a capture-phase listener sees it with viewport coordinates.
127 const contextMenuPointerRef = useRef<{ x: number; y: number; at: number } | null>(null);
128 useEffect(() => {
129 const capturePointer = (event: MouseEvent) => {
130 contextMenuPointerRef.current = { x: event.clientX, y: event.clientY, at: event.timeStamp };
131 };
132 document.addEventListener("contextmenu", capturePointer, true);
133 return () => document.removeEventListener("contextmenu", capturePointer, true);
134 }, []);
135​
136 const showEntryContextMenu = async (
137 item: TreeContextMenuItem,
138 context: TreeContextMenuOpenContext,
139 ) => {
140 const api = readLocalApi();
141 if (!api) {
142 context.close();
143 return;
144 }
145 const relativePath = item.path.replace(/\/$/, "");
146 const mention = serializeComposerFileLink(relativePath);
147 const pointer = contextMenuPointerRef.current;
148 const pointerIsFresh = pointer !== null && performance.now() - pointer.at < 1000;
149 const anchorRect = context.anchorElement.getBoundingClientRect();
150 const position = pointerIsFresh
151 ? { x: pointer.x, y: pointer.y }
152 : { x: anchorRect.left, y: anchorRect.bottom };
153 try {
154 const clicked = await api.contextMenu.show(
155 [
156 { id: "copy-mention", label: "Copy mention" },
157 { id: "add-to-chat", label: "Add to chat" },
158 ],
159 position,
160 );
161 if (clicked === "copy-mention") {
162 try {
163 await writeTextToClipboard(mention);
164 toastManager.add({ type: "success", title: "Mention copied", description: relativePath });
165 } catch (error) {
166 toastManager.add({
167 type: "error",
168 title: "Failed to copy mention",
169 description: error instanceof Error ? error.message : "An error occurred.",
170 });
171 }
172 return;
173 }
174 if (clicked === "add-to-chat") {
175 const composer = composerRef?.current;
176 if (!composer) {
177 toastManager.add({
178 type: "error",
179 title: "Unable to add to chat",
180 description: "Open a chat for this project and try again.",
181 });
182 return;
183 }
184 const inserted = composer.insertTextAtEnd(`${mention} `, { ensureLeadingBoundary: true });
185 if (!inserted) {
186 toastManager.add({
187 type: "error",
188 title: "Unable to add to chat",
189 description: "The chat isn't ready to accept input right now.",
190 });
191 }
192 }
193 } finally {
194 context.close();
195 }
196 };
197 const showEntryContextMenuRef = useRef(showEntryContextMenu);
198 useEffect(() => {
199 showEntryContextMenuRef.current = showEntryContextMenu;
200 });
201​
202 const treeModelRef = useRef<ReturnType<typeof useFileTree>["model"] | null>(null);
203 const dragMention = useMemo(
204 () =>
205 createFileTreeDragMentionController({
206 deselect: (path) => treeModelRef.current?.getItem(path)?.deselect(),
207 }),
208 [],
209 );
210 const { model } = useFileTree({
211 composition: {
212 contextMenu: {
213 triggerMode: "right-click",
214 onOpen: (item, context) => {
215 void showEntryContextMenuRef.current(item, context);
216 },
217 },
218 },
219 // Rows only need to be draggable so entries can be dropped into the chat
220 // composer; rearranging files inside the tree stays off.
221 dragAndDrop: { canDrop: () => false },
222 density: "compact",
223 fileTreeSearchMode: "hide-non-matches",
224 flattenEmptyDirectories: true,
225 initialExpansion: 1,
226 icons: T3_PIERRE_ICONS,
227 onSelectionChange: (selectedPaths) => {
228 // The drag controller's selection cache must track every change,
229 // including reveal-driven ones, or drags act on a stale selection.
230 dragMention.handleSelectionChange(selectedPaths);
231 // Selection changes driven by the reveal sync below are echoes of an
232 // already-open file, not a request to open it again.
233 if (syncingSelectionRef.current) return;
234 // Starting a drag selects the dragged row; that selection is a side
235 // effect of the gesture, not a request to open the file.
236 if (dragMention.isDragInProgress()) {
237 return;
238 }
239 const selectedPath = selectedPaths.at(-1)?.replace(/\/$/, "");
240 if (selectedPath && entryKindsRef.current.get(selectedPath) === "file") {
241 treeSelectionPathRef.current = selectedPath;
242 onOpenFile(selectedPath);
243 }
244 },
245 paths: [],
246 search: false,
247 unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
248 });
249 const search = useFileTreeSearch(model);
250 const allDirectoriesExpanded = useFileTreeSelector(model, (currentModel) =>
251 areAllDirectoriesExpanded(currentModel, directoryPaths),
252 );
253 const toggleAllDirectories = () => {
254 setAllDirectoriesExpanded(model, directoryPaths, !allDirectoriesExpanded);
255 };
256 const handleSearchValueChange = (value: string) => {
257 if (value.trim().length === 0) {
258 search.close();
259 return;
260 }
261 search.setValue(value);
262 };
263 const handleRefresh = () => {
264 entriesQuery.refresh();
265 onRefreshSelectedFile?.();
266 };
267 useWorkspaceMutationRefresh({
268 mutationId: workspaceMutationId,
269 refresh: entriesQuery.refresh,
270 resourceKey: `files:${environmentId}:${cwd}`,
271 });
272​
273 useEffect(() => {
274 if (entriesQuery.data === null) return;
275 if (previousTreePathsRef.current === treePaths) return;
276 entryKindsRef.current = entryKinds;
277 const previousTreePaths = previousTreePathsRef.current;
278 previousTreePathsRef.current = treePaths;
279 if (previousTreePaths === null) {
280 model.resetPaths(treePaths);
281 return;
282 }
283 const updates = buildFileTreePathUpdates(previousTreePaths, treePaths);
284 if (updates.length > 0) model.batch(updates);
285 }, [entriesQuery.data, entryKinds, model, treePaths]);
286​
287 useEffect(() => {
288 if (!selectedPath) {
289 handledRevealRef.current = null;
290 return;
291 }
292 const revealRequest = { path: selectedPath, revealId: selectedPathRevealId };
293 const handledReveal = handledRevealRef.current;
294 // Entry refreshes rebuild treePaths while the same preview stays open.
295 // Replaying a handled reveal would close an active tree search and steal focus.
296 if (
297 handledReveal?.path === revealRequest.path &&
298 handledReveal.revealId === revealRequest.revealId
299 ) {
300 return;
301 }
302 if (entryKinds.get(selectedPath) !== "file") return;
303 const selectedItem = model.getItem(selectedPath);
304 if (!selectedItem) return;
305​
306 // A selection that originated inside the tree (clicking a row, possibly
307 // in an active tree search) is already visible; re-revealing it would
308 // close the search and clobber the user's context. Only sync external
309 // opens (file picker, content search, chat links).
310 const selectedInTree = model
311 .getSelectedPaths()
312 .some((path) => path.replace(/\/$/, "") === selectedPath);
313 if (selectedInTree && treeSelectionPathRef.current === selectedPath) {
314 treeSelectionPathRef.current = null;
315 handledRevealRef.current = revealRequest;
316 return;
317 }
318 treeSelectionPathRef.current = null;
319 handledRevealRef.current = revealRequest;
320​
321 syncingSelectionRef.current = true;
322 model.closeSearch();
323 for (const path of model.getSelectedPaths()) {
324 model.getItem(path)?.deselect();
325 }
326​
327 // Directory rows are registered with a trailing slash (see treePath), so
328 // ancestor lookups must use the same form to expand them.
329 const segments = selectedPath.split("/");
330 let ancestorPath = "";
331 for (const segment of segments.slice(0, -1)) {
332 ancestorPath = ancestorPath ? `${ancestorPath}/${segment}` : segment;
333 const item = model.getItem(`${ancestorPath}/`) ?? model.getItem(ancestorPath);
334 if (item && "expand" in item) item.expand();
335 }
336​
337 selectedItem.select();
338 model.scrollToPath(selectedPath, { focus: true, offset: "center" });
339 queueMicrotask(() => {
340 syncingSelectionRef.current = false;
341 });
342 }, [entryKinds, model, selectedPath, selectedPathRevealId, treePaths]);
343​
344 // Tag tree drags with the composer mention payload. The row is read from
345 // the composed event path (the tree's shadow root is open), so this does
346 // not depend on running after the tree's own dragstart handler; the drag
347 // data store is writable for every dragstart listener in the dispatch.
348 // The capture phase runs before the tree's own dragstart handler selects
349 // the dragged row, so the drag flag is up before that selection emits.
350 const panelRef = useRef<HTMLDivElement | null>(null);
351 useEffect(() => {
352 treeModelRef.current = model;
353 }, [model]);
354 useEffect(() => {
355 const panel = panelRef.current;
356 if (panel === null) {
357 return;
358 }
359 const handleDragStart = (event: DragEvent) => dragMention.handleDragStart(event);
360 const handleDragEnd = () => dragMention.handleDragEnd();
361 panel.addEventListener("dragstart", handleDragStart, true);
362 panel.addEventListener("dragend", handleDragEnd);
363 return () => {
364 panel.removeEventListener("dragstart", handleDragStart, true);
365 panel.removeEventListener("dragend", handleDragEnd);
366 };
367 }, [dragMention]);
368​
369 return (
370 <div
371 ref={panelRef}
372 className="flex min-h-0 flex-1 flex-col bg-background"
373 data-file-browser-panel={`${environmentId}:${cwd}`}
374 >
375 <div
376 className="flex h-10 min-h-10 shrink-0 items-center gap-1 border-b border-border/60 bg-background px-2 in-data-[preview-panel-mode=inline]:mb-1 in-data-[preview-panel-mode=inline]:h-9 in-data-[preview-panel-mode=inline]:min-h-9 in-data-[preview-panel-mode=inline]:border-b-transparent"
377 data-surface-subheader
378 >
379 <RefreshFilesButton isPending={entriesQuery.isPending} onRefresh={handleRefresh} />
380 <FileSearchField
381 name="project-files-search"
382 ariaLabel={`Search ${projectName} files`}
383 value={search.value}
384 onValueChange={handleSearchValueChange}
385 onClose={search.close}
386 />
387 {directoryPaths.length > 0 ? (
388 <Tooltip>
389 <TooltipTrigger
390 render={
391 <Button
392 type="button"
393 size="icon-xs"
394 variant="ghost"
395 aria-label={
396 allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"
397 }
398 onClick={toggleAllDirectories}
399 />
400 }
401 >
402 {allDirectoriesExpanded ? (
403 <ChevronsDownUpIcon className="size-3.5" />
404 ) : (
405 <ChevronsUpDownIcon className="size-3.5" />
406 )}
407 </TooltipTrigger>
408 <TooltipPopup>
409 {allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
410 </TooltipPopup>
411 </Tooltip>
412 ) : null}
413 </div>
414 {entriesQuery.error && entriesQuery.data === null ? (
415 <div className="p-4 text-xs leading-relaxed text-destructive">{entriesQuery.error}</div>
416 ) : (
417 <FileTree
418 model={model}
419 aria-label={`${projectName} files`}
420 className="min-h-0 flex-1 overflow-hidden"
421 style={pierreTreeStyle(resolvedTheme)}
422 />
423 )}
424 </div>
425 );