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 { ChevronsDownUpIcon, ChevronsUpDownIcon } from "lucide-react";
13import { type Ref, useEffect, useEffectEvent, useRef, useState } from "react";
14
15import { Button } from "~/components/ui/button";
16import { InputGroup, InputGroupInput } from "~/components/ui/input-group";
17import { toastManager } from "~/components/ui/toast";
18import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
19import { useComposerHandleContext } from "~/composerHandleContext";
20import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
21import { useStableCallback } from "~/hooks/useStableCallback";
22import { useTheme } from "~/hooks/useTheme";
23import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";
24import { useFileContextMenu, type FileContextMenuAction } from "~/fileContextMenu";
25import { readLocalApi } from "~/localApi";
26import { T3_PIERRE_ICONS } from "~/pierre-icons";
27import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme";
28
29import { joinHostPath } from "./filePath";
30import { createFileTreeDragMentionController } from "./fileTreeDragMention";
31import {
32 areAllDirectoriesExpanded,
33 coalesceReentrantCalls,
34 readExpandedDirectories,
35 setAllDirectoriesExpanded,
36 writeExpandedDirectories,
37} from "./fileTreeExpansion";
38import { buildFileTreePathUpdates } from "./fileTreePathReconciliation";
39import { loadFileAncestors } from "./loadFileAncestors";
40import { useDirectoryEntries } from "./useDirectoryEntries";
41import { useProjectPathSearch } from "~/state/queries";
42import { isMacPlatform } from "~/lib/utils";
43import { type PreviewAction, subscribePreviewAction } from "../preview/previewActionBus";
44
45interface FileBrowserPanelProps {
46 environmentId: EnvironmentId;
47 cwd: string;
48 projectName: string;
49 selectedPath: string | null;
50 selectedPathRevealId: number;
51 onOpenFile: (relativePath: string) => void;
52 /** Host-folder entries use absolute paths. Avoid full traversal: disable expand-all and search only
53 * loaded folders. */
54 hostFolder?: boolean;
55 onRefreshSelectedFile?: () => void;
56 workspaceMutationId: string | null;
57 answersPanelFind?: boolean;
58}
59
60function treePath(entry: ProjectEntry): string {
61 return entry.kind === "directory" ? `${entry.path}/` : entry.path;
62}
63
64function RefreshFilesButton(props: { isPending: boolean; onRefresh: () => void }) {
65 return (
66 <Tooltip>
67 <TooltipTrigger
68 render={
69 <Button
70 type="button"
71 variant="ghost"
72 size="icon-xs"
73 aria-label="Refresh workspace files"
74 onClick={props.onRefresh}
75 />
76 }
77 >
78 <RefreshIcon refreshing={props.isPending} />
79 </TooltipTrigger>
80 <TooltipPopup>{props.isPending ? "Refreshing…" : "Refresh files"}</TooltipPopup>
81 </Tooltip>
82 );
83}
84
85function FileSearchField({
86 ref,
87 ...props
88}: {
89 ariaLabel: string;
90 name: string;
91 onClose: () => void;
92 onValueChange: (value: string) => void;
93 ref: Ref<HTMLInputElement>;
94 value: string;
95}) {
96 return (
97 <InputGroup variant="ghost" className="h-7 min-w-0 flex-1">
98 <InputGroupInput
99 ref={ref}
100 type="search"
101 name={props.name}
102 size="sm"
103 value={props.value}
104 aria-label={props.ariaLabel}
105 placeholder="Search files"
106 data-workspace-focus-default
107 spellCheck={false}
108 onChange={(event) => props.onValueChange(event.target.value)}
109 onKeyDown={(event) => {
110 if (event.key !== "Escape") return;
111 props.onClose();
112 event.currentTarget.blur();
113 }}
114 />
115 </InputGroup>
116 );
117}
118
119function buildTreeEntries(
120 directoryEntries: readonly ProjectEntry[],
121 searchEntries: readonly ProjectEntry[],
122 searchPending: boolean,
123 query: string,
124) {
125 const result = new Map(directoryEntries.map((entry) => [entry.path, entry]));
126 if (query.trim() && !searchPending) {
127 for (const entry of searchEntries) {
128 if (!result.has(entry.path)) result.set(entry.path, entry);
129 const segments = entry.path.split("/");
130 for (let index = 1; index < segments.length; index++) {
131 const path = segments.slice(0, index).join("/");
132 if (!result.has(path)) result.set(path, { path, kind: "directory" });
133 }
134 }
135 }
136 const entries = [...result.values()];
137 const entryKinds: ReadonlyMap<string, ProjectEntry["kind"]> = new Map(
138 entries.map((entry) => [entry.path, entry.kind] as const),
139 );
140 const treePaths = entries.map(treePath);
141 const directories = entries.filter((entry) => entry.kind === "directory");
142 const directoryPaths = directories.map(treePath);
143 // Expanding a folder lists it, and an ignored one such as `node_modules` can hold tens of
144 // thousands, so expand all skips ignored folders. They still open by hand.
145 const expandableDirectoryPaths = directories.filter((entry) => !entry.ignored).map(treePath);
146 return { entries, entryKinds, treePaths, directoryPaths, expandableDirectoryPaths };
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 answersPanelFind = false,
160}: FileBrowserPanelProps) {
161 const panelPath = (relativePath: string) =>
162 hostFolder ? joinHostPath(cwd, relativePath) : relativePath;
163 const { resolvedTheme } = useTheme();
164 const composerRef = useComposerHandleContext();
165 const fileContextMenu = useFileContextMenu(environmentId);
166 const {
167 entries: directoryEntries,
168 load,
169 refresh,
170 ready,
171 error,
172 isPending,
173 loadingDirectories,
174 } = useDirectoryEntries(environmentId, cwd);
175 const [query, setQuery] = useState("");
176 const [expandAll, setExpandAll] = useState(false);
177 const pathSearch = useProjectPathSearch(
178 { environmentId, cwd: hostFolder ? null : cwd, query: query.slice(0, 256) },
179 200,
180 );
181 const { entries, entryKinds, treePaths, directoryPaths, expandableDirectoryPaths } =
182 buildTreeEntries(directoryEntries, pathSearch.entries, pathSearch.isPending, query);
183 const entryKindsRef = useRef(entryKinds);
184 const previousTreePathsRef = useRef<readonly string[] | null>(null);
185 const syncingSelectionRef = useRef(false);
186 const treeSelectionPathRef = useRef<string | null>(null);
187 const handledRevealRef = useRef<{ path: string; revealId: number } | null>(null);
188
189 // Shadow-DOM row rects are unreliable; capture the composed contextmenu event's viewport position.
190 const contextMenuPointerRef = useRef<{ x: number; y: number; at: number } | null>(null);
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 // The app menu owns focus; the tree's outside-click handler would dismiss it before click.
210 context.close({ restoreFocus: !pointerIsFresh });
211 void settlePromise(async () => {
212 const clicked = await api.contextMenu.show(
213 [
214 ...fileMenuItems,
215 { id: "copy-mention", label: "Copy mention" },
216 { id: "add-to-chat", label: "Add to chat" },
217 ],
218 position,
219 );
220 if (clicked === null) return;
221 // Open-with submenu ids are absent from the top-level item list.
222 const isFileMenuAction =
223 fileMenuItems.some((entry) => entry.id === clicked) || clicked.startsWith("editor:");
224 if (isFileMenuAction) {
225 await fileContextMenu.activate(clicked as FileContextMenuAction, fileTarget);
226 return;
227 }
228 if (clicked === "copy-mention") {
229 try {
230 await writeTextToClipboard(mention);
231 } catch (error) {
232 toastManager.add({
233 type: "error",
234 title: "Failed to copy mention",
235 description: error instanceof Error ? error.message : "An error occurred.",
236 });
237 }
238 return;
239 }
240 if (clicked === "add-to-chat") {
241 const composer = composerRef?.current;
242 if (!composer) {
243 toastManager.add({
244 type: "error",
245 title: "Unable to add to chat",
246 description: "Open a chat for this project and try again.",
247 });
248 return;
249 }
250 const inserted = composer.insertTextAtEnd(`${mention} `, { ensureLeadingBoundary: true });
251 if (!inserted) {
252 toastManager.add({
253 type: "error",
254 title: "Unable to add to chat",
255 description: "The chat isn't ready to accept input right now.",
256 });
257 }
258 }
259 }).then((result) => {
260 if (!AsyncResult.isSuccess(result)) throw Cause.squash(result.cause);
261 });
262 },
263 );
264
265 const loadingDirectoriesRef = useRef(loadingDirectories);
266 const dragMention = createFileTreeDragMentionController(
267 hostFolder ? { mentionPath: (path: string) => joinHostPath(cwd, path) } : {},
268 );
269 const { model } = useFileTree({
270 composition: {
271 contextMenu: {
272 triggerMode: "right-click",
273 onOpen: (item, context) => {
274 showEntryContextMenu(item, context);
275 },
276 },
277 },
278 dragAndDrop: { canDrop: () => false },
279 density: "compact",
280 fileTreeSearchMode: "hide-non-matches",
281 flattenEmptyDirectories: true,
282 initialExpansion: "closed",
283 icons: T3_PIERRE_ICONS,
284 onSelectionChange: (selectedPaths) => {
285 // Update drag selection even for reveals so subsequent drags cannot use stale paths.
286 dragMention.handleSelectionChange(selectedPaths);
287 if (syncingSelectionRef.current) return;
288 if (dragMention.isDragInProgress()) {
289 return;
290 }
291 const selectedPath = selectedPaths.at(-1)?.replace(/\/$/, "");
292 if (selectedPath && entryKindsRef.current.get(selectedPath) === "file") {
293 treeSelectionPathRef.current = selectedPath;
294 onOpenFile(panelPath(selectedPath));
295 }
296 },
297 paths: [],
298 renderRowDecoration: ({ item, row }) =>
299 row.kind === "directory" &&
300 row.isExpanded &&
301 loadingDirectoriesRef.current.has(item.path.replace(/\/$/, ""))
302 ? { icon: "t3-tree-icon-loading", title: "Loading…" }
303 : null,
304 search: false,
305 onSearchChange: (value) => setQuery(value ?? ""),
306 unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
307 });
308 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- makes the Pierre tree model re-render row decorations when loading directories change
309 useEffect(() => {
310 if (loadingDirectoriesRef.current === loadingDirectories) return;
311 loadingDirectoriesRef.current = loadingDirectories;
312 model.setComposition(model.getComposition());
313 }, [loadingDirectories, model]);
314 const search = useFileTreeSearch(model);
315 // Pierre restores the unfiltered tree when a search has no matches.
316 const hasNoSearchMatches = search.value.trim().length > 0 && search.matchingPaths.length === 0;
317 const allDirectoriesExpanded = useFileTreeSelector(model, (currentModel) =>
318 areAllDirectoriesExpanded(currentModel, expandableDirectoryPaths),
319 );
320 const toggleAllDirectories = () => {
321 const expanded = !(expandAll || allDirectoriesExpanded);
322 setExpandAll(expanded);
323 setAllDirectoriesExpanded(
324 model,
325 expanded ? expandableDirectoryPaths : directoryPaths,
326 expanded,
327 );
328 };
329 const closeSearch = () => {
330 setQuery("");
331 search.close();
332 };
333 const searchInputRef = useRef<HTMLInputElement>(null);
334 const focusSearch = () => {
335 searchInputRef.current?.focus();
336 searchInputRef.current?.select();
337 };
338 const onPanelAction = useEffectEvent((action: PreviewAction) => {
339 // Hidden panel tabs stay mounted; only the visible Files tab answers.
340 if (action === "find" && searchInputRef.current?.getClientRects().length) focusSearch();
341 });
342 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the panel find command, which fires while focus is anywhere in the right panel
343 useEffect(() => {
344 if (!answersPanelFind) return;
345 return subscribePreviewAction(onPanelAction);
346 }, [answersPanelFind]);
347 const expandedPathsRef = useRef(new Set<string>());
348 const expansionRoot = `${environmentId}:${cwd}`;
349 // Folders expanded when the panel last unmounted; each reopens once lazy loading lists it.
350 const [pendingExpandedPaths] = useState(() => new Set(readExpandedDirectories(expansionRoot)));
351 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the Pierre tree model to load directories as they are expanded
352 useEffect(() => {
353 const currentPaths = new Set(directoryPaths);
354 for (const path of expandedPathsRef.current) {
355 if (!currentPaths.has(path)) expandedPathsRef.current.delete(path);
356 }
357 // Restoring calls item.expand(), which notifies subscribers synchronously.
358 const loadExpanded = coalesceReentrantCalls(() => {
359 if (model.isSearchOpen()) return;
360 let changed = false;
361 for (const path of directoryPaths) {
362 const item = model.getItem(path);
363 if (item?.isDirectory() && pendingExpandedPaths.delete(path) && "expand" in item) {
364 item.expand();
365 }
366 if (item?.isDirectory() && "isExpanded" in item && item.isExpanded()) {
367 if (!expandedPathsRef.current.has(path)) {
368 expandedPathsRef.current.add(path);
369 changed = true;
370 void load(path.replace(/\/$/, ""));
371 }
372 } else {
373 if (item?.isDirectory() && expandedPathsRef.current.has(path)) setExpandAll(false);
374 if (expandedPathsRef.current.delete(path)) changed = true;
375 }
376 }
377 if (changed) {
378 writeExpandedDirectories(expansionRoot, [
379 ...expandedPathsRef.current,
380 ...pendingExpandedPaths,
381 ]);
382 }
383 });
384 loadExpanded();
385 return model.subscribe(loadExpanded);
386 }, [directoryPaths, expansionRoot, load, model, pendingExpandedPaths]);
387 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes ignored-file status into the imperative Pierre tree model
388 useEffect(() => {
389 model.setGitStatus(
390 entries
391 .filter((entry) => entry.ignored)
392 .map((entry) => ({
393 path: treePath(entry),
394 status: "ignored",
395 })),
396 );
397 }, [entries, model]);
398 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- loads the selected file's ancestor directories and aborts on cleanup
399 useEffect(() => {
400 if (!selectedPath) return;
401 const controller = new AbortController();
402 void loadFileAncestors(selectedPath, load, { signal: controller.signal });
403 return () => {
404 controller.abort();
405 };
406 }, [load, selectedPath]);
407 const handleSearchValueChange = (value: string) => {
408 setQuery(value);
409 if (value.trim().length === 0) {
410 search.close();
411 return;
412 }
413 search.setValue(value);
414 };
415 const handleRefresh = () => {
416 refresh();
417 if (query.trim()) pathSearch.refresh();
418 onRefreshSelectedFile?.();
419 };
420 useWorkspaceMutationRefresh({
421 mutationId: workspaceMutationId,
422 refresh: () => {
423 refresh();
424 if (query.trim()) pathSearch.refresh();
425 },
426 resourceKey: `files:${environmentId}:${cwd}`,
427 });
428
429 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- applies tree path changes to the imperative Pierre tree model as a reset or batch update
430 useEffect(() => {
431 if (!ready) return;
432 if (previousTreePathsRef.current === treePaths) return;
433 entryKindsRef.current = entryKinds;
434 const previousTreePaths = previousTreePathsRef.current;
435 previousTreePathsRef.current = treePaths;
436 if (previousTreePaths === null) {
437 model.resetPaths(treePaths);
438 return;
439 }
440 const updates = buildFileTreePathUpdates(previousTreePaths, treePaths);
441 if (updates.length > 0) model.batch(updates);
442 }, [ready, entryKinds, model, treePaths]);
443
444 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- expands every directory in the Pierre tree model while expand-all is on and no search is active
445 useEffect(() => {
446 if (expandAll && !query.trim())
447 setAllDirectoriesExpanded(model, expandableDirectoryPaths, true);
448 }, [expandableDirectoryPaths, expandAll, model, query]);
449
450 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reveals an externally selected path in the Pierre tree model by expanding, selecting and scrolling
451 useEffect(() => {
452 if (!selectedPath) {
453 handledRevealRef.current = null;
454 return;
455 }
456 const selectedKind = entryKinds.get(selectedPath);
457 if (selectedKind === undefined) {
458 handledRevealRef.current = null;
459 return;
460 }
461 const revealRequest = { path: selectedPath, revealId: selectedPathRevealId };
462 const handledReveal = handledRevealRef.current;
463 // Refresh rebuilds treePaths; replaying handled reveals would close search and steal focus.
464 if (
465 handledReveal?.path === revealRequest.path &&
466 handledReveal.revealId === revealRequest.revealId
467 ) {
468 return;
469 }
470 const selectedTreePath = selectedKind === "directory" ? `${selectedPath}/` : selectedPath;
471 const selectedItem = model.getItem(selectedTreePath);
472 if (!selectedItem) return;
473
474 // Reveal only external selections; tree selections are visible and re-revealing would close search.
475 const selectedInTree = model
476 .getSelectedPaths()
477 .some((path) => path.replace(/\/$/, "") === selectedPath);
478 if (selectedInTree && treeSelectionPathRef.current === selectedPath) {
479 treeSelectionPathRef.current = null;
480 handledRevealRef.current = revealRequest;
481 return;
482 }
483 treeSelectionPathRef.current = null;
484 handledRevealRef.current = revealRequest;
485
486 syncingSelectionRef.current = true;
487 setQuery("");
488 model.closeSearch();
489 for (const path of model.getSelectedPaths()) {
490 model.getItem(path)?.deselect();
491 }
492
493 // Directory paths include trailing slashes; ancestor lookups must match.
494 const segments = selectedPath.split("/");
495 let ancestorPath = "";
496 for (const segment of segments.slice(0, -1)) {
497 ancestorPath = ancestorPath ? `${ancestorPath}/${segment}` : segment;
498 const item = model.getItem(`${ancestorPath}/`) ?? model.getItem(ancestorPath);
499 if (item && "expand" in item) item.expand();
500 }
501
502 if ("expand" in selectedItem) selectedItem.expand();
503 selectedItem.select();
504 model.scrollToPath(selectedTreePath, {
505 focus: true,
506 offset: "center",
507 });
508 queueMicrotask(() => {
509 syncingSelectionRef.current = false;
510 });
511 }, [entryKinds, model, selectedPath, selectedPathRevealId]);
512
513 return (
514 <div
515 className="flex min-h-0 flex-1 flex-col bg-background"
516 data-file-browser-panel={`${environmentId}:${cwd}`}
517 // Capture runs before the tree's shadow-internal row handler opens the menu.
518 onContextMenuCapture={(event) => {
519 contextMenuPointerRef.current = { x: event.clientX, y: event.clientY, at: event.timeStamp };
520 }}
521 // Capture dragstart before the tree selects the row so selection sees the drag flag.
522 onDragStartCapture={(event) => dragMention.handleDragStart(event.nativeEvent)}
523 onDragEnd={() => dragMention.handleDragEnd((path) => model.getItem(path)?.deselect())}
524 onKeyDown={(event) => {
525 const isModPressed = isMacPlatform(navigator.platform) ? event.metaKey : event.ctrlKey;
526 if (!isModPressed || event.altKey || event.shiftKey || event.key.toLowerCase() !== "f")
527 return;
528 event.preventDefault();
529 focusSearch();
530 }}
531 >
532 <div
533 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"
534 data-surface-subheader
535 >
536 <RefreshFilesButton isPending={isPending} onRefresh={handleRefresh} />
537 <FileSearchField
538 ref={searchInputRef}
539 name="project-files-search"
540 ariaLabel={`Search ${projectName} files`}
541 value={search.value}
542 onValueChange={handleSearchValueChange}
543 onClose={closeSearch}
544 />
545 {directoryPaths.length > 0 && !hostFolder ? (
546 <Tooltip>
547 <TooltipTrigger
548 render={
549 <Button
550 type="button"
551 size="icon-xs"
552 variant="ghost"
553 aria-label={
554 expandAll || allDirectoriesExpanded
555 ? "Collapse all folders"
556 : "Expand all folders"
557 }
558 onClick={toggleAllDirectories}
559 />
560 }
561 >
562 {allDirectoriesExpanded ? (
563 <ChevronsDownUpIcon className="size-3.5" />
564 ) : (
565 <ChevronsUpDownIcon className="size-3.5" />
566 )}
567 </TooltipTrigger>
568 <TooltipPopup>
569 {expandAll || allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
570 </TooltipPopup>
571 </Tooltip>
572 ) : null}
573 </div>
574 {error || pathSearch.error ? (
575 <button
576 type="button"
577 onClick={handleRefresh}
578 className="p-4 text-left text-xs leading-relaxed text-destructive"
579 >
580 {error ?? pathSearch.error} Click to retry.
581 </button>
582 ) : null}
583 {query.trim() && pathSearch.truncated && !pathSearch.isPending ? (
584 <div className="px-3 py-1 text-xs text-muted-foreground">
585 More matches available. Refine your search.
586 </div>
587 ) : null}
588 {(!ready || pathSearch.isPending) && (
589 <div
590 role="status"
591 className={
592 entries.length > 0 && !hasNoSearchMatches
593 ? "sr-only"
594 : "px-3 py-1 text-xs text-muted-foreground"
595 }
596 >
597 Loading files…
598 </div>
599 )}
600 {hasNoSearchMatches ? (
601 ready && !isPending && !pathSearch.isPending && !error && !pathSearch.error ? (
602 <div role="status" className="px-3 py-4 text-xs text-muted-foreground">
603 No matching files.
604 </div>
605 ) : null
606 ) : (
607 <FileTree
608 model={model}
609 aria-label={`${projectName} files`}
610 className="min-h-0 flex-1 overflow-hidden"
611 style={pierreTreeStyle(resolvedTheme)}
612 />
613 )}
614 </div>
615 );
616}