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

FileBrowserPanel.tsx

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