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 /** Entry currently open in the surface; revealed and selected in the tree. A directory is expanded. */
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 const selectedKind = entryKinds.get(selectedPath);
380 // An unloaded entry has no row to reveal yet; folders do, and chat links can
381 // point at them.
382 if (selectedKind === undefined) {
383 handledRevealRef.current = null;
384 return;
385 }
386 const revealRequest = { path: selectedPath, revealId: selectedPathRevealId };
387 const handledReveal = handledRevealRef.current;
388 // Entry refreshes rebuild treePaths while the same preview stays open.
389 // Replaying a handled reveal would close an active tree search and steal focus.
390 if (
391 handledReveal?.path === revealRequest.path &&
392 handledReveal.revealId === revealRequest.revealId
393 ) {
394 return;
395 }
396 // Directory rows are registered with a trailing slash (see treePath).
397 const selectedTreePath = selectedKind === "directory" ? `${selectedPath}/` : selectedPath;
398 const selectedItem = model.getItem(selectedTreePath);
399 if (!selectedItem) return;
400
401 // A selection that originated inside the tree (clicking a row, possibly
402 // in an active tree search) is already visible; re-revealing it would
403 // close the search and clobber the user's context. Only sync external
404 // opens (file picker, content search, chat links).
405 const selectedInTree = model
406 .getSelectedPaths()
407 .some((path) => path.replace(/\/$/, "") === selectedPath);
408 if (selectedInTree && treeSelectionPathRef.current === selectedPath) {
409 treeSelectionPathRef.current = null;
410 handledRevealRef.current = revealRequest;
411 return;
412 }
413 treeSelectionPathRef.current = null;
414 handledRevealRef.current = revealRequest;
415
416 syncingSelectionRef.current = true;
417 setQuery("");
418 model.closeSearch();
419 for (const path of model.getSelectedPaths()) {
420 model.getItem(path)?.deselect();
421 }
422
423 // Directory rows are registered with a trailing slash (see treePath), so
424 // ancestor lookups must use the same form to expand them.
425 const segments = selectedPath.split("/");
426 let ancestorPath = "";
427 for (const segment of segments.slice(0, -1)) {
428 ancestorPath = ancestorPath ? `${ancestorPath}/${segment}` : segment;
429 const item = model.getItem(`${ancestorPath}/`) ?? model.getItem(ancestorPath);
430 if (item && "expand" in item) item.expand();
431 }
432
433 if ("expand" in selectedItem) selectedItem.expand();
434 selectedItem.select();
435 model.scrollToPath(selectedTreePath, {
436 focus: true,
437 offset: "center",
438 });
439 queueMicrotask(() => {
440 syncingSelectionRef.current = false;
441 });
442 }, [entryKinds, model, selectedPath, selectedPathRevealId]);
443
444 // Tag tree drags with the composer mention payload. The row is read from
445 // the composed event path (the tree's shadow root is open), so this does
446 // not depend on running after the tree's own dragstart handler; the drag
447 // data store is writable for every dragstart listener in the dispatch.
448 // The capture phase runs before the tree's own dragstart handler selects
449 // the dragged row, so the drag flag is up before that selection emits.
450 const panelRef = useRef<HTMLDivElement | null>(null);
451 useEffect(() => {
452 treeModelRef.current = model;
453 }, [model]);
454 useEffect(() => {
455 const panel = panelRef.current;
456 if (panel === null) {
457 return;
458 }
459 const handleDragStart = (event: DragEvent) => dragMention.handleDragStart(event);
460 const handleDragEnd = () => dragMention.handleDragEnd();
461 panel.addEventListener("dragstart", handleDragStart, true);
462 panel.addEventListener("dragend", handleDragEnd);
463 return () => {
464 panel.removeEventListener("dragstart", handleDragStart, true);
465 panel.removeEventListener("dragend", handleDragEnd);
466 };
467 }, [dragMention]);
468
469 return (
470 <div
471 ref={panelRef}
472 className="flex min-h-0 flex-1 flex-col bg-background"
473 data-file-browser-panel={`${environmentId}:${cwd}`}
474 >
475 <div
476 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"
477 data-surface-subheader
478 >
479 <RefreshFilesButton isPending={isPending} onRefresh={handleRefresh} />
480 <FileSearchField
481 name="project-files-search"
482 ariaLabel={`Search ${projectName} files`}
483 value={search.value}
484 onValueChange={handleSearchValueChange}
485 onClose={closeSearch}
486 />
487 {directoryPaths.length > 0 ? (
488 <Tooltip>
489 <TooltipTrigger
490 render={
491 <Button
492 type="button"
493 size="icon-xs"
494 variant="ghost"
495 aria-label={
496 expandAll || allDirectoriesExpanded
497 ? "Collapse all folders"
498 : "Expand all folders"
499 }
500 onClick={toggleAllDirectories}
501 />
502 }
503 >
504 {allDirectoriesExpanded ? (
505 <ChevronsDownUpIcon className="size-3.5" />
506 ) : (
507 <ChevronsUpDownIcon className="size-3.5" />
508 )}
509 </TooltipTrigger>
510 <TooltipPopup>
511 {expandAll || allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
512 </TooltipPopup>
513 </Tooltip>
514 ) : null}
515 </div>
516 {error || pathSearch.error ? (
517 <button
518 type="button"
519 onClick={handleRefresh}
520 className="p-4 text-left text-xs leading-relaxed text-destructive"
521 >
522 {error ?? pathSearch.error} Click to retry.
523 </button>
524 ) : null}
525 {query.trim() && pathSearch.truncated && !pathSearch.isPending ? (
526 <div className="px-3 py-1 text-xs text-muted-foreground">
527 More matches available. Refine your search.
528 </div>
529 ) : null}
530 {(isPending || pathSearch.isPending) && (
531 <div role="status" className="px-3 py-1 text-xs text-muted-foreground">
532 Loading files…
533 </div>
534 )}
535 <FileTree
536 model={model}
537 aria-label={`${projectName} files`}
538 className="min-h-0 flex-1 overflow-hidden"
539 style={pierreTreeStyle(resolvedTheme)}
540 />
541 </div>
542 );
543}