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