Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

FileBrowserPanel.tsx

387 lines14.0 KB

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