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 /** Host-folder entries use absolute paths. Avoid full traversal: disable expand-all and search only
46 * loaded folders. */
47 hostFolder?: boolean;
48 onRefreshSelectedFile?: () => void;
49 workspaceMutationId: string | null;
50}
51
52function treePath(entry: ProjectEntry): string {
53 return entry.kind === "directory" ? `${entry.path}/` : entry.path;
54}
55
56function RefreshFilesButton(props: { isPending: boolean; onRefresh: () => void }) {
57 return (
58 <Tooltip>
59 <TooltipTrigger
60 render={
61 <Button
62 type="button"
63 variant="ghost"
64 size="icon-xs"
65 aria-label="Refresh workspace files"
66 onClick={props.onRefresh}
67 />
68 }
69 >
70 <RefreshIcon refreshing={props.isPending} />
71 </TooltipTrigger>
72 <TooltipPopup>{props.isPending ? "Refreshing…" : "Refresh files"}</TooltipPopup>
73 </Tooltip>
74 );
75}
76
77function FileSearchField(props: {
78 ariaLabel: string;
79 name: string;
80 onClose: () => void;
81 onValueChange: (value: string) => void;
82 value: string;
83}) {
84 return (
85 <InputGroup variant="ghost" className="h-7 min-w-0 flex-1">
86 <InputGroupInput
87 type="search"
88 name={props.name}
89 size="sm"
90 value={props.value}
91 aria-label={props.ariaLabel}
92 placeholder="Search files"
93 data-workspace-focus-default
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
106function buildTreeEntries(
107 directoryEntries: readonly ProjectEntry[],
108 searchEntries: readonly ProjectEntry[],
109 searchPending: boolean,
110 query: string,
111) {
112 const result = new Map(directoryEntries.map((entry) => [entry.path, entry]));
113 if (query.trim() && !searchPending) {
114 for (const entry of searchEntries) {
115 if (!result.has(entry.path)) result.set(entry.path, entry);
116 const segments = entry.path.split("/");
117 for (let index = 1; index < segments.length; index++) {
118 const path = segments.slice(0, index).join("/");
119 if (!result.has(path)) result.set(path, { path, kind: "directory" });
120 }
121 }
122 }
123 const entries = [...result.values()];
124 const entryKinds: ReadonlyMap<string, ProjectEntry["kind"]> = new Map(
125 entries.map((entry) => [entry.path, entry.kind] as const),
126 );
127 const treePaths = entries.map(treePath);
128 const directories = entries.filter((entry) => entry.kind === "directory");
129 const directoryPaths = directories.map(treePath);
130 // Expanding a folder lists it, and an ignored one such as `node_modules` can hold tens of
131 // thousands, so expand all skips ignored folders. They still open by hand.
132 const expandableDirectoryPaths = directories.filter((entry) => !entry.ignored).map(treePath);
133 return { entries, entryKinds, treePaths, directoryPaths, expandableDirectoryPaths };
134}
135
136export default function FileBrowserPanel({
137 environmentId,
138 cwd,
139 projectName,
140 selectedPath,
141 selectedPathRevealId,
142 onOpenFile,
143 onRefreshSelectedFile,
144 workspaceMutationId,
145 hostFolder = false,
146}: FileBrowserPanelProps) {
147 const panelPath = (relativePath: string) =>
148 hostFolder ? joinHostPath(cwd, relativePath) : relativePath;
149 const { resolvedTheme } = useTheme();
150 const composerRef = useComposerHandleContext();
151 const fileContextMenu = useFileContextMenu(environmentId);
152 const {
153 entries: directoryEntries,
154 load,
155 refresh,
156 ready,
157 error,
158 isPending,
159 loadingDirectories,
160 } = useDirectoryEntries(environmentId, cwd);
161 const [query, setQuery] = useState("");
162 const [expandAll, setExpandAll] = useState(false);
163 const pathSearch = useProjectPathSearch(
164 { environmentId, cwd: hostFolder ? null : cwd, query: query.slice(0, 256) },
165 200,
166 );
167 const { entries, entryKinds, treePaths, directoryPaths, expandableDirectoryPaths } =
168 buildTreeEntries(directoryEntries, pathSearch.entries, pathSearch.isPending, query);
169 const entryKindsRef = useRef(entryKinds);
170 const previousTreePathsRef = useRef<readonly string[] | null>(null);
171 const syncingSelectionRef = useRef(false);
172 const treeSelectionPathRef = useRef<string | null>(null);
173 const handledRevealRef = useRef<{ path: string; revealId: number } | null>(null);
174
175 // Shadow-DOM row rects are unreliable; capture the composed contextmenu event's viewport position.
176 const contextMenuPointerRef = useRef<{ x: number; y: number; at: number } | null>(null);
177
178 const showEntryContextMenu = useStableCallback(
179 (item: TreeContextMenuItem, context: TreeContextMenuOpenContext) => {
180 const api = readLocalApi();
181 if (!api) {
182 context.close();
183 return;
184 }
185 const relativePath = item.path.replace(/\/$/, "");
186 const mention = serializeComposerFileLink(panelPath(relativePath));
187 const pointer = contextMenuPointerRef.current;
188 const pointerIsFresh = pointer !== null && performance.now() - pointer.at < 1000;
189 const anchorRect = context.anchorElement.getBoundingClientRect();
190 const position = pointerIsFresh
191 ? { x: pointer.x, y: pointer.y }
192 : { x: anchorRect.left, y: anchorRect.bottom };
193 const fileTarget = { environmentId, filePath: relativePath, workspaceRoot: cwd };
194 const fileMenuItems = fileContextMenu.buildItems(fileTarget);
195 void settlePromise(async () => {
196 const clicked = await api.contextMenu.show(
197 [
198 ...fileMenuItems,
199 { id: "copy-mention", label: "Copy mention" },
200 { id: "add-to-chat", label: "Add to chat" },
201 ],
202 position,
203 );
204 if (clicked === null) return;
205 // Open-with submenu ids are absent from the top-level item list.
206 const isFileMenuAction =
207 fileMenuItems.some((entry) => entry.id === clicked) || clicked.startsWith("editor:");
208 if (isFileMenuAction) {
209 await fileContextMenu.activate(clicked as FileContextMenuAction, fileTarget);
210 return;
211 }
212 if (clicked === "copy-mention") {
213 try {
214 await writeTextToClipboard(mention);
215 toastManager.add({
216 type: "success",
217 title: "Mention copied",
218 description: relativePath,
219 });
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 }).then((result) => {
249 context.close();
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 <MorphIcon
516 className="size-3.5"
517 icon={allDirectoriesExpanded ? ChevronsDownUp : ChevronsUpDown}
518 />
519 </TooltipTrigger>
520 <TooltipPopup>
521 {expandAll || allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
522 </TooltipPopup>
523 </Tooltip>
524 ) : null}
525 </div>
526 {error || pathSearch.error ? (
527 <button
528 type="button"
529 onClick={handleRefresh}
530 className="p-4 text-left text-xs leading-relaxed text-destructive"
531 >
532 {error ?? pathSearch.error} Click to retry.
533 </button>
534 ) : null}
535 {query.trim() && pathSearch.truncated && !pathSearch.isPending ? (
536 <div className="px-3 py-1 text-xs text-muted-foreground">
537 More matches available. Refine your search.
538 </div>
539 ) : null}
540 {(!ready || pathSearch.isPending) && (
541 <div
542 role="status"
543 className={
544 entries.length > 0 && !hasNoSearchMatches
545 ? "sr-only"
546 : "px-3 py-1 text-xs text-muted-foreground"
547 }
548 >
549 Loading files…
550 </div>
551 )}
552 {hasNoSearchMatches ? (
553 ready && !isPending && !pathSearch.isPending && !error && !pathSearch.error ? (
554 <div role="status" className="px-3 py-4 text-xs text-muted-foreground">
555 No matching files.
556 </div>
557 ) : null
558 ) : (
559 <FileTree
560 model={model}
561 aria-label={`${projectName} files`}
562 className="min-h-0 flex-1 overflow-hidden"
563 style={pierreTreeStyle(resolvedTheme)}
564 />
565 )}
566 </div>
567 );
568}