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