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 onOpenFile: (relativePath: string) => void;
30}
31
32const TREE_UNSAFE_CSS = `
33 :host {
34 --trees-bg-override: transparent;
35 --trees-selected-bg-override: color-mix(in srgb, currentColor 12%, transparent);
36 --trees-hover-bg-override: color-mix(in srgb, currentColor 7%, transparent);
37 --trees-border-color-override: color-mix(in srgb, currentColor 14%, transparent);
38 --trees-font-family-override: var(--font-sans);
39 --trees-font-size-override: 12px;
40 }
41 button[data-type='item'] { border-radius: 5px; }
42`;
43
44function treePath(entry: ProjectEntry): string {
45 return entry.kind === "directory" ? `${entry.path}/` : entry.path;
46}
47
48function RefreshFilesButton(props: { isPending: boolean; onRefresh: () => void }) {
49 return (
50 <Tooltip>
51 <TooltipTrigger
52 render={
53 <Button
54 type="button"
55 variant="ghost"
56 size="icon-xs"
57 aria-label="Refresh workspace files"
58 onClick={props.onRefresh}
59 />
60 }
61 >
62 <RotateCw className={cn(props.isPending && "animate-spin")} />
63 </TooltipTrigger>
64 <TooltipPopup>{props.isPending ? "Refreshing…" : "Refresh files"}</TooltipPopup>
65 </Tooltip>
66 );
67}
68
69function FileSearchField(props: {
70 ariaLabel: string;
71 name: string;
72 onClose: () => void;
73 onValueChange: (value: string) => void;
74 value: string;
75}) {
76 return (
77 <InputGroup variant="ghost" className="h-7 min-w-0 flex-1 rounded-md">
78 <InputGroupInput
79 type="search"
80 name={props.name}
81 size="sm"
82 value={props.value}
83 aria-label={props.ariaLabel}
84 placeholder="Search files"
85 spellCheck={false}
86 onChange={(event) => props.onValueChange(event.target.value)}
87 onKeyDown={(event) => {
88 if (event.key !== "Escape") return;
89 props.onClose();
90 event.currentTarget.blur();
91 }}
92 />
93 </InputGroup>
94 );
95}
96
97export default function FileBrowserPanel({
98 environmentId,
99 cwd,
100 projectName,
101 onOpenFile,
102}: FileBrowserPanelProps) {
103 const { resolvedTheme } = useTheme();
104 const composerRef = useComposerHandleContext();
105 const entriesQuery = useProjectEntriesQuery(environmentId, cwd);
106 const entries = entriesQuery.data?.entries ?? [];
107 const entryKinds = useMemo(
108 () => new Map(entries.map((entry) => [entry.path, entry.kind] as const)),
109 [entries],
110 );
111 const entryKindsRef = useRef<ReadonlyMap<string, ProjectEntry["kind"]>>(entryKinds);
112 const treePaths = useMemo(() => entries.map(treePath), [entries]);
113 const previousTreePathsRef = useRef<readonly string[]>([]);
114
115 // The tree renders rows in shadow DOM and its anchor rect is unreliable, so
116 // capture the right-click position ourselves; contextmenu is a composed
117 // event, so a capture-phase listener sees it with viewport coordinates.
118 const contextMenuPointerRef = useRef<{ x: number; y: number; at: number } | null>(null);
119 useEffect(() => {
120 const capturePointer = (event: MouseEvent) => {
121 contextMenuPointerRef.current = { x: event.clientX, y: event.clientY, at: event.timeStamp };
122 };
123 document.addEventListener("contextmenu", capturePointer, true);
124 return () => document.removeEventListener("contextmenu", capturePointer, true);
125 }, []);
126
127 const showEntryContextMenu = async (
128 item: TreeContextMenuItem,
129 context: TreeContextMenuOpenContext,
130 ) => {
131 const api = readLocalApi();
132 if (!api) {
133 context.close();
134 return;
135 }
136 const relativePath = item.path.replace(/\/$/, "");
137 const mention = serializeComposerFileLink(relativePath);
138 const pointer = contextMenuPointerRef.current;
139 const pointerIsFresh = pointer !== null && performance.now() - pointer.at < 1000;
140 const anchorRect = context.anchorElement.getBoundingClientRect();
141 const position = pointerIsFresh
142 ? { x: pointer.x, y: pointer.y }
143 : { x: anchorRect.left, y: anchorRect.bottom };
144 try {
145 const clicked = await api.contextMenu.show(
146 [
147 { id: "copy-mention", label: "Copy mention" },
148 { id: "add-to-chat", label: "Add to chat" },
149 ],
150 position,
151 );
152 if (clicked === "copy-mention") {
153 try {
154 await writeTextToClipboard(mention);
155 toastManager.add({ type: "success", title: "Mention copied", description: relativePath });
156 } catch (error) {
157 toastManager.add({
158 type: "error",
159 title: "Failed to copy mention",
160 description: error instanceof Error ? error.message : "An error occurred.",
161 });
162 }
163 return;
164 }
165 if (clicked === "add-to-chat") {
166 const composer = composerRef?.current;
167 if (!composer) {
168 toastManager.add({
169 type: "error",
170 title: "Unable to add to chat",
171 description: "Open a chat for this project and try again.",
172 });
173 return;
174 }
175 const inserted = composer.insertTextAtEnd(`${mention} `, { ensureLeadingBoundary: true });
176 if (!inserted) {
177 toastManager.add({
178 type: "error",
179 title: "Unable to add to chat",
180 description: "The chat isn't ready to accept input right now.",
181 });
182 }
183 }
184 } finally {
185 context.close();
186 }
187 };
188 const showEntryContextMenuRef = useRef(showEntryContextMenu);
189 useEffect(() => {
190 showEntryContextMenuRef.current = showEntryContextMenu;
191 });
192
193 const treeModelRef = useRef<ReturnType<typeof useFileTree>["model"] | null>(null);
194 const dragMention = useMemo(
195 () =>
196 createFileTreeDragMentionController({
197 deselect: (path) => treeModelRef.current?.getItem(path)?.deselect(),
198 }),
199 [],
200 );
201 const { model } = useFileTree({
202 composition: {
203 contextMenu: {
204 triggerMode: "right-click",
205 onOpen: (item, context) => {
206 void showEntryContextMenuRef.current(item, context);
207 },
208 },
209 },
210 // Rows only need to be draggable so entries can be dropped into the chat
211 // composer; rearranging files inside the tree stays off.
212 dragAndDrop: { canDrop: () => false },
213 density: "compact",
214 fileTreeSearchMode: "hide-non-matches",
215 flattenEmptyDirectories: true,
216 initialExpansion: 1,
217 icons: T3_PIERRE_ICONS,
218 onSelectionChange: (selectedPaths) => {
219 dragMention.handleSelectionChange(selectedPaths);
220 // Starting a drag selects the dragged row; that selection is a side
221 // effect of the gesture, not a request to open the file.
222 if (dragMention.isDragInProgress()) {
223 return;
224 }
225 const selectedPath = selectedPaths.at(-1)?.replace(/\/$/, "");
226 if (selectedPath && entryKindsRef.current.get(selectedPath) === "file") {
227 onOpenFile(selectedPath);
228 }
229 },
230 paths: [],
231 search: false,
232 unsafeCSS: TREE_UNSAFE_CSS,
233 });
234 const search = useFileTreeSearch(model);
235 const handleSearchValueChange = (value: string) => {
236 if (value.trim().length === 0) {
237 search.close();
238 return;
239 }
240 search.setValue(value);
241 };
242
243 useEffect(() => {
244 if (previousTreePathsRef.current === treePaths) return;
245 entryKindsRef.current = entryKinds;
246 previousTreePathsRef.current = treePaths;
247 model.resetPaths(treePaths);
248 }, [entryKinds, model, treePaths]);
249
250 // Tag tree drags with the composer mention payload. The row is read from
251 // the composed event path (the tree's shadow root is open), so this does
252 // not depend on running after the tree's own dragstart handler; the drag
253 // data store is writable for every dragstart listener in the dispatch.
254 // The capture phase runs before the tree's own dragstart handler selects
255 // the dragged row, so the drag flag is up before that selection emits.
256 const panelRef = useRef<HTMLDivElement | null>(null);
257 useEffect(() => {
258 treeModelRef.current = model;
259 }, [model]);
260 useEffect(() => {
261 const panel = panelRef.current;
262 if (panel === null) {
263 return;
264 }
265 const handleDragStart = (event: DragEvent) => dragMention.handleDragStart(event);
266 const handleDragEnd = () => dragMention.handleDragEnd();
267 panel.addEventListener("dragstart", handleDragStart, true);
268 panel.addEventListener("dragend", handleDragEnd);
269 return () => {
270 panel.removeEventListener("dragstart", handleDragStart, true);
271 panel.removeEventListener("dragend", handleDragEnd);
272 };
273 }, [dragMention]);
274
275 return (
276 <div
277 ref={panelRef}
278 className="flex min-h-0 flex-1 flex-col bg-background"
279 data-file-browser-panel={`${environmentId}:${cwd}`}
280 >
281 <div className="surface-subheader gap-1 px-2" data-surface-subheader>
282 <RefreshFilesButton isPending={entriesQuery.isPending} onRefresh={entriesQuery.refresh} />
283 <FileSearchField
284 name="project-files-search"
285 ariaLabel={`Search ${projectName} files`}
286 value={search.value}
287 onValueChange={handleSearchValueChange}
288 onClose={search.close}
289 />
290 </div>
291 {entriesQuery.error && entriesQuery.data === null ? (
292 <div className="p-4 text-xs leading-relaxed text-destructive">{entriesQuery.error}</div>
293 ) : (
294 <FileTree
295 model={model}
296 aria-label={`${projectName} files`}
297 className="min-h-0 flex-1 overflow-hidden"
298 style={{
299 colorScheme: resolvedTheme,
300 ["--trees-fg-override" as string]: "var(--foreground)",
301 }}
302 />
303 )}
304 </div>
305 );
306}