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

FileBrowserPanel.tsx

560 lines20.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 useEffect(() => {
298 if (loadingDirectoriesRef.current === loadingDirectories) return;
299 loadingDirectoriesRef.current = loadingDirectories;
300 model.setComposition(model.getComposition());
301 }, [loadingDirectories, model]);
302 const search = useFileTreeSearch(model);
303 // Pierre restores the unfiltered tree when a search has no matches.
304 const hasNoSearchMatches = search.value.trim().length > 0 && search.matchingPaths.length === 0;
305 const allDirectoriesExpanded = useFileTreeSelector(model, (currentModel) =>
306 areAllDirectoriesExpanded(currentModel, expandableDirectoryPaths),
307 );
308 const toggleAllDirectories = () => {
309 const expanded = !(expandAll || allDirectoriesExpanded);
310 setExpandAll(expanded);
311 setAllDirectoriesExpanded(
312 model,
313 expanded ? expandableDirectoryPaths : directoryPaths,
314 expanded,
315 );
316 };
317 const closeSearch = () => {
318 setQuery("");
319 search.close();
320 };
321 const expandedPathsRef = useRef(new Set<string>());
322 useEffect(() => {
323 const currentPaths = new Set(directoryPaths);
324 for (const path of expandedPathsRef.current) {
325 if (!currentPaths.has(path)) expandedPathsRef.current.delete(path);
326 }
327 const loadExpanded = () => {
328 if (model.isSearchOpen()) return;
329 for (const path of directoryPaths) {
330 const item = model.getItem(path);
331 if (item?.isDirectory() && "isExpanded" in item && item.isExpanded()) {
332 if (!expandedPathsRef.current.has(path)) {
333 expandedPathsRef.current.add(path);
334 void load(path.replace(/\/$/, ""));
335 }
336 } else {
337 if (item?.isDirectory() && expandedPathsRef.current.has(path)) setExpandAll(false);
338 expandedPathsRef.current.delete(path);
339 }
340 }
341 };
342 loadExpanded();
343 return model.subscribe(loadExpanded);
344 }, [directoryPaths, load, model]);
345 useEffect(() => {
346 model.setGitStatus(
347 entries
348 .filter((entry) => entry.ignored)
349 .map((entry) => ({
350 path: treePath(entry),
351 status: "ignored",
352 })),
353 );
354 }, [entries, model]);
355 useEffect(() => {
356 if (!selectedPath) return;
357 const controller = new AbortController();
358 void loadFileAncestors(selectedPath, load, { signal: controller.signal });
359 return () => {
360 controller.abort();
361 };
362 }, [load, selectedPath]);
363 const handleSearchValueChange = (value: string) => {
364 setQuery(value);
365 if (value.trim().length === 0) {
366 search.close();
367 return;
368 }
369 search.setValue(value);
370 };
371 const handleRefresh = () => {
372 refresh();
373 if (query.trim()) pathSearch.refresh();
374 onRefreshSelectedFile?.();
375 };
376 useWorkspaceMutationRefresh({
377 mutationId: workspaceMutationId,
378 refresh: () => {
379 refresh();
380 if (query.trim()) pathSearch.refresh();
381 },
382 resourceKey: `files:${environmentId}:${cwd}`,
383 });
384​
385 useEffect(() => {
386 if (!ready) return;
387 if (previousTreePathsRef.current === treePaths) return;
388 entryKindsRef.current = entryKinds;
389 const previousTreePaths = previousTreePathsRef.current;
390 previousTreePathsRef.current = treePaths;
391 if (previousTreePaths === null) {
392 model.resetPaths(treePaths);
393 return;
394 }
395 const updates = buildFileTreePathUpdates(previousTreePaths, treePaths);
396 if (updates.length > 0) model.batch(updates);
397 }, [ready, entryKinds, model, treePaths]);
398​
399 useEffect(() => {
400 if (expandAll && !query.trim())
401 setAllDirectoriesExpanded(model, expandableDirectoryPaths, true);
402 }, [expandableDirectoryPaths, expandAll, model, query]);
403​
404 useEffect(() => {
405 if (!selectedPath) {
406 handledRevealRef.current = null;
407 return;
408 }
409 const selectedKind = entryKinds.get(selectedPath);
410 if (selectedKind === undefined) {
411 handledRevealRef.current = null;
412 return;
413 }
414 const revealRequest = { path: selectedPath, revealId: selectedPathRevealId };
415 const handledReveal = handledRevealRef.current;
416 // Refresh rebuilds treePaths; replaying handled reveals would close search and steal focus.
417 if (
418 handledReveal?.path === revealRequest.path &&
419 handledReveal.revealId === revealRequest.revealId
420 ) {
421 return;
422 }
423 const selectedTreePath = selectedKind === "directory" ? `${selectedPath}/` : selectedPath;
424 const selectedItem = model.getItem(selectedTreePath);
425 if (!selectedItem) return;
426​
427 // Reveal only external selections; tree selections are visible and re-revealing would close search.
428 const selectedInTree = model
429 .getSelectedPaths()
430 .some((path) => path.replace(/\/$/, "") === selectedPath);
431 if (selectedInTree && treeSelectionPathRef.current === selectedPath) {
432 treeSelectionPathRef.current = null;
433 handledRevealRef.current = revealRequest;
434 return;
435 }
436 treeSelectionPathRef.current = null;
437 handledRevealRef.current = revealRequest;
438​
439 syncingSelectionRef.current = true;
440 setQuery("");
441 model.closeSearch();
442 for (const path of model.getSelectedPaths()) {
443 model.getItem(path)?.deselect();
444 }
445​
446 // Directory paths include trailing slashes; ancestor lookups must match.
447 const segments = selectedPath.split("/");
448 let ancestorPath = "";
449 for (const segment of segments.slice(0, -1)) {
450 ancestorPath = ancestorPath ? `${ancestorPath}/${segment}` : segment;
451 const item = model.getItem(`${ancestorPath}/`) ?? model.getItem(ancestorPath);
452 if (item && "expand" in item) item.expand();
453 }
454​
455 if ("expand" in selectedItem) selectedItem.expand();
456 selectedItem.select();
457 model.scrollToPath(selectedTreePath, {
458 focus: true,
459 offset: "center",
460 });
461 queueMicrotask(() => {
462 syncingSelectionRef.current = false;
463 });
464 }, [entryKinds, model, selectedPath, selectedPathRevealId]);
465​
466 return (
467 <div
468 className="flex min-h-0 flex-1 flex-col bg-background"
469 data-file-browser-panel={`${environmentId}:${cwd}`}
470 // Capture runs before the tree's shadow-internal row handler opens the menu.
471 onContextMenuCapture={(event) => {
472 contextMenuPointerRef.current = { x: event.clientX, y: event.clientY, at: event.timeStamp };
473 }}
474 // Capture dragstart before the tree selects the row so selection sees the drag flag.
475 onDragStartCapture={(event) => dragMention.handleDragStart(event.nativeEvent)}
476 onDragEnd={() => dragMention.handleDragEnd((path) => model.getItem(path)?.deselect())}
477 >
478 <div
479 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"
480 data-surface-subheader
481 >
482 <RefreshFilesButton isPending={isPending} onRefresh={handleRefresh} />
483 <FileSearchField
484 name="project-files-search"
485 ariaLabel={`Search ${projectName} files`}
486 value={search.value}
487 onValueChange={handleSearchValueChange}
488 onClose={closeSearch}
489 />
490 {directoryPaths.length > 0 && !hostFolder ? (
491 <Tooltip>
492 <TooltipTrigger
493 render={
494 <Button
495 type="button"
496 size="icon-xs"
497 variant="ghost"
498 aria-label={
499 expandAll || allDirectoriesExpanded
500 ? "Collapse all folders"
501 : "Expand all folders"
502 }
503 onClick={toggleAllDirectories}
504 />
505 }
506 >
507 <MorphIcon
508 className="size-3.5"
509 icon={allDirectoriesExpanded ? ChevronsDownUp : ChevronsUpDown}
510 />
511 </TooltipTrigger>
512 <TooltipPopup>
513 {expandAll || allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
514 </TooltipPopup>
515 </Tooltip>
516 ) : null}
517 </div>
518 {error || pathSearch.error ? (
519 <button
520 type="button"
521 onClick={handleRefresh}
522 className="p-4 text-left text-xs leading-relaxed text-destructive"
523 >
524 {error ?? pathSearch.error} Click to retry.
525 </button>
526 ) : null}
527 {query.trim() && pathSearch.truncated && !pathSearch.isPending ? (
528 <div className="px-3 py-1 text-xs text-muted-foreground">
529 More matches available. Refine your search.
530 </div>
531 ) : null}
532 {(!ready || pathSearch.isPending) && (
533 <div
534 role="status"
535 className={
536 entries.length > 0 && !hasNoSearchMatches
537 ? "sr-only"
538 : "px-3 py-1 text-xs text-muted-foreground"
539 }
540 >
541 Loading files…
542 </div>
543 )}
544 {hasNoSearchMatches ? (
545 ready && !isPending && !pathSearch.isPending && !error && !pathSearch.error ? (
546 <div role="status" className="px-3 py-4 text-xs text-muted-foreground">
547 No matching files.
548 </div>
549 ) : null
550 ) : (
551 <FileTree
552 model={model}
553 aria-label={`${projectName} files`}
554 className="min-h-0 flex-1 overflow-hidden"
555 style={pierreTreeStyle(resolvedTheme)}
556 />
557 )}
558 </div>
559 );