Open History to see the last commit
1import type {
2 ContextMenuItem as TreeContextMenuItem,
3 ContextMenuOpenContext as TreeContextMenuOpenContext,
4} from "@pierre/trees";
5import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
6import { FileTree, useFileTree } from "@pierre/trees/react";
7import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
8import { RefreshCw, Search } from "lucide-react";
9import { useEffect, useMemo, useRef } from "react";
10
11import { toastManager } from "~/components/ui/toast";
12import { useComposerHandleContext } from "~/composerHandleContext";
13import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
14import { useTheme } from "~/hooks/useTheme";
15import { cn } from "~/lib/utils";
16import { readLocalApi } from "~/localApi";
17import { T3_PIERRE_ICONS } from "~/pierre-icons";
18
19import { createFileTreeDragMentionController } from "./fileTreeDragMention";
20import { useProjectEntriesQuery } from "./projectFilesQueryState";
21
22interface FileBrowserPanelProps {
23 environmentId: EnvironmentId;
24 cwd: string;
25 projectName: string;
26 onOpenFile: (relativePath: string) => void;
27}
28
29const TREE_UNSAFE_CSS = `
30 :host {
31 --trees-bg-override: transparent;
32 --trees-selected-bg-override: color-mix(in srgb, currentColor 12%, transparent);
33 --trees-hover-bg-override: color-mix(in srgb, currentColor 7%, transparent);
34 --trees-border-color-override: color-mix(in srgb, currentColor 14%, transparent);
35 --trees-font-family-override: var(--font-sans);
36 --trees-font-size-override: 12px;
37 }
38 button[data-type='item'] { border-radius: 5px; }
39`;
40
41function treePath(entry: ProjectEntry): string {
42 return entry.kind === "directory" ? `${entry.path}/` : entry.path;
43}
44
45export default function FileBrowserPanel({
46 environmentId,
47 cwd,
48 projectName,
49 onOpenFile,
50}: FileBrowserPanelProps) {
51 const { resolvedTheme } = useTheme();
52 const composerRef = useComposerHandleContext();
53 const entriesQuery = useProjectEntriesQuery(environmentId, cwd);
54 const entries = entriesQuery.data?.entries ?? [];
55 const entryKinds = useMemo(
56 () => new Map(entries.map((entry) => [entry.path, entry.kind] as const)),
57 [entries],
58 );
59 const entryKindsRef = useRef<ReadonlyMap<string, ProjectEntry["kind"]>>(entryKinds);
60 const treePaths = useMemo(() => entries.map(treePath), [entries]);
61 const previousTreePathsRef = useRef<readonly string[]>([]);
62
63 // The tree renders rows in shadow DOM and its anchor rect is unreliable, so
64 // capture the right-click position ourselves; contextmenu is a composed
65 // event, so a capture-phase listener sees it with viewport coordinates.
66 const contextMenuPointerRef = useRef<{ x: number; y: number; at: number } | null>(null);
67 useEffect(() => {
68 const capturePointer = (event: MouseEvent) => {
69 contextMenuPointerRef.current = { x: event.clientX, y: event.clientY, at: event.timeStamp };
70 };
71 document.addEventListener("contextmenu", capturePointer, true);
72 return () => document.removeEventListener("contextmenu", capturePointer, true);
73 }, []);
74
75 const showEntryContextMenu = async (
76 item: TreeContextMenuItem,
77 context: TreeContextMenuOpenContext,
78 ) => {
79 const api = readLocalApi();
80 if (!api) {
81 context.close();
82 return;
83 }
84 const relativePath = item.path.replace(/\/$/, "");
85 const mention = serializeComposerFileLink(relativePath);
86 const pointer = contextMenuPointerRef.current;
87 const pointerIsFresh = pointer !== null && performance.now() - pointer.at < 1000;
88 const anchorRect = context.anchorElement.getBoundingClientRect();
89 const position = pointerIsFresh
90 ? { x: pointer.x, y: pointer.y }
91 : { x: anchorRect.left, y: anchorRect.bottom };
92 try {
93 const clicked = await api.contextMenu.show(
94 [
95 { id: "copy-mention", label: "Copy mention" },
96 { id: "add-to-chat", label: "Add to chat" },
97 ],
98 position,
99 );
100 if (clicked === "copy-mention") {
101 try {
102 await writeTextToClipboard(mention);
103 toastManager.add({ type: "success", title: "Mention copied", description: relativePath });
104 } catch (error) {
105 toastManager.add({
106 type: "error",
107 title: "Failed to copy mention",
108 description: error instanceof Error ? error.message : "An error occurred.",
109 });
110 }
111 return;
112 }
113 if (clicked === "add-to-chat") {
114 const composer = composerRef?.current;
115 if (!composer) {
116 toastManager.add({
117 type: "error",
118 title: "Unable to add to chat",
119 description: "Open a chat for this project and try again.",
120 });
121 return;
122 }
123 const inserted = composer.insertTextAtEnd(`${mention} `, { ensureLeadingBoundary: true });
124 if (!inserted) {
125 toastManager.add({
126 type: "error",
127 title: "Unable to add to chat",
128 description: "The chat isn't ready to accept input right now.",
129 });
130 }
131 }
132 } finally {
133 context.close();
134 }
135 };
136 const showEntryContextMenuRef = useRef(showEntryContextMenu);
137 useEffect(() => {
138 showEntryContextMenuRef.current = showEntryContextMenu;
139 });
140
141 const treeModelRef = useRef<ReturnType<typeof useFileTree>["model"] | null>(null);
142 const dragMention = useMemo(
143 () =>
144 createFileTreeDragMentionController({
145 deselect: (path) => treeModelRef.current?.getItem(path)?.deselect(),
146 }),
147 [],
148 );
149 const { model } = useFileTree({
150 composition: {
151 contextMenu: {
152 triggerMode: "right-click",
153 onOpen: (item, context) => {
154 void showEntryContextMenuRef.current(item, context);
155 },
156 },
157 },
158 // Rows only need to be draggable so entries can be dropped into the chat
159 // composer; rearranging files inside the tree stays off.
160 dragAndDrop: { canDrop: () => false },
161 density: "compact",
162 fileTreeSearchMode: "hide-non-matches",
163 flattenEmptyDirectories: true,
164 initialExpansion: 1,
165 icons: T3_PIERRE_ICONS,
166 onSelectionChange: (selectedPaths) => {
167 dragMention.handleSelectionChange(selectedPaths);
168 // Starting a drag selects the dragged row; that selection is a side
169 // effect of the gesture, not a request to open the file.
170 if (dragMention.isDragInProgress()) {
171 return;
172 }
173 const selectedPath = selectedPaths.at(-1)?.replace(/\/$/, "");
174 if (selectedPath && entryKindsRef.current.get(selectedPath) === "file") {
175 onOpenFile(selectedPath);
176 }
177 },
178 paths: [],
179 search: true,
180 unsafeCSS: TREE_UNSAFE_CSS,
181 });
182
183 useEffect(() => {
184 if (previousTreePathsRef.current === treePaths) return;
185 entryKindsRef.current = entryKinds;
186 previousTreePathsRef.current = treePaths;
187 model.resetPaths(treePaths);
188 }, [entryKinds, model, treePaths]);
189
190 const fileCount = useMemo(
191 () => entries.reduce((count, entry) => count + (entry.kind === "file" ? 1 : 0), 0),
192 [entries],
193 );
194
195 // Tag tree drags with the composer mention payload. The row is read from
196 // the composed event path (the tree's shadow root is open), so this does
197 // not depend on running after the tree's own dragstart handler; the drag
198 // data store is writable for every dragstart listener in the dispatch.
199 // The capture phase runs before the tree's own dragstart handler selects
200 // the dragged row, so the drag flag is up before that selection emits.
201 const panelRef = useRef<HTMLDivElement | null>(null);
202 useEffect(() => {
203 treeModelRef.current = model;
204 }, [model]);
205 useEffect(() => {
206 const panel = panelRef.current;
207 if (panel === null) {
208 return;
209 }
210 const handleDragStart = (event: DragEvent) => dragMention.handleDragStart(event);
211 const handleDragEnd = () => dragMention.handleDragEnd();
212 panel.addEventListener("dragstart", handleDragStart, true);
213 panel.addEventListener("dragend", handleDragEnd);
214 return () => {
215 panel.removeEventListener("dragstart", handleDragStart, true);
216 panel.removeEventListener("dragend", handleDragEnd);
217 };
218 }, [dragMention]);
219
220 return (
221 <div
222 ref={panelRef}
223 className="flex min-h-0 flex-1 flex-col bg-background"
224 data-file-browser-panel={`${environmentId}:${cwd}`}
225 >
226 <div className="flex h-9 shrink-0 items-center gap-2 border-b border-border/60 px-3">
227 <div className="min-w-0 flex-1">
228 <div className="truncate text-xs font-medium text-foreground">{projectName}</div>
229 <div className="truncate text-[10px] leading-none text-muted-foreground">
230 {entriesQuery.isPending && entriesQuery.data === null
231 ? "Indexing…"
232 : `${fileCount.toLocaleString()} files`}
233 {entriesQuery.data?.truncated ? " · partial" : ""}
234 </div>
235 </div>
236 <button
237 type="button"
238 className="rounded-md p-1.5 text-muted-foreground hover:bg-accent hover:text-foreground"
239 aria-label="Search workspace files"
240 onClick={() => model.openSearch()}
241 >
242 <Search className="size-3.5" />
243 </button>
244 <button
245 type="button"
246 className="rounded-md p-1.5 text-muted-foreground hover:bg-accent hover:text-foreground"
247 aria-label="Refresh workspace files"
248 onClick={entriesQuery.refresh}
249 >
250 <RefreshCw className={cn("size-3.5", entriesQuery.isPending && "animate-spin")} />
251 </button>
252 </div>
253 {entriesQuery.error && entriesQuery.data === null ? (
254 <div className="p-4 text-xs leading-relaxed text-destructive">{entriesQuery.error}</div>
255 ) : (
256 <FileTree
257 model={model}
258 aria-label={`${projectName} files`}
259 className="min-h-0 flex-1 overflow-hidden"
260 style={{
261 colorScheme: resolvedTheme,
262 ["--trees-fg-override" as string]: "var(--foreground)",
263 }}
264 />
265 )}
266 </div>
267 );
268}