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 { useEffect, 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 { areAllDirectoriesExpanded, setAllDirectoriesExpanded } from "./fileTreeExpansion";
32import { buildFileTreePathUpdates } from "./fileTreePathReconciliation";
33import { loadFileAncestors } from "./loadFileAncestors";
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 /** Host-folder entries use absolute paths. Avoid full traversal: disable expand-all and search only
45 * loaded folders. */
46 hostFolder?: boolean;
47 onRefreshSelectedFile?: () => void;
48 workspaceMutationId: string | null;
49}
50
51function treePath(entry: ProjectEntry): string {
52 return entry.kind === "directory" ? `${entry.path}/` : entry.path;
53}
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 );
74}
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 data-workspace-focus-default
93 spellCheck={false}
94 onChange={(event) => props.onValueChange(event.target.value)}
95 onKeyDown={(event) => {
96 if (event.key !== "Escape") return;
97 props.onClose();
98 event.currentTarget.blur();
99 }}
100 />
101 </InputGroup>
102 );
103}
104
105function buildTreeEntries(
106 directoryEntries: readonly ProjectEntry[],
107 searchEntries: readonly ProjectEntry[],
108 searchPending: boolean,
109 query: string,
110) {
111 const result = new Map(directoryEntries.map((entry) => [entry.path, entry]));
112 if (query.trim() && !searchPending) {
113 for (const entry of searchEntries) {
114 if (!result.has(entry.path)) result.set(entry.path, entry);
115 const segments = entry.path.split("/");
116 for (let index = 1; index < segments.length; index++) {
117 const path = segments.slice(0, index).join("/");
118 if (!result.has(path)) result.set(path, { path, kind: "directory" });
119 }
120 }
121 }
122 const entries = [...result.values()];
123 const entryKinds: ReadonlyMap<string, ProjectEntry["kind"]> = new Map(
124 entries.map((entry) => [entry.path, entry.kind] as const),
125 );
126 const treePaths = entries.map(treePath);
127 const directories = entries.filter((entry) => entry.kind === "directory");
128 const directoryPaths = directories.map(treePath);
129 // Expanding a folder lists it, and an ignored one such as `node_modules` can hold tens of
130 // thousands, so expand all skips ignored folders. They still open by hand.
131 const expandableDirectoryPaths = directories.filter((entry) => !entry.ignored).map(treePath);
132 return { entries, entryKinds, treePaths, directoryPaths, expandableDirectoryPaths };
133}
134
135export default function FileBrowserPanel({
136 environmentId,
137 cwd,
138 projectName,
139 selectedPath,
140 selectedPathRevealId,
141 onOpenFile,
142 onRefreshSelectedFile,
143 workspaceMutationId,
144 hostFolder = false,
145}: FileBrowserPanelProps) {
146 const panelPath = (relativePath: string) =>
147 hostFolder ? joinHostPath(cwd, relativePath) : relativePath;
148 const { resolvedTheme } = useTheme();
149 const composerRef = useComposerHandleContext();
150 const fileContextMenu = useFileContextMenu(environmentId);
151 const {
152 entries: directoryEntries,
153 load,
154 refresh,
155 ready,
156 error,
157 isPending,
158 loadingDirectories,
159 } = useDirectoryEntries(environmentId, cwd);
160 const [query, setQuery] = useState("");
161 const [expandAll, setExpandAll] = useState(false);
162 const pathSearch = useProjectPathSearch(
163 { environmentId, cwd: hostFolder ? null : cwd, query: query.slice(0, 256) },
164 200,
165 );
166 const { entries, entryKinds, treePaths, directoryPaths, expandableDirectoryPaths } =
167 buildTreeEntries(directoryEntries, pathSearch.entries, pathSearch.isPending, query);
168 const entryKindsRef = useRef(entryKinds);
169 const previousTreePathsRef = useRef<readonly string[] | null>(null);
170 const syncingSelectionRef = useRef(false);
171 const treeSelectionPathRef = useRef<string | null>(null);
172 const handledRevealRef = useRef<{ path: string; revealId: number } | null>(null);
173
174 // Shadow-DOM row rects are unreliable; capture the composed contextmenu event's viewport position.
175 const contextMenuPointerRef = useRef<{ x: number; y: number; at: number } | null>(null);
176
177 const showEntryContextMenu = useStableCallback(
178 (item: TreeContextMenuItem, context: TreeContextMenuOpenContext) => {
179 const api = readLocalApi();
180 if (!api) {
181 context.close();
182 return;
183 }
184 const relativePath = item.path.replace(/\/$/, "");
185 const mention = serializeComposerFileLink(panelPath(relativePath));
186 const pointer = contextMenuPointerRef.current;
187 const pointerIsFresh = pointer !== null && performance.now() - pointer.at < 1000;
188 const anchorRect = context.anchorElement.getBoundingClientRect();
189 const position = pointerIsFresh
190 ? { x: pointer.x, y: pointer.y }
191 : { x: anchorRect.left, y: anchorRect.bottom };
192 const fileTarget = { environmentId, filePath: relativePath, workspaceRoot: cwd };
193 const fileMenuItems = fileContextMenu.buildItems(fileTarget);
194 // The app menu owns focus; the tree's outside-click handler would dismiss it before click.
195 context.close({ restoreFocus: !pointerIsFresh });
196 void settlePromise(async () => {
197 const clicked = await api.contextMenu.show(
198 [
199 ...fileMenuItems,
200 { id: "copy-mention", label: "Copy mention" },
201 { id: "add-to-chat", label: "Add to chat" },
202 ],
203 position,
204 );
205 if (clicked === null) return;
206 // Open-with submenu ids are absent from 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({
217 type: "success",
218 title: "Mention copied",
219 description: relativePath,
220 });
221 } catch (error) {
222 toastManager.add({
223 type: "error",
224 title: "Failed to copy mention",
225 description: error instanceof Error ? error.message : "An error occurred.",
226 });
227 }
228 return;
229 }
230 if (clicked === "add-to-chat") {
231 const composer = composerRef?.current;
232 if (!composer) {
233 toastManager.add({
234 type: "error",
235 title: "Unable to add to chat",
236 description: "Open a chat for this project and try again.",
237 });
238 return;
239 }
240 const inserted = composer.insertTextAtEnd(`${mention} `, { ensureLeadingBoundary: true });
241 if (!inserted) {
242 toastManager.add({
243 type: "error",
244 title: "Unable to add to chat",
245 description: "The chat isn't ready to accept input right now.",
246 });
247 }
248 }
249 }).then((result) => {
250 if (!AsyncResult.isSuccess(result)) throw Cause.squash(result.cause);
251 });
252 },
253 );
254
255 const loadingDirectoriesRef = useRef(loadingDirectories);
256 const dragMention = createFileTreeDragMentionController(
257 hostFolder ? { mentionPath: (path: string) => joinHostPath(cwd, path) } : {},
258 );
259 const { model } = useFileTree({
260 composition: {
261 contextMenu: {
262 triggerMode: "right-click",
263 onOpen: (item, context) => {
264 showEntryContextMenu(item, context);
265 },
266 },
267 },
268 dragAndDrop: { canDrop: () => false },
269 density: "compact",
270 fileTreeSearchMode: "hide-non-matches",
271 flattenEmptyDirectories: true,
272 initialExpansion: "closed",
273 icons: T3_PIERRE_ICONS,
274 onSelectionChange: (selectedPaths) => {
275 // Update drag selection even for reveals so subsequent drags cannot use stale paths.
276 dragMention.handleSelectionChange(selectedPaths);
277 if (syncingSelectionRef.current) return;
278 if (dragMention.isDragInProgress()) {
279 return;
280 }
281 const selectedPath = selectedPaths.at(-1)?.replace(/\/$/, "");
282 if (selectedPath && entryKindsRef.current.get(selectedPath) === "file") {
283 treeSelectionPathRef.current = selectedPath;
284 onOpenFile(panelPath(selectedPath));
285 }
286 },
287 paths: [],
288 renderRowDecoration: ({ item, row }) =>
289 row.kind === "directory" &&
290 row.isExpanded &&
291 loadingDirectoriesRef.current.has(item.path.replace(/\/$/, ""))
292 ? { icon: "t3-tree-icon-loading", title: "Loading…" }
293 : null,
294 search: false,
295 onSearchChange: (value) => setQuery(value ?? ""),
296 unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
297 });
298 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- makes the Pierre tree model re-render row decorations when loading directories change
299 useEffect(() => {
300 if (loadingDirectoriesRef.current === loadingDirectories) return;
301 loadingDirectoriesRef.current = loadingDirectories;
302 model.setComposition(model.getComposition());
303 }, [loadingDirectories, model]);
304 const search = useFileTreeSearch(model);
305 // Pierre restores the unfiltered tree when a search has no matches.
306 const hasNoSearchMatches = search.value.trim().length > 0 && search.matchingPaths.length === 0;
307 const allDirectoriesExpanded = useFileTreeSelector(model, (currentModel) =>
308 areAllDirectoriesExpanded(currentModel, expandableDirectoryPaths),
309 );
310 const toggleAllDirectories = () => {
311 const expanded = !(expandAll || allDirectoriesExpanded);
312 setExpandAll(expanded);
313 setAllDirectoriesExpanded(
314 model,
315 expanded ? expandableDirectoryPaths : directoryPaths,
316 expanded,
317 );
318 };
319 const closeSearch = () => {
320 setQuery("");
321 search.close();
322 };
323 const expandedPathsRef = useRef(new Set<string>());
324 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the Pierre tree model to load directories as they are expanded
325 useEffect(() => {
326 const currentPaths = new Set(directoryPaths);
327 for (const path of expandedPathsRef.current) {
328 if (!currentPaths.has(path)) expandedPathsRef.current.delete(path);
329 }
330 const loadExpanded = () => {
331 if (model.isSearchOpen()) return;
332 for (const path of directoryPaths) {
333 const item = model.getItem(path);
334 if (item?.isDirectory() && "isExpanded" in item && item.isExpanded()) {
335 if (!expandedPathsRef.current.has(path)) {
336 expandedPathsRef.current.add(path);
337 void load(path.replace(/\/$/, ""));
338 }
339 } else {
340 if (item?.isDirectory() && expandedPathsRef.current.has(path)) setExpandAll(false);
341 expandedPathsRef.current.delete(path);
342 }
343 }
344 };
345 loadExpanded();
346 return model.subscribe(loadExpanded);
347 }, [directoryPaths, load, model]);
348 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes ignored-file status into the imperative Pierre tree model
349 useEffect(() => {
350 model.setGitStatus(
351 entries
352 .filter((entry) => entry.ignored)
353 .map((entry) => ({
354 path: treePath(entry),
355 status: "ignored",
356 })),
357 );
358 }, [entries, model]);
359 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- loads the selected file's ancestor directories and aborts on cleanup
360 useEffect(() => {
361 if (!selectedPath) return;
362 const controller = new AbortController();
363 void loadFileAncestors(selectedPath, load, { signal: controller.signal });
364 return () => {
365 controller.abort();
366 };
367 }, [load, selectedPath]);
368 const handleSearchValueChange = (value: string) => {
369 setQuery(value);
370 if (value.trim().length === 0) {
371 search.close();
372 return;
373 }
374 search.setValue(value);
375 };
376 const handleRefresh = () => {
377 refresh();
378 if (query.trim()) pathSearch.refresh();
379 onRefreshSelectedFile?.();
380 };
381 useWorkspaceMutationRefresh({
382 mutationId: workspaceMutationId,
383 refresh: () => {
384 refresh();
385 if (query.trim()) pathSearch.refresh();
386 },
387 resourceKey: `files:${environmentId}:${cwd}`,
388 });
389
390 // 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
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 // 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
406 useEffect(() => {
407 if (expandAll && !query.trim())
408 setAllDirectoriesExpanded(model, expandableDirectoryPaths, true);
409 }, [expandableDirectoryPaths, expandAll, model, query]);
410
411 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reveals an externally selected path in the Pierre tree model by expanding, selecting and scrolling
412 useEffect(() => {
413 if (!selectedPath) {
414 handledRevealRef.current = null;
415 return;
416 }
417 const selectedKind = entryKinds.get(selectedPath);
418 if (selectedKind === undefined) {
419 handledRevealRef.current = null;
420 return;
421 }
422 const revealRequest = { path: selectedPath, revealId: selectedPathRevealId };
423 const handledReveal = handledRevealRef.current;
424 // Refresh rebuilds treePaths; replaying handled reveals would close search and steal focus.
425 if (
426 handledReveal?.path === revealRequest.path &&
427 handledReveal.revealId === revealRequest.revealId
428 ) {
429 return;
430 }
431 const selectedTreePath = selectedKind === "directory" ? `${selectedPath}/` : selectedPath;
432 const selectedItem = model.getItem(selectedTreePath);
433 if (!selectedItem) return;
434
435 // Reveal only external selections; tree selections are visible and re-revealing would close search.
436 const selectedInTree = model
437 .getSelectedPaths()
438 .some((path) => path.replace(/\/$/, "") === selectedPath);
439 if (selectedInTree && treeSelectionPathRef.current === selectedPath) {
440 treeSelectionPathRef.current = null;
441 handledRevealRef.current = revealRequest;
442 return;
443 }
444 treeSelectionPathRef.current = null;
445 handledRevealRef.current = revealRequest;
446
447 syncingSelectionRef.current = true;
448 setQuery("");
449 model.closeSearch();
450 for (const path of model.getSelectedPaths()) {
451 model.getItem(path)?.deselect();
452 }
453
454 // Directory paths include trailing slashes; ancestor lookups must match.
455 const segments = selectedPath.split("/");
456 let ancestorPath = "";
457 for (const segment of segments.slice(0, -1)) {
458 ancestorPath = ancestorPath ? `${ancestorPath}/${segment}` : segment;
459 const item = model.getItem(`${ancestorPath}/`) ?? model.getItem(ancestorPath);
460 if (item && "expand" in item) item.expand();
461 }
462
463 if ("expand" in selectedItem) selectedItem.expand();
464 selectedItem.select();
465 model.scrollToPath(selectedTreePath, {
466 focus: true,
467 offset: "center",
468 });
469 queueMicrotask(() => {
470 syncingSelectionRef.current = false;
471 });
472 }, [entryKinds, model, selectedPath, selectedPathRevealId]);
473
474 return (
475 <div
476 className="flex min-h-0 flex-1 flex-col bg-background"
477 data-file-browser-panel={`${environmentId}:${cwd}`}
478 // Capture runs before the tree's shadow-internal row handler opens the menu.
479 onContextMenuCapture={(event) => {
480 contextMenuPointerRef.current = { x: event.clientX, y: event.clientY, at: event.timeStamp };
481 }}
482 // Capture dragstart before the tree selects the row so selection sees the drag flag.
483 onDragStartCapture={(event) => dragMention.handleDragStart(event.nativeEvent)}
484 onDragEnd={() => dragMention.handleDragEnd((path) => model.getItem(path)?.deselect())}
485 >
486 <div
487 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"
488 data-surface-subheader
489 >
490 <RefreshFilesButton isPending={isPending} onRefresh={handleRefresh} />
491 <FileSearchField
492 name="project-files-search"
493 ariaLabel={`Search ${projectName} files`}
494 value={search.value}
495 onValueChange={handleSearchValueChange}
496 onClose={closeSearch}
497 />
498 {directoryPaths.length > 0 && !hostFolder ? (
499 <Tooltip>
500 <TooltipTrigger
501 render={
502 <Button
503 type="button"
504 size="icon-xs"
505 variant="ghost"
506 aria-label={
507 expandAll || allDirectoriesExpanded
508 ? "Collapse all folders"
509 : "Expand all folders"
510 }
511 onClick={toggleAllDirectories}
512 />
513 }
514 >
515 {allDirectoriesExpanded ? (
516 <ChevronsDownUpIcon className="size-3.5" />
517 ) : (
518 <ChevronsUpDownIcon className="size-3.5" />
519 )}
520 </TooltipTrigger>
521 <TooltipPopup>
522 {expandAll || allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
523 </TooltipPopup>
524 </Tooltip>
525 ) : null}
526 </div>
527 {error || pathSearch.error ? (
528 <button
529 type="button"
530 onClick={handleRefresh}
531 className="p-4 text-left text-xs leading-relaxed text-destructive"
532 >
533 {error ?? pathSearch.error} Click to retry.
534 </button>
535 ) : null}
536 {query.trim() && pathSearch.truncated && !pathSearch.isPending ? (
537 <div className="px-3 py-1 text-xs text-muted-foreground">
538 More matches available. Refine your search.
539 </div>
540 ) : null}
541 {(!ready || pathSearch.isPending) && (
542 <div
543 role="status"
544 className={
545 entries.length > 0 && !hasNoSearchMatches
546 ? "sr-only"
547 : "px-3 py-1 text-xs text-muted-foreground"
548 }
549 >
550 Loading files…
551 </div>
552 )}
553 {hasNoSearchMatches ? (
554 ready && !isPending && !pathSearch.isPending && !error && !pathSearch.error ? (
555 <div role="status" className="px-3 py-4 text-xs text-muted-foreground">
556 No matching files.
557 </div>
558 ) : null
559 ) : (
560 <FileTree
561 model={model}
562 aria-label={`${projectName} files`}
563 className="min-h-0 flex-1 overflow-hidden"
564 style={pierreTreeStyle(resolvedTheme)}
565 />
566 )}
567 </div>
568 );
569}