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