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 // The app menu owns focus; the tree's outside-click handler would dismiss it before click.
196 context.close({ restoreFocus: !pointerIsFresh });
197 void settlePromise(async () => {
198 const clicked = await api.contextMenu.show(
199 [
200 ...fileMenuItems,
201 { id: "copy-mention", label: "Copy mention" },
202 { id: "add-to-chat", label: "Add to chat" },
203 ],
204 position,
205 );
206 if (clicked === null) return;
207 // Open-with submenu ids are absent from the top-level item list.
208 const isFileMenuAction =
209 fileMenuItems.some((entry) => entry.id === clicked) || clicked.startsWith("editor:");
210 if (isFileMenuAction) {
211 await fileContextMenu.activate(clicked as FileContextMenuAction, fileTarget);
212 return;
213 }
214 if (clicked === "copy-mention") {
215 try {
216 await writeTextToClipboard(mention);
217 toastManager.add({
218 type: "success",
219 title: "Mention copied",
220 description: relativePath,
221 });
222 } catch (error) {
223 toastManager.add({
224 type: "error",
225 title: "Failed to copy mention",
226 description: error instanceof Error ? error.message : "An error occurred.",
227 });
228 }
229 return;
230 }
231 if (clicked === "add-to-chat") {
232 const composer = composerRef?.current;
233 if (!composer) {
234 toastManager.add({
235 type: "error",
236 title: "Unable to add to chat",
237 description: "Open a chat for this project and try again.",
238 });
239 return;
240 }
241 const inserted = composer.insertTextAtEnd(`${mention} `, { ensureLeadingBoundary: true });
242 if (!inserted) {
243 toastManager.add({
244 type: "error",
245 title: "Unable to add to chat",
246 description: "The chat isn't ready to accept input right now.",
247 });
248 }
249 }
250 }).then((result) => {
251 if (!AsyncResult.isSuccess(result)) throw Cause.squash(result.cause);
252 });
253 },
254 );
255
256 const loadingDirectoriesRef = useRef(loadingDirectories);
257 const dragMention = createFileTreeDragMentionController(
258 hostFolder ? { mentionPath: (path: string) => joinHostPath(cwd, path) } : {},
259 );
260 const { model } = useFileTree({
261 composition: {
262 contextMenu: {
263 triggerMode: "right-click",
264 onOpen: (item, context) => {
265 showEntryContextMenu(item, context);
266 },
267 },
268 },
269 dragAndDrop: { canDrop: () => false },
270 density: "compact",
271 fileTreeSearchMode: "hide-non-matches",
272 flattenEmptyDirectories: true,
273 initialExpansion: "closed",
274 icons: T3_PIERRE_ICONS,
275 onSelectionChange: (selectedPaths) => {
276 // Update drag selection even for reveals so subsequent drags cannot use stale paths.
277 dragMention.handleSelectionChange(selectedPaths);
278 if (syncingSelectionRef.current) return;
279 if (dragMention.isDragInProgress()) {
280 return;
281 }
282 const selectedPath = selectedPaths.at(-1)?.replace(/\/$/, "");
283 if (selectedPath && entryKindsRef.current.get(selectedPath) === "file") {
284 treeSelectionPathRef.current = selectedPath;
285 onOpenFile(panelPath(selectedPath));
286 }
287 },
288 paths: [],
289 renderRowDecoration: ({ item, row }) =>
290 row.kind === "directory" &&
291 row.isExpanded &&
292 loadingDirectoriesRef.current.has(item.path.replace(/\/$/, ""))
293 ? { icon: "t3-tree-icon-loading", title: "Loading…" }
294 : null,
295 search: false,
296 onSearchChange: (value) => setQuery(value ?? ""),
297 unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
298 });
299 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- makes the Pierre tree model re-render row decorations when loading directories change
300 useEffect(() => {
301 if (loadingDirectoriesRef.current === loadingDirectories) return;
302 loadingDirectoriesRef.current = loadingDirectories;
303 model.setComposition(model.getComposition());
304 }, [loadingDirectories, model]);
305 const search = useFileTreeSearch(model);
306 // Pierre restores the unfiltered tree when a search has no matches.
307 const hasNoSearchMatches = search.value.trim().length > 0 && search.matchingPaths.length === 0;
308 const allDirectoriesExpanded = useFileTreeSelector(model, (currentModel) =>
309 areAllDirectoriesExpanded(currentModel, expandableDirectoryPaths),
310 );
311 const toggleAllDirectories = () => {
312 const expanded = !(expandAll || allDirectoriesExpanded);
313 setExpandAll(expanded);
314 setAllDirectoriesExpanded(
315 model,
316 expanded ? expandableDirectoryPaths : directoryPaths,
317 expanded,
318 );
319 };
320 const closeSearch = () => {
321 setQuery("");
322 search.close();
323 };
324 const expandedPathsRef = useRef(new Set<string>());
325 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the Pierre tree model to load directories as they are expanded
326 useEffect(() => {
327 const currentPaths = new Set(directoryPaths);
328 for (const path of expandedPathsRef.current) {
329 if (!currentPaths.has(path)) expandedPathsRef.current.delete(path);
330 }
331 const loadExpanded = () => {
332 if (model.isSearchOpen()) return;
333 for (const path of directoryPaths) {
334 const item = model.getItem(path);
335 if (item?.isDirectory() && "isExpanded" in item && item.isExpanded()) {
336 if (!expandedPathsRef.current.has(path)) {
337 expandedPathsRef.current.add(path);
338 void load(path.replace(/\/$/, ""));
339 }
340 } else {
341 if (item?.isDirectory() && expandedPathsRef.current.has(path)) setExpandAll(false);
342 expandedPathsRef.current.delete(path);
343 }
344 }
345 };
346 loadExpanded();
347 return model.subscribe(loadExpanded);
348 }, [directoryPaths, load, model]);
349 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes ignored-file status into the imperative Pierre tree model
350 useEffect(() => {
351 model.setGitStatus(
352 entries
353 .filter((entry) => entry.ignored)
354 .map((entry) => ({
355 path: treePath(entry),
356 status: "ignored",
357 })),
358 );
359 }, [entries, model]);
360 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- loads the selected file's ancestor directories and aborts on cleanup
361 useEffect(() => {
362 if (!selectedPath) return;
363 const controller = new AbortController();
364 void loadFileAncestors(selectedPath, load, { signal: controller.signal });
365 return () => {
366 controller.abort();
367 };
368 }, [load, selectedPath]);
369 const handleSearchValueChange = (value: string) => {
370 setQuery(value);
371 if (value.trim().length === 0) {
372 search.close();
373 return;
374 }
375 search.setValue(value);
376 };
377 const handleRefresh = () => {
378 refresh();
379 if (query.trim()) pathSearch.refresh();
380 onRefreshSelectedFile?.();
381 };
382 useWorkspaceMutationRefresh({
383 mutationId: workspaceMutationId,
384 refresh: () => {
385 refresh();
386 if (query.trim()) pathSearch.refresh();
387 },
388 resourceKey: `files:${environmentId}:${cwd}`,
389 });
390
391 // 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
392 useEffect(() => {
393 if (!ready) return;
394 if (previousTreePathsRef.current === treePaths) return;
395 entryKindsRef.current = entryKinds;
396 const previousTreePaths = previousTreePathsRef.current;
397 previousTreePathsRef.current = treePaths;
398 if (previousTreePaths === null) {
399 model.resetPaths(treePaths);
400 return;
401 }
402 const updates = buildFileTreePathUpdates(previousTreePaths, treePaths);
403 if (updates.length > 0) model.batch(updates);
404 }, [ready, entryKinds, model, treePaths]);
405
406 // 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
407 useEffect(() => {
408 if (expandAll && !query.trim())
409 setAllDirectoriesExpanded(model, expandableDirectoryPaths, true);
410 }, [expandableDirectoryPaths, expandAll, model, query]);
411
412 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reveals an externally selected path in the Pierre tree model by expanding, selecting and scrolling
413 useEffect(() => {
414 if (!selectedPath) {
415 handledRevealRef.current = null;
416 return;
417 }
418 const selectedKind = entryKinds.get(selectedPath);
419 if (selectedKind === undefined) {
420 handledRevealRef.current = null;
421 return;
422 }
423 const revealRequest = { path: selectedPath, revealId: selectedPathRevealId };
424 const handledReveal = handledRevealRef.current;
425 // Refresh rebuilds treePaths; replaying handled reveals would close search and steal focus.
426 if (
427 handledReveal?.path === revealRequest.path &&
428 handledReveal.revealId === revealRequest.revealId
429 ) {
430 return;
431 }
432 const selectedTreePath = selectedKind === "directory" ? `${selectedPath}/` : selectedPath;
433 const selectedItem = model.getItem(selectedTreePath);
434 if (!selectedItem) return;
435
436 // Reveal only external selections; tree selections are visible and re-revealing would close search.
437 const selectedInTree = model
438 .getSelectedPaths()
439 .some((path) => path.replace(/\/$/, "") === selectedPath);
440 if (selectedInTree && treeSelectionPathRef.current === selectedPath) {
441 treeSelectionPathRef.current = null;
442 handledRevealRef.current = revealRequest;
443 return;
444 }
445 treeSelectionPathRef.current = null;
446 handledRevealRef.current = revealRequest;
447
448 syncingSelectionRef.current = true;
449 setQuery("");
450 model.closeSearch();
451 for (const path of model.getSelectedPaths()) {
452 model.getItem(path)?.deselect();
453 }
454
455 // Directory paths include trailing slashes; ancestor lookups must match.
456 const segments = selectedPath.split("/");
457 let ancestorPath = "";
458 for (const segment of segments.slice(0, -1)) {
459 ancestorPath = ancestorPath ? `${ancestorPath}/${segment}` : segment;
460 const item = model.getItem(`${ancestorPath}/`) ?? model.getItem(ancestorPath);
461 if (item && "expand" in item) item.expand();
462 }
463
464 if ("expand" in selectedItem) selectedItem.expand();
465 selectedItem.select();
466 model.scrollToPath(selectedTreePath, {
467 focus: true,
468 offset: "center",
469 });
470 queueMicrotask(() => {
471 syncingSelectionRef.current = false;
472 });
473 }, [entryKinds, model, selectedPath, selectedPathRevealId]);
474
475 return (
476 <div
477 className="flex min-h-0 flex-1 flex-col bg-background"
478 data-file-browser-panel={`${environmentId}:${cwd}`}
479 // Capture runs before the tree's shadow-internal row handler opens the menu.
480 onContextMenuCapture={(event) => {
481 contextMenuPointerRef.current = { x: event.clientX, y: event.clientY, at: event.timeStamp };
482 }}
483 // Capture dragstart before the tree selects the row so selection sees the drag flag.
484 onDragStartCapture={(event) => dragMention.handleDragStart(event.nativeEvent)}
485 onDragEnd={() => dragMention.handleDragEnd((path) => model.getItem(path)?.deselect())}
486 >
487 <div
488 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"
489 data-surface-subheader
490 >
491 <RefreshFilesButton isPending={isPending} onRefresh={handleRefresh} />
492 <FileSearchField
493 name="project-files-search"
494 ariaLabel={`Search ${projectName} files`}
495 value={search.value}
496 onValueChange={handleSearchValueChange}
497 onClose={closeSearch}
498 />
499 {directoryPaths.length > 0 && !hostFolder ? (
500 <Tooltip>
501 <TooltipTrigger
502 render={
503 <Button
504 type="button"
505 size="icon-xs"
506 variant="ghost"
507 aria-label={
508 expandAll || allDirectoriesExpanded
509 ? "Collapse all folders"
510 : "Expand all folders"
511 }
512 onClick={toggleAllDirectories}
513 />
514 }
515 >
516 <MorphIcon
517 className="size-3.5"
518 icon={allDirectoriesExpanded ? ChevronsDownUp : ChevronsUpDown}
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}