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