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

FileBrowserPanel.tsx

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