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