Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

FileBrowserPanel.tsx

600 lines22.8 KB

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