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

FileBrowserPanel.tsx

579 lines20.9 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 useEffect(() => {
177 const capturePointer = (event: MouseEvent) => {
178 contextMenuPointerRef.current = { x: event.clientX, y: event.clientY, at: event.timeStamp };
179 };
180 document.addEventListener("contextmenu", capturePointer, true);
181 return () => document.removeEventListener("contextmenu", capturePointer, true);
182 }, []);
183​
184 const showEntryContextMenu = useStableCallback(
185 (item: TreeContextMenuItem, context: TreeContextMenuOpenContext) => {
186 const api = readLocalApi();
187 if (!api) {
188 context.close();
189 return;
190 }
191 const relativePath = item.path.replace(/\/$/, "");
192 const mention = serializeComposerFileLink(panelPath(relativePath));
193 const pointer = contextMenuPointerRef.current;
194 const pointerIsFresh = pointer !== null && performance.now() - pointer.at < 1000;
195 const anchorRect = context.anchorElement.getBoundingClientRect();
196 const position = pointerIsFresh
197 ? { x: pointer.x, y: pointer.y }
198 : { x: anchorRect.left, y: anchorRect.bottom };
199 const fileTarget = { environmentId, filePath: relativePath, workspaceRoot: cwd };
200 const fileMenuItems = fileContextMenu.buildItems(fileTarget);
201 void settlePromise(async () => {
202 const clicked = await api.contextMenu.show(
203 [
204 ...fileMenuItems,
205 { id: "copy-mention", label: "Copy mention" },
206 { id: "add-to-chat", label: "Add to chat" },
207 ],
208 position,
209 );
210 if (clicked === null) return;
211 // Open-with submenu ids are absent from the top-level item list.
212 const isFileMenuAction =
213 fileMenuItems.some((entry) => entry.id === clicked) || clicked.startsWith("editor:");
214 if (isFileMenuAction) {
215 await fileContextMenu.activate(clicked as FileContextMenuAction, fileTarget);
216 return;
217 }
218 if (clicked === "copy-mention") {
219 try {
220 await writeTextToClipboard(mention);
221 toastManager.add({
222 type: "success",
223 title: "Mention copied",
224 description: relativePath,
225 });
226 } catch (error) {
227 toastManager.add({
228 type: "error",
229 title: "Failed to copy mention",
230 description: error instanceof Error ? error.message : "An error occurred.",
231 });
232 }
233 return;
234 }
235 if (clicked === "add-to-chat") {
236 const composer = composerRef?.current;
237 if (!composer) {
238 toastManager.add({
239 type: "error",
240 title: "Unable to add to chat",
241 description: "Open a chat for this project and try again.",
242 });
243 return;
244 }
245 const inserted = composer.insertTextAtEnd(`${mention} `, { ensureLeadingBoundary: true });
246 if (!inserted) {
247 toastManager.add({
248 type: "error",
249 title: "Unable to add to chat",
250 description: "The chat isn't ready to accept input right now.",
251 });
252 }
253 }
254 }).then((result) => {
255 context.close();
256 if (!AsyncResult.isSuccess(result)) throw Cause.squash(result.cause);
257 });
258 },
259 );
260​
261 const loadingDirectoriesRef = useRef(loadingDirectories);
262 const dragMention = createFileTreeDragMentionController(
263 hostFolder ? { mentionPath: (path: string) => joinHostPath(cwd, path) } : {},
264 );
265 const { model } = useFileTree({
266 composition: {
267 contextMenu: {
268 triggerMode: "right-click",
269 onOpen: (item, context) => {
270 showEntryContextMenu(item, context);
271 },
272 },
273 },
274 dragAndDrop: { canDrop: () => false },
275 density: "compact",
276 fileTreeSearchMode: "hide-non-matches",
277 flattenEmptyDirectories: true,
278 initialExpansion: "closed",
279 icons: T3_PIERRE_ICONS,
280 onSelectionChange: (selectedPaths) => {
281 // Update drag selection even for reveals so subsequent drags cannot use stale paths.
282 dragMention.handleSelectionChange(selectedPaths);
283 if (syncingSelectionRef.current) return;
284 if (dragMention.isDragInProgress()) {
285 return;
286 }
287 const selectedPath = selectedPaths.at(-1)?.replace(/\/$/, "");
288 if (selectedPath && entryKindsRef.current.get(selectedPath) === "file") {
289 treeSelectionPathRef.current = selectedPath;
290 onOpenFile(panelPath(selectedPath));
291 }
292 },
293 paths: [],
294 renderRowDecoration: ({ item, row }) =>
295 row.kind === "directory" &&
296 row.isExpanded &&
297 loadingDirectoriesRef.current.has(item.path.replace(/\/$/, ""))
298 ? { icon: "t3-tree-icon-loading", title: "Loading…" }
299 : null,
300 search: false,
301 onSearchChange: (value) => setQuery(value ?? ""),
302 unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
303 });
304 useEffect(() => {
305 if (loadingDirectoriesRef.current === loadingDirectories) return;
306 loadingDirectoriesRef.current = loadingDirectories;
307 model.setComposition(model.getComposition());
308 }, [loadingDirectories, model]);
309 const search = useFileTreeSearch(model);
310 // Pierre restores the unfiltered tree when a search has no matches.
311 const hasNoSearchMatches = search.value.trim().length > 0 && search.matchingPaths.length === 0;
312 const allDirectoriesExpanded = useFileTreeSelector(model, (currentModel) =>
313 areAllDirectoriesExpanded(currentModel, expandableDirectoryPaths),
314 );
315 const toggleAllDirectories = () => {
316 const expanded = !(expandAll || allDirectoriesExpanded);
317 setExpandAll(expanded);
318 setAllDirectoriesExpanded(
319 model,
320 expanded ? expandableDirectoryPaths : directoryPaths,
321 expanded,
322 );
323 };
324 const closeSearch = () => {
325 setQuery("");
326 search.close();
327 };
328 const expandedPathsRef = useRef(new Set<string>());
329 useEffect(() => {
330 const currentPaths = new Set(directoryPaths);
331 for (const path of expandedPathsRef.current) {
332 if (!currentPaths.has(path)) expandedPathsRef.current.delete(path);
333 }
334 const loadExpanded = () => {
335 if (model.isSearchOpen()) return;
336 for (const path of directoryPaths) {
337 const item = model.getItem(path);
338 if (item?.isDirectory() && "isExpanded" in item && item.isExpanded()) {
339 if (!expandedPathsRef.current.has(path)) {
340 expandedPathsRef.current.add(path);
341 void load(path.replace(/\/$/, ""));
342 }
343 } else {
344 if (item?.isDirectory() && expandedPathsRef.current.has(path)) setExpandAll(false);
345 expandedPathsRef.current.delete(path);
346 }
347 }
348 };
349 loadExpanded();
350 return model.subscribe(loadExpanded);
351 }, [directoryPaths, load, model]);
352 useEffect(() => {
353 model.setGitStatus(
354 entries
355 .filter((entry) => entry.ignored)
356 .map((entry) => ({
357 path: treePath(entry),
358 status: "ignored",
359 })),
360 );
361 }, [entries, model]);
362 useEffect(() => {
363 if (!selectedPath) return;
364 const controller = new AbortController();
365 void loadFileAncestors(selectedPath, load, { signal: controller.signal });
366 return () => {
367 controller.abort();
368 };
369 }, [load, selectedPath]);
370 const handleSearchValueChange = (value: string) => {
371 setQuery(value);
372 if (value.trim().length === 0) {
373 search.close();
374 return;
375 }
376 search.setValue(value);
377 };
378 const handleRefresh = () => {
379 refresh();
380 if (query.trim()) pathSearch.refresh();
381 onRefreshSelectedFile?.();
382 };
383 useWorkspaceMutationRefresh({
384 mutationId: workspaceMutationId,
385 refresh: () => {
386 refresh();
387 if (query.trim()) pathSearch.refresh();
388 },
389 resourceKey: `files:${environmentId}:${cwd}`,
390 });
391​
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 useEffect(() => {
407 if (expandAll && !query.trim())
408 setAllDirectoriesExpanded(model, expandableDirectoryPaths, true);
409 }, [expandableDirectoryPaths, expandAll, model, query]);
410​
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 // Capture dragstart before the tree selects the row so selection sees the drag flag.
474 const panelRef = useRef<HTMLDivElement | null>(null);
475 useEffect(() => {
476 const panel = panelRef.current;
477 if (panel === null) {
478 return;
479 }
480 const handleDragStart = (event: DragEvent) => dragMention.handleDragStart(event);
481 const handleDragEnd = () =>
482 dragMention.handleDragEnd((path) => model.getItem(path)?.deselect());
483 panel.addEventListener("dragstart", handleDragStart, true);
484 panel.addEventListener("dragend", handleDragEnd);
485 return () => {
486 panel.removeEventListener("dragstart", handleDragStart, true);
487 panel.removeEventListener("dragend", handleDragEnd);
488 };
489 }, [dragMention, model]);
490​
491 return (
492 <div
493 ref={panelRef}
494 className="flex min-h-0 flex-1 flex-col bg-background"
495 data-file-browser-panel={`${environmentId}:${cwd}`}
496 >
497 <div
498 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"
499 data-surface-subheader
500 >
501 <RefreshFilesButton isPending={isPending} onRefresh={handleRefresh} />
502 <FileSearchField
503 name="project-files-search"
504 ariaLabel={`Search ${projectName} files`}
505 value={search.value}
506 onValueChange={handleSearchValueChange}
507 onClose={closeSearch}
508 />
509 {directoryPaths.length > 0 && !hostFolder ? (
510 <Tooltip>
511 <TooltipTrigger
512 render={
513 <Button
514 type="button"
515 size="icon-xs"
516 variant="ghost"
517 aria-label={
518 expandAll || allDirectoriesExpanded
519 ? "Collapse all folders"
520 : "Expand all folders"
521 }
522 onClick={toggleAllDirectories}
523 />
524 }
525 >
526 <MorphIcon
527 className="size-3.5"
528 icon={allDirectoriesExpanded ? ChevronsDownUp : ChevronsUpDown}
529 />
530 </TooltipTrigger>
531 <TooltipPopup>
532 {expandAll || allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
533 </TooltipPopup>
534 </Tooltip>
535 ) : null}
536 </div>
537 {error || pathSearch.error ? (
538 <button
539 type="button"
540 onClick={handleRefresh}
541 className="p-4 text-left text-xs leading-relaxed text-destructive"
542 >
543 {error ?? pathSearch.error} Click to retry.
544 </button>
545 ) : null}
546 {query.trim() && pathSearch.truncated && !pathSearch.isPending ? (
547 <div className="px-3 py-1 text-xs text-muted-foreground">
548 More matches available. Refine your search.
549 </div>
550 ) : null}
551 {(!ready || pathSearch.isPending) && (
552 <div
553 role="status"
554 className={
555 entries.length > 0 && !hasNoSearchMatches
556 ? "sr-only"
557 : "px-3 py-1 text-xs text-muted-foreground"
558 }
559 >
560 Loading files…
561 </div>
562 )}
563 {hasNoSearchMatches ? (
564 ready && !isPending && !pathSearch.isPending && !error && !pathSearch.error ? (
565 <div role="status" className="px-3 py-4 text-xs text-muted-foreground">
566 No matching files.
567 </div>
568 ) : null
569 ) : (
570 <FileTree
571 model={model}
572 aria-label={`${projectName} files`}
573 className="min-h-0 flex-1 overflow-hidden"
574 style={pierreTreeStyle(resolvedTheme)}
575 />
576 )}
577 </div>
578 );