Open History to see the last commit
1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import { contextMenuSourceOf } from "../../contextMenuSource";
3import { m } from "~/i18n/messages";
4import { RefreshIcon } from "~/components/ui/refresh-icon";
5import type {
6 ContextMenuItem as TreeContextMenuItem,
7 ContextMenuOpenContext as TreeContextMenuOpenContext,
8} from "@pierre/trees";
9import type { ContextMenuSource, EnvironmentId, ProjectEntry } from "@t3tools/contracts";
10import { FileTree, useFileTree, useFileTreeSearch, useFileTreeSelector } from "@pierre/trees/react";
11import { settlePromise } from "@t3tools/client-runtime/state/runtime";
12import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
13import * as AsyncResult from "effect/reactivity/AsyncResult";
14import * as Cause from "effect/Cause";
15import { T, useGT, useMessages } from "gt-react";
16import { ChevronsDownUpIcon, ChevronsUpDownIcon } from "lucide-react";
17import { type Ref, useEffect, useEffectEvent, useRef, useState } from "react";
18
19import { Button } from "~/components/ui/button";
20import { InputGroup, InputGroupInput } from "~/components/ui/input-group";
21import { toastManager } from "~/components/ui/toast";
22import { useComposerHandleContext } from "~/composerHandleContext";
23import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
24import { useStableCallback } from "~/hooks/useStableCallback";
25import { useTheme } from "~/hooks/useTheme";
26import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";
27import { useFileContextMenu, type FileContextMenuAction } from "~/fileContextMenu";
28import { readLocalApi } from "~/localApi";
29import { T3_PIERRE_ICONS } from "~/pierre-icons";
30import {
31 PIERRE_TREE_UNSAFE_CSS,
32 pierreTreeStyle,
33 titleClippedPierreTreeRow,
34} from "~/pierre-tree-theme";
35
36import { joinHostPath } from "./filePath";
37import { createFileTreeDragMentionController } from "./fileTreeDragMention";
38import {
39 areAllDirectoriesExpanded,
40 coalesceReentrantCalls,
41 onlyChildren,
42 readExpandedDirectories,
43 setAllDirectoriesExpanded,
44 writeExpandedDirectories,
45} from "./fileTreeExpansion";
46import { buildFileTreePathUpdates, shouldRebuildFileTree } from "./fileTreePathReconciliation";
47import { loadFileAncestors } from "./loadFileAncestors";
48import { useDirectoryEntries } from "./useDirectoryEntries";
49import { useProjectPathSearch } from "~/state/queries";
50import { isMacPlatform } from "~/lib/utils";
51import { type PreviewAction, subscribePreviewAction } from "../preview/previewActionBus";
52import { SharedTooltipTrigger } from "~/components/ui/shared-tooltip";
53
54interface FileBrowserPanelProps {
55 environmentId: EnvironmentId;
56 cwd: string;
57 projectName: string;
58 selectedPath: string | null;
59 selectedPathRevealId: number;
60 onOpenFile: (relativePath: string) => void;
61 /** Host-folder entries use absolute paths. Avoid full traversal: disable expand-all and search only
62 * loaded folders. */
63 hostFolder?: boolean;
64 onRefreshSelectedFile?: () => void;
65 workspaceMutationId: string | null;
66 answersPanelFind?: boolean;
67}
68
69function treePath(entry: ProjectEntry): string {
70 return entry.kind === "directory" ? `${entry.path}/` : entry.path;
71}
72
73function RefreshFilesButton(props: { isPending: boolean; onRefresh: () => void }) {
74 const gt = useGT();
75 return (
76 <SharedTooltipTrigger
77 render={
78 <Button
79 type="button"
80 variant="ghost"
81 size="icon-xs"
82 aria-label={gt("Refresh workspace files")}
83 onClick={props.onRefresh}
84 />
85 }
86 label={props.isPending ? gt("Refreshing…") : gt("Refresh files")}
87 >
88 <RefreshIcon refreshing={props.isPending} />
89 </SharedTooltipTrigger>
90 );
91}
92
93function FileSearchField({
94 ref,
95 ...props
96}: {
97 ariaLabel: string;
98 name: string;
99 onClose: () => void;
100 onValueChange: (value: string) => void;
101 ref: Ref<HTMLInputElement>;
102 value: string;
103}) {
104 const gt = useGT();
105 return (
106 <InputGroup variant="ghost" className="h-7 min-w-0 flex-1">
107 {/* Native search inputs clear on Escape even during IME composition. */}
108 <InputGroupInput
109 ref={ref}
110 type="text"
111 role="searchbox"
112 name={props.name}
113 size="sm"
114 value={props.value}
115 aria-label={props.ariaLabel}
116 placeholder={gt("Search files")}
117 data-workspace-focus-default
118 spellCheck={false}
119 onChange={(event) => props.onValueChange(event.target.value)}
120 onKeyDown={(event) => {
121 if (event.key !== "Escape" || event.nativeEvent.isComposing || event.keyCode === 229)
122 return;
123 if (props.value || event.repeat) {
124 event.preventDefault();
125 event.stopPropagation();
126 if (props.value) props.onClose();
127 return;
128 }
129 props.onClose();
130 event.currentTarget.blur();
131 }}
132 />
133 </InputGroup>
134 );
135}
136
137function buildTreeEntries(
138 directoryEntries: readonly ProjectEntry[],
139 searchEntries: readonly ProjectEntry[],
140 searchPending: boolean,
141 query: string,
142) {
143 const result = new Map(directoryEntries.map((entry) => [entry.path, entry]));
144 if (query.trim() && !searchPending) {
145 for (const entry of searchEntries) {
146 if (!result.has(entry.path)) result.set(entry.path, entry);
147 const segments = entry.path.split("/");
148 for (let index = 1; index < segments.length; index++) {
149 const path = segments.slice(0, index).join("/");
150 if (!result.has(path)) result.set(path, { path, kind: "directory" });
151 }
152 }
153 }
154 const entries = [...result.values()];
155 const entryKinds: ReadonlyMap<string, ProjectEntry["kind"]> = new Map(
156 entries.map((entry) => [entry.path, entry.kind] as const),
157 );
158 const treePaths = entries.map(treePath);
159 const directories = entries.filter((entry) => entry.kind === "directory");
160 const directoryPaths = directories.map(treePath);
161 // Expanding a folder lists it, and an ignored one such as `node_modules` can hold tens of
162 // thousands, so expand all skips ignored folders. They still open by hand.
163 const expandableDirectoryPaths = directories.filter((entry) => !entry.ignored).map(treePath);
164 return { entries, entryKinds, treePaths, directoryPaths, expandableDirectoryPaths };
165}
166
167// A symlink to its own parent lists itself as an only child without end.
168const MAX_FOLDERS_OPENED_WITH_PARENT = 16;
169
170export default function FileBrowserPanel({
171 environmentId,
172 cwd,
173 projectName,
174 selectedPath,
175 selectedPathRevealId,
176 onOpenFile,
177 onRefreshSelectedFile,
178 workspaceMutationId,
179 hostFolder = false,
180 answersPanelFind = false,
181}: FileBrowserPanelProps) {
182 const panelPath = (relativePath: string) =>
183 hostFolder ? joinHostPath(cwd, relativePath) : relativePath;
184 const gt = useGT();
185 const messages = useMessages();
186 const { resolvedTheme } = useTheme();
187 const composerRef = useComposerHandleContext();
188 const fileContextMenu = useFileContextMenu(environmentId);
189 const {
190 entries: directoryEntries,
191 load,
192 refresh,
193 revalidate,
194 ready,
195 error,
196 isPending,
197 loadingDirectories,
198 } = useDirectoryEntries(environmentId, cwd);
199 const [query, setQuery] = useState("");
200 const [expandAll, setExpandAll] = useState(false);
201 const pathSearch = useProjectPathSearch(
202 { environmentId, cwd: hostFolder ? null : cwd, query: query.slice(0, 256) },
203 200,
204 undefined,
205 messages,
206 );
207 const { entries, entryKinds, treePaths, directoryPaths, expandableDirectoryPaths } =
208 buildTreeEntries(directoryEntries, pathSearch.entries, pathSearch.isPending, query);
209 const entryKindsRef = useRef(entryKinds);
210 const previousTreePathsRef = useRef<readonly string[] | null>(null);
211 const syncingSelectionRef = useRef(false);
212 const treeSelectionPathRef = useRef<string | null>(null);
213 const handledRevealRef = useRef<{ path: string; revealId: number } | null>(null);
214 // Tree path of the revealed row. Folders restored or loaded later insert rows above it, so each
215 // path update scrolls to it again until the user takes over the scroll position.
216 const followedRevealRef = useRef<string | null>(null);
217
218 // Shadow-DOM row rects are unreliable; capture the composed contextmenu event's viewport position.
219 const contextMenuPointerRef = useRef<{
220 x: number;
221 y: number;
222 at: number;
223 source: ContextMenuSource;
224 } | null>(null);
225
226 const showEntryContextMenu = useStableCallback(
227 (item: TreeContextMenuItem, context: TreeContextMenuOpenContext) => {
228 const api = readLocalApi();
229 if (!api) {
230 context.close();
231 return;
232 }
233 const relativePath = item.path.replace(/\/$/, "");
234 const mention = serializeComposerFileLink(panelPath(relativePath));
235 const pointer = contextMenuPointerRef.current;
236 const pointerIsFresh = pointer !== null && performance.now() - pointer.at < 1000;
237 const anchorRect = context.anchorElement.getBoundingClientRect();
238 const position = pointerIsFresh
239 ? { x: pointer.x, y: pointer.y }
240 : { x: anchorRect.left, y: anchorRect.bottom };
241 const fileTarget = {
242 environmentId,
243 filePath: relativePath,
244 workspaceRoot: cwd,
245 isDirectory: item.kind === "directory",
246 };
247 const fileMenuItems = fileContextMenu.buildItems(fileTarget);
248 // The app menu owns focus; the tree's outside-click handler would dismiss it before click.
249 context.close({ restoreFocus: !pointerIsFresh });
250 void settlePromise(async () => {
251 const clicked = await api.contextMenu.show(
252 [
253 ...fileMenuItems,
254 { id: "copy-mention", label: gt("Copy mention") },
255 { id: "add-to-chat", label: gt("Add to chat") },
256 ],
257 position,
258 pointerIsFresh ? pointer.source : undefined,
259 );
260 if (clicked === null) return;
261 // Open-with submenu ids are absent from the top-level item list.
262 const isFileMenuAction =
263 fileMenuItems.some((entry) => entry.id === clicked) || clicked.startsWith("editor:");
264 if (isFileMenuAction) {
265 await fileContextMenu.activate(clicked as FileContextMenuAction, fileTarget);
266 return;
267 }
268 if (clicked === "copy-mention") {
269 try {
270 await writeTextToClipboard(mention);
271 } catch (error) {
272 toastManager.add({
273 type: "error",
274 title: gt("Failed to copy mention"),
275 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
276 });
277 }
278 return;
279 }
280 if (clicked === "add-to-chat") {
281 const composer = composerRef?.current;
282 if (!composer) {
283 toastManager.add({
284 type: "error",
285 title: gt("Unable to add to chat"),
286 description: gt("Open a chat for this project and try again."),
287 });
288 return;
289 }
290 const inserted = composer.insertTextAtEnd(`${mention} `, { ensureLeadingBoundary: true });
291 if (!inserted) {
292 toastManager.add({
293 type: "error",
294 title: gt("Unable to add to chat"),
295 description: gt("The chat isn't ready to accept input right now."),
296 });
297 }
298 }
299 }).then((result) => {
300 if (!AsyncResult.isSuccess(result)) throw Cause.squash(result.cause);
301 });
302 },
303 );
304
305 const loadingDirectoriesRef = useRef(loadingDirectories);
306 const revalidateDirectory = useStableCallback(revalidate);
307 const dragMention = createFileTreeDragMentionController(
308 hostFolder ? { mentionPath: (path: string) => joinHostPath(cwd, path) } : {},
309 );
310 const { model } = useFileTree({
311 composition: {
312 contextMenu: {
313 triggerMode: "right-click",
314 onOpen: (item, context) => {
315 showEntryContextMenu(item, context);
316 },
317 },
318 },
319 dragAndDrop: { canDrop: () => false },
320 density: "compact",
321 fileTreeSearchMode: "hide-non-matches",
322 flattenEmptyDirectories: true,
323 initialExpansion: "closed",
324 icons: T3_PIERRE_ICONS,
325 onSelectionChange: (selectedPaths) => {
326 // Update drag selection even for reveals so subsequent drags cannot use stale paths.
327 dragMention.handleSelectionChange(selectedPaths);
328 if (syncingSelectionRef.current) return;
329 if (dragMention.isDragInProgress()) {
330 return;
331 }
332 const selectedPath = selectedPaths.at(-1)?.replace(/\/$/, "");
333 if (selectedPath && entryKindsRef.current.get(selectedPath) === "file") {
334 treeSelectionPathRef.current = selectedPath;
335 onOpenFile(panelPath(selectedPath));
336 }
337 },
338 paths: [],
339 renderRowDecoration: ({ item, row }) => {
340 const path = item.path.replace(/\/$/, "");
341 const open = row.kind === "directory" && row.isExpanded;
342 // Pierre calls this for the rows it renders, which is the only sign of what is on screen.
343 revalidateDirectory(open ? path : path.slice(0, Math.max(0, path.lastIndexOf("/"))));
344 return open && loadingDirectoriesRef.current.has(path)
345 ? { icon: "t3-tree-icon-loading", title: gt("Loading…") }
346 : null;
347 },
348 search: false,
349 onSearchChange: (value) => setQuery(value ?? ""),
350 unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
351 });
352 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- makes the Pierre tree model re-render row decorations when loading directories change
353 useEffect(() => {
354 if (loadingDirectoriesRef.current === loadingDirectories) return;
355 loadingDirectoriesRef.current = loadingDirectories;
356 model.setComposition(model.getComposition());
357 }, [loadingDirectories, model]);
358 const search = useFileTreeSearch(model);
359 // Pierre restores the unfiltered tree when a search has no matches.
360 const hasNoSearchMatches = search.value.trim().length > 0 && search.matchingPaths.length === 0;
361 const allDirectoriesExpanded = useFileTreeSelector(model, (currentModel) =>
362 areAllDirectoriesExpanded(currentModel, expandableDirectoryPaths),
363 );
364 const toggleAllDirectories = () => {
365 const expanded = !(expandAll || allDirectoriesExpanded);
366 setExpandAll(expanded);
367 setAllDirectoriesExpanded(
368 model,
369 expanded ? expandableDirectoryPaths : directoryPaths,
370 expanded,
371 );
372 };
373 const closeSearch = () => {
374 setQuery("");
375 search.close();
376 };
377 const searchInputRef = useRef<HTMLInputElement>(null);
378 const focusSearch = () => {
379 searchInputRef.current?.focus();
380 searchInputRef.current?.select();
381 };
382 const onPanelAction = useEffectEvent((action: PreviewAction) => {
383 // Hidden panel tabs stay mounted; only the visible Files tab answers.
384 if (action === "find" && searchInputRef.current?.getClientRects().length) focusSearch();
385 });
386 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the panel find command, which fires while focus is anywhere in the right panel
387 useEffect(() => {
388 if (!answersPanelFind) return;
389 return subscribePreviewAction(onPanelAction);
390 }, [answersPanelFind]);
391 const expandedPathsRef = useRef(new Set<string>());
392 const expansionRoot = `${environmentId}:${cwd}`;
393 // Folders expanded when the panel last unmounted; each reopens once lazy loading lists it.
394 const [pendingExpandedPaths] = useState(() => new Set(readExpandedDirectories(expansionRoot)));
395 // Folders just opened and not listed yet, with how many only-child folders may open below each.
396 // Pierre merges such a chain into one row that takes its open state from the last folder.
397 const openingPathsRef = useRef(new Map<string, number>());
398 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the Pierre tree model to load directories as they are expanded
399 useEffect(() => {
400 const currentPaths = new Set(directoryPaths);
401 for (const path of expandedPathsRef.current) {
402 if (!currentPaths.has(path)) expandedPathsRef.current.delete(path);
403 }
404 for (const path of openingPathsRef.current.keys()) {
405 if (!currentPaths.has(path)) openingPathsRef.current.delete(path);
406 }
407 let childrenByParent: ReadonlyMap<string, ProjectEntry | null> | null = null;
408 const openOnlyChild = (path: string) => {
409 const remaining = openingPathsRef.current.get(path);
410 if (remaining === undefined) return;
411 if (childrenByParent === null) childrenByParent = onlyChildren(directoryEntries);
412 const child = childrenByParent.get(path.replace(/\/$/, ""));
413 if (child === undefined) return;
414 // Like expand all, leave an ignored folder such as `node_modules` to open by hand.
415 const opensChild =
416 child?.kind === "directory" &&
417 (!child.ignored ||
418 directoryEntries.some((entry) => entry.ignored && treePath(entry) === path));
419 if (!opensChild || remaining === 0) {
420 openingPathsRef.current.delete(path);
421 return;
422 }
423 const childItem = model.getItem(treePath(child));
424 // The listing reaches the tree after this effect, which notifies again.
425 if (!childItem || !("expand" in childItem)) return;
426 openingPathsRef.current.delete(path);
427 if (childItem.isExpanded()) return;
428 openingPathsRef.current.set(treePath(child), remaining - 1);
429 childItem.expand();
430 };
431 // Restoring calls item.expand(), which notifies subscribers synchronously.
432 const loadExpanded = coalesceReentrantCalls(() => {
433 if (model.isSearchOpen()) return;
434 let changed = false;
435 for (const path of directoryPaths) {
436 const item = model.getItem(path);
437 const restored = item?.isDirectory() && pendingExpandedPaths.delete(path);
438 if (restored && item && "expand" in item) item.expand();
439 if (item?.isDirectory() && "isExpanded" in item && item.isExpanded()) {
440 if (!expandedPathsRef.current.has(path)) {
441 expandedPathsRef.current.add(path);
442 changed = true;
443 if (!restored && !openingPathsRef.current.has(path)) {
444 openingPathsRef.current.set(path, MAX_FOLDERS_OPENED_WITH_PARENT);
445 }
446 void load(path.replace(/\/$/, ""));
447 }
448 openOnlyChild(path);
449 } else {
450 if (item?.isDirectory() && expandedPathsRef.current.has(path)) setExpandAll(false);
451 openingPathsRef.current.delete(path);
452 if (expandedPathsRef.current.delete(path)) changed = true;
453 }
454 }
455 if (changed) {
456 writeExpandedDirectories(expansionRoot, [
457 ...expandedPathsRef.current,
458 ...pendingExpandedPaths,
459 ]);
460 }
461 });
462 loadExpanded();
463 return model.subscribe(loadExpanded);
464 }, [directoryEntries, directoryPaths, expansionRoot, load, model, pendingExpandedPaths]);
465 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes ignored-file status into the imperative Pierre tree model
466 useEffect(() => {
467 model.setGitStatus(
468 entries
469 .filter((entry) => entry.ignored)
470 .map((entry) => ({
471 path: treePath(entry),
472 status: "ignored",
473 })),
474 );
475 }, [entries, model]);
476 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- loads the selected file's ancestor directories and aborts on cleanup
477 useEffect(() => {
478 if (!selectedPath) return;
479 const controller = new AbortController();
480 void loadFileAncestors(selectedPath, load, { signal: controller.signal });
481 return () => {
482 controller.abort();
483 };
484 }, [load, selectedPath]);
485 const stopFollowingReveal = () => {
486 followedRevealRef.current = null;
487 };
488 const handleSearchValueChange = (value: string) => {
489 setQuery(value);
490 if (value.trim().length === 0) {
491 search.close();
492 return;
493 }
494 search.setValue(value);
495 };
496 const refreshDirectories = () => {
497 refresh();
498 // Renders the rows again, so each one on screen revalidates the folders it comes from.
499 model.setComposition(model.getComposition());
500 };
501 const handleRefresh = () => {
502 refreshDirectories();
503 if (query.trim()) pathSearch.refresh();
504 onRefreshSelectedFile?.();
505 };
506 useWorkspaceMutationRefresh({
507 mutationId: workspaceMutationId,
508 refresh: () => {
509 refreshDirectories();
510 if (query.trim()) pathSearch.refresh();
511 },
512 resourceKey: `files:${environmentId}:${cwd}`,
513 });
514
515 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- applies tree path changes to the imperative Pierre tree model as a reset or batch update
516 useEffect(() => {
517 if (!ready) return;
518 if (previousTreePathsRef.current === treePaths) return;
519 entryKindsRef.current = entryKinds;
520 const previousTreePaths = previousTreePathsRef.current;
521 previousTreePathsRef.current = treePaths;
522 if (previousTreePaths === null) {
523 model.resetPaths(treePaths);
524 return;
525 }
526 const updates = buildFileTreePathUpdates(previousTreePaths, treePaths);
527 if (shouldRebuildFileTree(previousTreePaths, treePaths, updates)) {
528 // A reset keeps old search matches, so search closes first and recomputes afterwards.
529 const activeSearch = model.isSearchOpen() ? model.getSearchValue() : null;
530 if (activeSearch !== null) model.closeSearch();
531 model.resetPaths(treePaths, { initialExpandedPaths: [...expandedPathsRef.current] });
532 if (activeSearch !== null) model.setSearch(activeSearch);
533 } else if (updates.length > 0) {
534 model.batch(updates);
535 } else {
536 return;
537 }
538 if (followedRevealRef.current !== null) {
539 model.scrollToPath(followedRevealRef.current, { focus: false, offset: "center" });
540 }
541 }, [ready, entryKinds, model, treePaths]);
542
543 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- expands every directory in the Pierre tree model while expand-all is on and no search is active
544 useEffect(() => {
545 if (expandAll && !query.trim())
546 setAllDirectoriesExpanded(model, expandableDirectoryPaths, true);
547 }, [expandableDirectoryPaths, expandAll, model, query]);
548
549 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reveals an externally selected path in the Pierre tree model by expanding, selecting and scrolling
550 useEffect(() => {
551 if (!selectedPath) {
552 handledRevealRef.current = null;
553 followedRevealRef.current = null;
554 return;
555 }
556 const selectedKind = entryKinds.get(selectedPath);
557 if (selectedKind === undefined) {
558 handledRevealRef.current = null;
559 return;
560 }
561 const revealRequest = { path: selectedPath, revealId: selectedPathRevealId };
562 const handledReveal = handledRevealRef.current;
563 // Refresh rebuilds treePaths; replaying handled reveals would close search and steal focus.
564 if (
565 handledReveal?.path === revealRequest.path &&
566 handledReveal.revealId === revealRequest.revealId
567 ) {
568 return;
569 }
570 const selectedTreePath = selectedKind === "directory" ? `${selectedPath}/` : selectedPath;
571 const selectedItem = model.getItem(selectedTreePath);
572 if (!selectedItem) return;
573
574 // Reveal only external selections; tree selections are visible and re-revealing would close search.
575 const selectedInTree = model
576 .getSelectedPaths()
577 .some((path) => path.replace(/\/$/, "") === selectedPath);
578 if (selectedInTree && treeSelectionPathRef.current === selectedPath) {
579 treeSelectionPathRef.current = null;
580 handledRevealRef.current = revealRequest;
581 followedRevealRef.current = null;
582 return;
583 }
584 treeSelectionPathRef.current = null;
585 handledRevealRef.current = revealRequest;
586
587 syncingSelectionRef.current = true;
588 setQuery("");
589 model.closeSearch();
590 for (const path of model.getSelectedPaths()) {
591 model.getItem(path)?.deselect();
592 }
593
594 // Directory paths include trailing slashes; ancestor lookups must match.
595 const segments = selectedPath.split("/");
596 let ancestorPath = "";
597 for (const segment of segments.slice(0, -1)) {
598 ancestorPath = ancestorPath ? `${ancestorPath}/${segment}` : segment;
599 const item = model.getItem(`${ancestorPath}/`) ?? model.getItem(ancestorPath);
600 if (item && "expand" in item) item.expand();
601 }
602
603 if ("expand" in selectedItem) selectedItem.expand();
604 selectedItem.select();
605 model.scrollToPath(selectedTreePath, {
606 focus: true,
607 offset: "center",
608 });
609 followedRevealRef.current = selectedTreePath;
610 queueMicrotask(() => {
611 syncingSelectionRef.current = false;
612 });
613 }, [entryKinds, model, selectedPath, selectedPathRevealId]);
614
615 return (
616 <div
617 className="flex min-h-0 flex-1 flex-col bg-background"
618 data-file-browser-panel={`${environmentId}:${cwd}`}
619 // Capture runs before the tree's shadow-internal row handler opens the menu.
620 onContextMenuCapture={(event) => {
621 contextMenuPointerRef.current = {
622 x: event.clientX,
623 y: event.clientY,
624 at: event.timeStamp,
625 source: contextMenuSourceOf(event),
626 };
627 }}
628 // Capture dragstart before the tree selects the row so selection sees the drag flag.
629 onDragStartCapture={(event) => dragMention.handleDragStart(event.nativeEvent)}
630 onDragEnd={() => dragMention.handleDragEnd((path) => model.getItem(path)?.deselect())}
631 onWheel={stopFollowingReveal}
632 onPointerDown={stopFollowingReveal}
633 onTouchStart={stopFollowingReveal}
634 onKeyDown={(event) => {
635 stopFollowingReveal();
636 const isModPressed = isMacPlatform(navigator.platform) ? event.metaKey : event.ctrlKey;
637 if (!isModPressed || event.altKey || event.shiftKey || event.key.toLowerCase() !== "f")
638 return;
639 event.preventDefault();
640 focusSearch();
641 }}
642 >
643 <div
644 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"
645 data-surface-subheader
646 >
647 <RefreshFilesButton isPending={isPending} onRefresh={handleRefresh} />
648 <FileSearchField
649 ref={searchInputRef}
650 name="project-files-search"
651 ariaLabel={gt("Search {projectName} files", { projectName })}
652 value={search.value}
653 onValueChange={handleSearchValueChange}
654 onClose={closeSearch}
655 />
656 {directoryPaths.length > 0 && !hostFolder ? (
657 <SharedTooltipTrigger
658 render={
659 <Button
660 type="button"
661 size="icon-xs"
662 variant="ghost"
663 aria-label={
664 expandAll || allDirectoriesExpanded
665 ? gt("Collapse all folders")
666 : gt("Expand all folders")
667 }
668 onClick={toggleAllDirectories}
669 />
670 }
671 label={
672 expandAll || allDirectoriesExpanded
673 ? gt("Collapse all folders")
674 : gt("Expand all folders")
675 }
676 >
677 {allDirectoriesExpanded ? (
678 <ChevronsDownUpIcon className="size-3.5" />
679 ) : (
680 <ChevronsUpDownIcon className="size-3.5" />
681 )}
682 </SharedTooltipTrigger>
683 ) : null}
684 </div>
685 {error || pathSearch.error ? (
686 <button
687 type="button"
688 onClick={handleRefresh}
689 className="p-4 text-left text-xs leading-relaxed text-destructive"
690 >
691 {gt("{error} Click to retry.", { error: error ?? pathSearch.error })}
692 </button>
693 ) : null}
694 {query.trim() && pathSearch.truncated && !pathSearch.isPending ? (
695 <div className="px-3 py-1 text-xs text-muted-foreground">
696 <T>More matches available. Refine your search.</T>
697 </div>
698 ) : null}
699 {(!ready || pathSearch.isPending) && (
700 <div
701 role="status"
702 className={
703 entries.length > 0 && !hasNoSearchMatches
704 ? "sr-only"
705 : "px-3 py-1 text-xs text-muted-foreground"
706 }
707 >
708 <T>Loading files…</T>
709 </div>
710 )}
711 {hasNoSearchMatches ? (
712 ready && !isPending && !pathSearch.isPending && !error && !pathSearch.error ? (
713 <div role="status" className="px-3 py-4 text-xs text-muted-foreground">
714 <T>No matching files.</T>
715 </div>
716 ) : null
717 ) : (
718 <FileTree
719 model={model}
720 aria-label={gt("{projectName} files", { projectName })}
721 className="min-h-0 flex-1 overflow-hidden"
722 onClickCapture={(event) => {
723 if (
724 event.defaultPrevented ||
725 event.button !== 0 ||
726 event.ctrlKey ||
727 event.metaKey ||
728 event.shiftKey ||
729 event.altKey ||
730 dragMention.isDragInProgress()
731 ) {
732 return;
733 }
734 // Pierre emits no change for its sole selected row; read before the click to avoid double opens.
735 const selected = model.getSelectedPaths();
736 const path = selected.length === 1 ? selected[0] : undefined;
737 if (!path || entryKindsRef.current.get(path) !== "file") return;
738 const clickedSelectedRow = event.nativeEvent
739 .composedPath()
740 .some(
741 (node) =>
742 node instanceof HTMLElement && node.getAttribute("data-item-path") === path,
743 );
744 if (!clickedSelectedRow) return;
745 treeSelectionPathRef.current = path;
746 onOpenFile(panelPath(path));
747 }}
748 style={pierreTreeStyle(resolvedTheme)}
749 onPointerOver={titleClippedPierreTreeRow}
750 />
751 )}
752 </div>
753 );
754}