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

FileBrowserPanel.tsx

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