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