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

FileBrowserPanel.tsx

558 lines20.4 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, useState } 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 { useFileContextMenu, type FileContextMenuAction } from "~/fileContextMenu";
21import { readLocalApi } from "~/localApi";
22import { T3_PIERRE_ICONS } from "~/pierre-icons";
23import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme";
24​
25import { createFileTreeDragMentionController } from "./fileTreeDragMention";
26import { areAllDirectoriesExpanded, setAllDirectoriesExpanded } from "./fileTreeExpansion";
27import { buildFileTreePathUpdates } from "./fileTreePathReconciliation";
28import { useDirectoryEntries } from "./useDirectoryEntries";
29import { useProjectPathSearch } from "~/state/queries";
30​
31interface FileBrowserPanelProps {
32 environmentId: EnvironmentId;
33 cwd: string;
34 projectName: string;
35 /** Entry currently open in the surface; revealed and selected in the tree. A directory is expanded. */
36 selectedPath: string | null;
37 /** Bumped when the same path should be revealed again (e.g. re-opened from search). */
38 selectedPathRevealId: number;
39 onOpenFile: (relativePath: string) => void;
40 onRefreshSelectedFile?: () => void;
41 workspaceMutationId: string | null;
43​
44function treePath(entry: ProjectEntry): string {
45 return entry.kind === "directory" ? `${entry.path}/` : entry.path;
47​
48function RefreshFilesButton(props: { isPending: boolean; onRefresh: () => void }) {
49 return (
50 <Tooltip>
51 <TooltipTrigger
52 render={
53 <Button
54 type="button"
55 variant="ghost"
56 size="icon-xs"
57 aria-label="Refresh workspace files"
58 onClick={props.onRefresh}
59 />
60 }
61 >
62 <RefreshIcon refreshing={props.isPending} />
63 </TooltipTrigger>
64 <TooltipPopup>{props.isPending ? "Refreshing…" : "Refresh files"}</TooltipPopup>
65 </Tooltip>
66 );
68​
69function FileSearchField(props: {
70 ariaLabel: string;
71 name: string;
72 onClose: () => void;
73 onValueChange: (value: string) => void;
74 value: string;
75}) {
76 return (
77 <InputGroup variant="ghost" className="h-7 min-w-0 flex-1">
78 <InputGroupInput
79 type="search"
80 name={props.name}
81 size="sm"
82 value={props.value}
83 aria-label={props.ariaLabel}
84 placeholder="Search files"
85 spellCheck={false}
86 onChange={(event) => props.onValueChange(event.target.value)}
87 onKeyDown={(event) => {
88 if (event.key !== "Escape") return;
89 props.onClose();
90 event.currentTarget.blur();
91 }}
92 />
93 </InputGroup>
94 );
96​
97export default function FileBrowserPanel({
98 environmentId,
99 cwd,
100 projectName,
101 selectedPath,
102 selectedPathRevealId,
103 onOpenFile,
104 onRefreshSelectedFile,
105 workspaceMutationId,
106}: FileBrowserPanelProps) {
107 const { resolvedTheme } = useTheme();
108 const composerRef = useComposerHandleContext();
109 const fileContextMenu = useFileContextMenu(environmentId);
110 const {
111 entries: directoryEntries,
112 load,
113 refresh,
114 ready,
115 error,
116 isPending,
117 } = useDirectoryEntries(environmentId, cwd);
118 const [query, setQuery] = useState("");
119 const [expandAll, setExpandAll] = useState(false);
120 const pathSearch = useProjectPathSearch({ environmentId, cwd, query: query.slice(0, 256) }, 200);
121 const entries = useMemo(() => {
122 const result = new Map(directoryEntries.map((entry) => [entry.path, entry]));
123 if (query.trim() && !pathSearch.isPending) {
124 for (const entry of pathSearch.entries) {
125 if (!result.has(entry.path)) result.set(entry.path, entry);
126 const segments = entry.path.split("/");
127 for (let index = 1; index < segments.length; index++) {
128 const path = segments.slice(0, index).join("/");
129 if (!result.has(path)) result.set(path, { path, kind: "directory" });
130 }
131 }
132 }
133 return [...result.values()];
134 }, [directoryEntries, pathSearch.entries, pathSearch.isPending, query]);
135 const entryKinds = useMemo(
136 () => new Map(entries.map((entry) => [entry.path, entry.kind] as const)),
137 [entries],
138 );
139 const entryKindsRef = useRef<ReadonlyMap<string, ProjectEntry["kind"]>>(entryKinds);
140 const treePaths = useMemo(() => entries.map(treePath), [entries]);
141 const directoryPaths = useMemo(
142 () => entries.filter((entry) => entry.kind === "directory").map(treePath),
143 [entries],
144 );
145 const previousTreePathsRef = useRef<readonly string[] | null>(null);
146 const syncingSelectionRef = useRef(false);
147 const treeSelectionPathRef = useRef<string | null>(null);
148 const handledRevealRef = useRef<{ path: string; revealId: number } | null>(null);
149​
150 // The tree renders rows in shadow DOM and its anchor rect is unreliable, so
151 // capture the right-click position ourselves; contextmenu is a composed
152 // event, so a capture-phase listener sees it with viewport coordinates.
153 const contextMenuPointerRef = useRef<{ x: number; y: number; at: number } | null>(null);
154 useEffect(() => {
155 const capturePointer = (event: MouseEvent) => {
156 contextMenuPointerRef.current = { x: event.clientX, y: event.clientY, at: event.timeStamp };
157 };
158 document.addEventListener("contextmenu", capturePointer, true);
159 return () => document.removeEventListener("contextmenu", capturePointer, true);
160 }, []);
161​
162 /** Combines the file actions (open/reveal/open with) with the panel's own mention actions. */
163 const showEntryContextMenu = async (
164 item: TreeContextMenuItem,
165 context: TreeContextMenuOpenContext,
166 ) => {
167 const api = readLocalApi();
168 if (!api) {
169 context.close();
170 return;
171 }
172 const relativePath = item.path.replace(/\/$/, "");
173 const mention = serializeComposerFileLink(relativePath);
174 const pointer = contextMenuPointerRef.current;
175 const pointerIsFresh = pointer !== null && performance.now() - pointer.at < 1000;
176 const anchorRect = context.anchorElement.getBoundingClientRect();
177 const position = pointerIsFresh
178 ? { x: pointer.x, y: pointer.y }
179 : { x: anchorRect.left, y: anchorRect.bottom };
180 const fileTarget = { environmentId, filePath: relativePath, workspaceRoot: cwd };
181 const fileMenuItems = fileContextMenu.buildItems(fileTarget);
182 try {
183 const clicked = await api.contextMenu.show(
184 [
185 ...fileMenuItems,
186 { id: "copy-mention", label: "Copy mention" },
187 { id: "add-to-chat", label: "Add to chat" },
188 ],
189 position,
190 );
191 if (clicked === null) return;
192 // "Open with" submenu selections report the child id ("editor:<id>"),
193 // which is not present in the top-level item list.
194 const isFileMenuAction =
195 fileMenuItems.some((entry) => entry.id === clicked) || clicked.startsWith("editor:");
196 if (isFileMenuAction) {
197 await fileContextMenu.activate(clicked as FileContextMenuAction, fileTarget);
198 return;
199 }
200 if (clicked === "copy-mention") {
201 try {
202 await writeTextToClipboard(mention);
203 toastManager.add({ type: "success", title: "Mention copied", description: relativePath });
204 } catch (error) {
205 toastManager.add({
206 type: "error",
207 title: "Failed to copy mention",
208 description: error instanceof Error ? error.message : "An error occurred.",
209 });
210 }
211 return;
212 }
213 if (clicked === "add-to-chat") {
214 const composer = composerRef?.current;
215 if (!composer) {
216 toastManager.add({
217 type: "error",
218 title: "Unable to add to chat",
219 description: "Open a chat for this project and try again.",
220 });
221 return;
222 }
223 const inserted = composer.insertTextAtEnd(`${mention} `, { ensureLeadingBoundary: true });
224 if (!inserted) {
225 toastManager.add({
226 type: "error",
227 title: "Unable to add to chat",
228 description: "The chat isn't ready to accept input right now.",
229 });
230 }
231 }
232 } finally {
233 context.close();
234 }
235 };
236 const showEntryContextMenuRef = useRef(showEntryContextMenu);
237 useEffect(() => {
238 showEntryContextMenuRef.current = showEntryContextMenu;
239 });
240​
241 const treeModelRef = useRef<ReturnType<typeof useFileTree>["model"] | null>(null);
242 const dragMention = useMemo(
243 () =>
244 createFileTreeDragMentionController({
245 deselect: (path) => treeModelRef.current?.getItem(path)?.deselect(),
246 }),
247 [],
248 );
249 const { model } = useFileTree({
250 composition: {
251 contextMenu: {
252 triggerMode: "right-click",
253 onOpen: (item, context) => {
254 void showEntryContextMenuRef.current(item, context);
255 },
256 },
257 },
258 // Rows only need to be draggable so entries can be dropped into the chat
259 // composer; rearranging files inside the tree stays off.
260 dragAndDrop: { canDrop: () => false },
261 density: "compact",
262 fileTreeSearchMode: "hide-non-matches",
263 flattenEmptyDirectories: true,
264 initialExpansion: "closed",
265 icons: T3_PIERRE_ICONS,
266 onSelectionChange: (selectedPaths) => {
267 // The drag controller's selection cache must track every change,
268 // including reveal-driven ones, or drags act on a stale selection.
269 dragMention.handleSelectionChange(selectedPaths);
270 // Selection changes driven by the reveal sync below are echoes of an
271 // already-open file, not a request to open it again.
272 if (syncingSelectionRef.current) return;
273 // Starting a drag selects the dragged row; that selection is a side
274 // effect of the gesture, not a request to open the file.
275 if (dragMention.isDragInProgress()) {
276 return;
277 }
278 const selectedPath = selectedPaths.at(-1)?.replace(/\/$/, "");
279 if (selectedPath && entryKindsRef.current.get(selectedPath) === "file") {
280 treeSelectionPathRef.current = selectedPath;
281 onOpenFile(selectedPath);
282 }
283 },
284 paths: [],
285 search: false,
286 onSearchChange: (value) => setQuery(value ?? ""),
287 unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
288 });
289 const search = useFileTreeSearch(model);
290 const allDirectoriesExpanded = useFileTreeSelector(model, (currentModel) =>
291 areAllDirectoriesExpanded(currentModel, directoryPaths),
292 );
293 const toggleAllDirectories = () => {
294 const expanded = !(expandAll || allDirectoriesExpanded);
295 setExpandAll(expanded);
296 setAllDirectoriesExpanded(model, directoryPaths, expanded);
297 };
298 const closeSearch = () => {
299 setQuery("");
300 search.close();
301 };
302 const expandedPathsRef = useRef(new Set<string>());
303 useEffect(() => {
304 const currentPaths = new Set(directoryPaths);
305 for (const path of expandedPathsRef.current) {
306 if (!currentPaths.has(path)) expandedPathsRef.current.delete(path);
307 }
308 const loadExpanded = () => {
309 if (model.isSearchOpen()) return;
310 for (const path of directoryPaths) {
311 const item = model.getItem(path);
312 if (item?.isDirectory() && "isExpanded" in item && item.isExpanded()) {
313 if (!expandedPathsRef.current.has(path)) {
314 expandedPathsRef.current.add(path);
315 void load(path.replace(/\/$/, ""));
316 }
317 } else {
318 if (item?.isDirectory() && expandedPathsRef.current.has(path)) setExpandAll(false);
319 expandedPathsRef.current.delete(path);
320 }
321 }
322 };
323 loadExpanded();
324 return model.subscribe(loadExpanded);
325 }, [directoryPaths, load, model]);
326 useEffect(() => {
327 model.setGitStatus(
328 entries
329 .filter((entry) => entry.ignored)
330 .map((entry) => ({
331 path: treePath(entry),
332 status: "ignored",
333 })),
334 );
335 }, [entries, model]);
336 useEffect(() => {
337 if (!selectedPath) return;
338 const controller = new AbortController();
339 void (async () => {
340 const segments = selectedPath.split("/");
341 for (let index = 0; index < segments.length && !controller.signal.aborted; index++) {
342 await load(segments.slice(0, index).join("/"));
343 }
344 })();
345 return () => {
346 controller.abort();
347 };
348 }, [load, selectedPath]);
349 const handleSearchValueChange = (value: string) => {
350 setQuery(value);
351 if (value.trim().length === 0) {
352 search.close();
353 return;
354 }
355 search.setValue(value);
356 };
357 const handleRefresh = () => {
358 refresh();
359 if (query.trim()) pathSearch.refresh();
360 onRefreshSelectedFile?.();
361 };
362 useWorkspaceMutationRefresh({
363 mutationId: workspaceMutationId,
364 refresh: () => {
365 refresh();
366 if (query.trim()) pathSearch.refresh();
367 },
368 resourceKey: `files:${environmentId}:${cwd}`,
369 });
370​
371 useEffect(() => {
372 if (!ready) return;
373 if (previousTreePathsRef.current === treePaths) return;
374 entryKindsRef.current = entryKinds;
375 const previousTreePaths = previousTreePathsRef.current;
376 previousTreePathsRef.current = treePaths;
377 if (previousTreePaths === null) {
378 model.resetPaths(treePaths);
379 return;
380 }
381 const updates = buildFileTreePathUpdates(previousTreePaths, treePaths);
382 if (updates.length > 0) model.batch(updates);
383 }, [ready, entryKinds, model, treePaths]);
384​
385 useEffect(() => {
386 if (expandAll && !query.trim()) setAllDirectoriesExpanded(model, directoryPaths, true);
387 }, [directoryPaths, expandAll, model, query]);
388​
389 useEffect(() => {
390 if (!selectedPath) {
391 handledRevealRef.current = null;
392 return;
393 }
394 const selectedKind = entryKinds.get(selectedPath);
395 // An unloaded entry has no row to reveal yet; folders do, and chat links can
396 // point at them.
397 if (selectedKind === undefined) {
398 handledRevealRef.current = null;
399 return;
400 }
401 const revealRequest = { path: selectedPath, revealId: selectedPathRevealId };
402 const handledReveal = handledRevealRef.current;
403 // Entry refreshes rebuild treePaths while the same preview stays open.
404 // Replaying a handled reveal would close an active tree search and steal focus.
405 if (
406 handledReveal?.path === revealRequest.path &&
407 handledReveal.revealId === revealRequest.revealId
408 ) {
409 return;
410 }
411 // Directory rows are registered with a trailing slash (see treePath).
412 const selectedTreePath = selectedKind === "directory" ? `${selectedPath}/` : selectedPath;
413 const selectedItem = model.getItem(selectedTreePath);
414 if (!selectedItem) return;
415​
416 // A selection that originated inside the tree (clicking a row, possibly
417 // in an active tree search) is already visible; re-revealing it would
418 // close the search and clobber the user's context. Only sync external
419 // opens (file picker, content search, chat links).
420 const selectedInTree = model
421 .getSelectedPaths()
422 .some((path) => path.replace(/\/$/, "") === selectedPath);
423 if (selectedInTree && treeSelectionPathRef.current === selectedPath) {
424 treeSelectionPathRef.current = null;
425 handledRevealRef.current = revealRequest;
426 return;
427 }
428 treeSelectionPathRef.current = null;
429 handledRevealRef.current = revealRequest;
430​
431 syncingSelectionRef.current = true;
432 setQuery("");
433 model.closeSearch();
434 for (const path of model.getSelectedPaths()) {
435 model.getItem(path)?.deselect();
436 }
437​
438 // Directory rows are registered with a trailing slash (see treePath), so
439 // ancestor lookups must use the same form to expand them.
440 const segments = selectedPath.split("/");
441 let ancestorPath = "";
442 for (const segment of segments.slice(0, -1)) {
443 ancestorPath = ancestorPath ? `${ancestorPath}/${segment}` : segment;
444 const item = model.getItem(`${ancestorPath}/`) ?? model.getItem(ancestorPath);
445 if (item && "expand" in item) item.expand();
446 }
447​
448 if ("expand" in selectedItem) selectedItem.expand();
449 selectedItem.select();
450 model.scrollToPath(selectedTreePath, {
451 focus: true,
452 offset: "center",
453 });
454 queueMicrotask(() => {
455 syncingSelectionRef.current = false;
456 });
457 }, [entryKinds, model, selectedPath, selectedPathRevealId]);
458​
459 // Tag tree drags with the composer mention payload. The row is read from
460 // the composed event path (the tree's shadow root is open), so this does
461 // not depend on running after the tree's own dragstart handler; the drag
462 // data store is writable for every dragstart listener in the dispatch.
463 // The capture phase runs before the tree's own dragstart handler selects
464 // the dragged row, so the drag flag is up before that selection emits.
465 const panelRef = useRef<HTMLDivElement | null>(null);
466 useEffect(() => {
467 treeModelRef.current = model;
468 }, [model]);
469 useEffect(() => {
470 const panel = panelRef.current;
471 if (panel === null) {
472 return;
473 }
474 const handleDragStart = (event: DragEvent) => dragMention.handleDragStart(event);
475 const handleDragEnd = () => dragMention.handleDragEnd();
476 panel.addEventListener("dragstart", handleDragStart, true);
477 panel.addEventListener("dragend", handleDragEnd);
478 return () => {
479 panel.removeEventListener("dragstart", handleDragStart, true);
480 panel.removeEventListener("dragend", handleDragEnd);
481 };
482 }, [dragMention]);
483​
484 return (
485 <div
486 ref={panelRef}
487 className="flex min-h-0 flex-1 flex-col bg-background"
488 data-file-browser-panel={`${environmentId}:${cwd}`}
489 >
490 <div
491 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"
492 data-surface-subheader
493 >
494 <RefreshFilesButton isPending={isPending} onRefresh={handleRefresh} />
495 <FileSearchField
496 name="project-files-search"
497 ariaLabel={`Search ${projectName} files`}
498 value={search.value}
499 onValueChange={handleSearchValueChange}
500 onClose={closeSearch}
501 />
502 {directoryPaths.length > 0 ? (
503 <Tooltip>
504 <TooltipTrigger
505 render={
506 <Button
507 type="button"
508 size="icon-xs"
509 variant="ghost"
510 aria-label={
511 expandAll || allDirectoriesExpanded
512 ? "Collapse all folders"
513 : "Expand all folders"
514 }
515 onClick={toggleAllDirectories}
516 />
517 }
518 >
519 {allDirectoriesExpanded ? (
520 <ChevronsDownUpIcon className="size-3.5" />
521 ) : (
522 <ChevronsUpDownIcon className="size-3.5" />
523 )}
524 </TooltipTrigger>
525 <TooltipPopup>
526 {expandAll || allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
527 </TooltipPopup>
528 </Tooltip>
529 ) : null}
530 </div>
531 {error || pathSearch.error ? (
532 <button
533 type="button"
534 onClick={handleRefresh}
535 className="p-4 text-left text-xs leading-relaxed text-destructive"
536 >
537 {error ?? pathSearch.error} Click to retry.
538 </button>
539 ) : null}
540 {query.trim() && pathSearch.truncated && !pathSearch.isPending ? (
541 <div className="px-3 py-1 text-xs text-muted-foreground">
542 More matches available. Refine your search.
543 </div>
544 ) : null}
545 {(isPending || pathSearch.isPending) && (
546 <div role="status" className="px-3 py-1 text-xs text-muted-foreground">
547 Loading files…
548 </div>
549 )}
550 <FileTree
551 model={model}
552 aria-label={`${projectName} files`}
553 className="min-h-0 flex-1 overflow-hidden"
554 style={pierreTreeStyle(resolvedTheme)}
555 />
556 </div>
557 );