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