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, useFileTreeSearch } from "@pierre/trees/react";
7import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
8import { RotateCw } from "lucide-react";
9import { useEffect, useMemo, useRef } from "react";
10
11import { Button } from "~/components/ui/button";
12import { InputGroup, InputGroupInput } from "~/components/ui/input-group";
13import { toastManager } from "~/components/ui/toast";
14import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
15import { useComposerHandleContext } from "~/composerHandleContext";
16import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
17import { useTheme } from "~/hooks/useTheme";
18import { cn } from "~/lib/utils";
19import { readLocalApi } from "~/localApi";
20import { T3_PIERRE_ICONS } from "~/pierre-icons";
21
22import { createFileTreeDragMentionController } from "./fileTreeDragMention";
23import { useProjectEntriesQuery } from "./projectFilesQueryState";
24
25interface FileBrowserPanelProps {
26 environmentId: EnvironmentId;
27 cwd: string;
28 projectName: string;
29 /** File currently open in the preview pane; revealed and selected in the tree. */
30 selectedPath: string | null;
31 /** Bumped when the same path should be revealed again (e.g. re-opened from search). */
32 selectedPathRevealId: number;
33 onOpenFile: (relativePath: string) => void;
34}
35
36const TREE_UNSAFE_CSS = `
37 :host {
38 --trees-bg-override: transparent;
39 --trees-selected-bg-override: color-mix(in srgb, currentColor 12%, transparent);
40 --trees-hover-bg-override: color-mix(in srgb, currentColor 7%, transparent);
41 --trees-border-color-override: color-mix(in srgb, currentColor 14%, transparent);
42 --trees-font-family-override: var(--font-sans);
43 --trees-font-size-override: 12px;
44 }
45 button[data-type='item'] { border-radius: 5px; }
46`;
47
48function treePath(entry: ProjectEntry): string {
49 return entry.kind === "directory" ? `${entry.path}/` : entry.path;
50}
51
52function RefreshFilesButton(props: { isPending: boolean; onRefresh: () => void }) {
53 return (
54 <Tooltip>
55 <TooltipTrigger
56 render={
57 <Button
58 type="button"
59 variant="ghost"
60 size="icon-xs"
61 aria-label="Refresh workspace files"
62 onClick={props.onRefresh}
63 />
64 }
65 >
66 <RotateCw className={cn(props.isPending && "animate-spin")} />
67 </TooltipTrigger>
68 <TooltipPopup>{props.isPending ? "Refreshing…" : "Refresh files"}</TooltipPopup>
69 </Tooltip>
70 );
71}
72
73function FileSearchField(props: {
74 ariaLabel: string;
75 name: string;
76 onClose: () => void;
77 onValueChange: (value: string) => void;
78 value: string;
79}) {
80 return (
81 <InputGroup variant="ghost" className="h-7 min-w-0 flex-1">
82 <InputGroupInput
83 type="search"
84 name={props.name}
85 size="sm"
86 value={props.value}
87 aria-label={props.ariaLabel}
88 placeholder="Search files"
89 spellCheck={false}
90 onChange={(event) => props.onValueChange(event.target.value)}
91 onKeyDown={(event) => {
92 if (event.key !== "Escape") return;
93 props.onClose();
94 event.currentTarget.blur();
95 }}
96 />
97 </InputGroup>
98 );
99}
100
101export default function FileBrowserPanel({
102 environmentId,
103 cwd,
104 projectName,
105 selectedPath,
106 selectedPathRevealId,
107 onOpenFile,
108}: FileBrowserPanelProps) {
109 const { resolvedTheme } = useTheme();
110 const composerRef = useComposerHandleContext();
111 const entriesQuery = useProjectEntriesQuery(environmentId, cwd);
112 const entries = entriesQuery.data?.entries ?? [];
113 const entryKinds = useMemo(
114 () => new Map(entries.map((entry) => [entry.path, entry.kind] as const)),
115 [entries],
116 );
117 const entryKindsRef = useRef<ReadonlyMap<string, ProjectEntry["kind"]>>(entryKinds);
118 const treePaths = useMemo(() => entries.map(treePath), [entries]);
119 const previousTreePathsRef = useRef<readonly string[]>([]);
120 const syncingSelectionRef = useRef(false);
121 const treeSelectionPathRef = useRef<string | null>(null);
122 const handledRevealRef = useRef<{ path: string; revealId: number } | null>(null);
123
124 // The tree renders rows in shadow DOM and its anchor rect is unreliable, so
125 // capture the right-click position ourselves; contextmenu is a composed
126 // event, so a capture-phase listener sees it with viewport coordinates.
127 const contextMenuPointerRef = useRef<{ x: number; y: number; at: number } | null>(null);
128 useEffect(() => {
129 const capturePointer = (event: MouseEvent) => {
130 contextMenuPointerRef.current = { x: event.clientX, y: event.clientY, at: event.timeStamp };
131 };
132 document.addEventListener("contextmenu", capturePointer, true);
133 return () => document.removeEventListener("contextmenu", capturePointer, true);
134 }, []);
135
136 const showEntryContextMenu = async (
137 item: TreeContextMenuItem,
138 context: TreeContextMenuOpenContext,
139 ) => {
140 const api = readLocalApi();
141 if (!api) {
142 context.close();
143 return;
144 }
145 const relativePath = item.path.replace(/\/$/, "");
146 const mention = serializeComposerFileLink(relativePath);
147 const pointer = contextMenuPointerRef.current;
148 const pointerIsFresh = pointer !== null && performance.now() - pointer.at < 1000;
149 const anchorRect = context.anchorElement.getBoundingClientRect();
150 const position = pointerIsFresh
151 ? { x: pointer.x, y: pointer.y }
152 : { x: anchorRect.left, y: anchorRect.bottom };
153 try {
154 const clicked = await api.contextMenu.show(
155 [
156 { id: "copy-mention", label: "Copy mention" },
157 { id: "add-to-chat", label: "Add to chat" },
158 ],
159 position,
160 );
161 if (clicked === "copy-mention") {
162 try {
163 await writeTextToClipboard(mention);
164 toastManager.add({ type: "success", title: "Mention copied", description: relativePath });
165 } catch (error) {
166 toastManager.add({
167 type: "error",
168 title: "Failed to copy mention",
169 description: error instanceof Error ? error.message : "An error occurred.",
170 });
171 }
172 return;
173 }
174 if (clicked === "add-to-chat") {
175 const composer = composerRef?.current;
176 if (!composer) {
177 toastManager.add({
178 type: "error",
179 title: "Unable to add to chat",
180 description: "Open a chat for this project and try again.",
181 });
182 return;
183 }
184 const inserted = composer.insertTextAtEnd(`${mention} `, { ensureLeadingBoundary: true });
185 if (!inserted) {
186 toastManager.add({
187 type: "error",
188 title: "Unable to add to chat",
189 description: "The chat isn't ready to accept input right now.",
190 });
191 }
192 }
193 } finally {
194 context.close();
195 }
196 };
197 const showEntryContextMenuRef = useRef(showEntryContextMenu);
198 useEffect(() => {
199 showEntryContextMenuRef.current = showEntryContextMenu;
200 });
201
202 const treeModelRef = useRef<ReturnType<typeof useFileTree>["model"] | null>(null);
203 const dragMention = useMemo(
204 () =>
205 createFileTreeDragMentionController({
206 deselect: (path) => treeModelRef.current?.getItem(path)?.deselect(),
207 }),
208 [],
209 );
210 const { model } = useFileTree({
211 composition: {
212 contextMenu: {
213 triggerMode: "right-click",
214 onOpen: (item, context) => {
215 void showEntryContextMenuRef.current(item, context);
216 },
217 },
218 },
219 // Rows only need to be draggable so entries can be dropped into the chat
220 // composer; rearranging files inside the tree stays off.
221 dragAndDrop: { canDrop: () => false },
222 density: "compact",
223 fileTreeSearchMode: "hide-non-matches",
224 flattenEmptyDirectories: true,
225 initialExpansion: 1,
226 icons: T3_PIERRE_ICONS,
227 onSelectionChange: (selectedPaths) => {
228 // The drag controller's selection cache must track every change,
229 // including reveal-driven ones, or drags act on a stale selection.
230 dragMention.handleSelectionChange(selectedPaths);
231 // Selection changes driven by the reveal sync below are echoes of an
232 // already-open file, not a request to open it again.
233 if (syncingSelectionRef.current) return;
234 // Starting a drag selects the dragged row; that selection is a side
235 // effect of the gesture, not a request to open the file.
236 if (dragMention.isDragInProgress()) {
237 return;
238 }
239 const selectedPath = selectedPaths.at(-1)?.replace(/\/$/, "");
240 if (selectedPath && entryKindsRef.current.get(selectedPath) === "file") {
241 treeSelectionPathRef.current = selectedPath;
242 onOpenFile(selectedPath);
243 }
244 },
245 paths: [],
246 search: false,
247 unsafeCSS: TREE_UNSAFE_CSS,
248 });
249 const search = useFileTreeSearch(model);
250 const handleSearchValueChange = (value: string) => {
251 if (value.trim().length === 0) {
252 search.close();
253 return;
254 }
255 search.setValue(value);
256 };
257
258 useEffect(() => {
259 if (previousTreePathsRef.current === treePaths) return;
260 entryKindsRef.current = entryKinds;
261 previousTreePathsRef.current = treePaths;
262 model.resetPaths(treePaths);
263 }, [entryKinds, model, treePaths]);
264
265 useEffect(() => {
266 if (!selectedPath) {
267 handledRevealRef.current = null;
268 return;
269 }
270 const revealRequest = { path: selectedPath, revealId: selectedPathRevealId };
271 const handledReveal = handledRevealRef.current;
272 // Entry refreshes rebuild treePaths while the same preview stays open.
273 // Replaying a handled reveal would close an active tree search and steal focus.
274 if (
275 handledReveal?.path === revealRequest.path &&
276 handledReveal.revealId === revealRequest.revealId
277 ) {
278 return;
279 }
280 if (entryKinds.get(selectedPath) !== "file") return;
281 const selectedItem = model.getItem(selectedPath);
282 if (!selectedItem) return;
283
284 // A selection that originated inside the tree (clicking a row, possibly
285 // in an active tree search) is already visible; re-revealing it would
286 // close the search and clobber the user's context. Only sync external
287 // opens (file picker, content search, chat links).
288 const selectedInTree = model
289 .getSelectedPaths()
290 .some((path) => path.replace(/\/$/, "") === selectedPath);
291 if (selectedInTree && treeSelectionPathRef.current === selectedPath) {
292 treeSelectionPathRef.current = null;
293 handledRevealRef.current = revealRequest;
294 return;
295 }
296 treeSelectionPathRef.current = null;
297 handledRevealRef.current = revealRequest;
298
299 syncingSelectionRef.current = true;
300 model.closeSearch();
301 for (const path of model.getSelectedPaths()) {
302 model.getItem(path)?.deselect();
303 }
304
305 // Directory rows are registered with a trailing slash (see treePath), so
306 // ancestor lookups must use the same form to expand them.
307 const segments = selectedPath.split("/");
308 let ancestorPath = "";
309 for (const segment of segments.slice(0, -1)) {
310 ancestorPath = ancestorPath ? `${ancestorPath}/${segment}` : segment;
311 const item = model.getItem(`${ancestorPath}/`) ?? model.getItem(ancestorPath);
312 if (item && "expand" in item) item.expand();
313 }
314
315 selectedItem.select();
316 model.scrollToPath(selectedPath, { focus: true, offset: "center" });
317 queueMicrotask(() => {
318 syncingSelectionRef.current = false;
319 });
320 }, [entryKinds, model, selectedPath, selectedPathRevealId, treePaths]);
321
322 // Tag tree drags with the composer mention payload. The row is read from
323 // the composed event path (the tree's shadow root is open), so this does
324 // not depend on running after the tree's own dragstart handler; the drag
325 // data store is writable for every dragstart listener in the dispatch.
326 // The capture phase runs before the tree's own dragstart handler selects
327 // the dragged row, so the drag flag is up before that selection emits.
328 const panelRef = useRef<HTMLDivElement | null>(null);
329 useEffect(() => {
330 treeModelRef.current = model;
331 }, [model]);
332 useEffect(() => {
333 const panel = panelRef.current;
334 if (panel === null) {
335 return;
336 }
337 const handleDragStart = (event: DragEvent) => dragMention.handleDragStart(event);
338 const handleDragEnd = () => dragMention.handleDragEnd();
339 panel.addEventListener("dragstart", handleDragStart, true);
340 panel.addEventListener("dragend", handleDragEnd);
341 return () => {
342 panel.removeEventListener("dragstart", handleDragStart, true);
343 panel.removeEventListener("dragend", handleDragEnd);
344 };
345 }, [dragMention]);
346
347 return (
348 <div
349 ref={panelRef}
350 className="flex min-h-0 flex-1 flex-col bg-background"
351 data-file-browser-panel={`${environmentId}:${cwd}`}
352 >
353 <div
354 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-3 in-data-[preview-panel-mode=inline]:h-7 in-data-[preview-panel-mode=inline]:min-h-7 in-data-[preview-panel-mode=inline]:border-b-transparent"
355 data-surface-subheader
356 >
357 <RefreshFilesButton isPending={entriesQuery.isPending} onRefresh={entriesQuery.refresh} />
358 <FileSearchField
359 name="project-files-search"
360 ariaLabel={`Search ${projectName} files`}
361 value={search.value}
362 onValueChange={handleSearchValueChange}
363 onClose={search.close}
364 />
365 </div>
366 {entriesQuery.error && entriesQuery.data === null ? (
367 <div className="p-4 text-xs leading-relaxed text-destructive">{entriesQuery.error}</div>
368 ) : (
369 <FileTree
370 model={model}
371 aria-label={`${projectName} files`}
372 className="min-h-0 flex-1 overflow-hidden"
373 style={{
374 colorScheme: resolvedTheme,
375 ["--trees-fg-override" as string]: "var(--foreground)",
376 }}
377 />
378 )}
379 </div>
380 );
381}