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

FileBrowserPanel.tsx

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