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