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

FileBrowserPanel.tsx

756 lines29.5 KB

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;
68​
69function treePath(entry: ProjectEntry): string {
70 return entry.kind === "directory" ? `${entry.path}/` : entry.path;
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 );
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 );
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 };
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-path", label: gt("Copy path") },
255 { id: "copy-mention", label: gt("Copy mention") },
256 { id: "add-to-chat", label: gt("Add to chat") },
257 ],
258 position,
259 pointerIsFresh ? pointer.source : undefined,
260 );
261 if (clicked === null) return;
262 // Open-with submenu ids are absent from the top-level item list.
263 const isFileMenuAction =
264 fileMenuItems.some((entry) => entry.id === clicked) || clicked.startsWith("editor:");
265 if (isFileMenuAction) {
266 await fileContextMenu.activate(clicked as FileContextMenuAction, fileTarget);
267 return;
268 }
269 if (clicked === "copy-path" || clicked === "copy-mention") {
270 const copyingPath = clicked === "copy-path";
271 try {
272 await writeTextToClipboard(copyingPath ? joinHostPath(cwd, relativePath) : mention);
273 } catch (error) {
274 toastManager.add({
275 type: "error",
276 title: copyingPath ? gt("Failed to copy path") : gt("Failed to copy mention"),
277 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
278 });
279 }
280 return;
281 }
282 if (clicked === "add-to-chat") {
283 const composer = composerRef?.current;
284 if (!composer) {
285 toastManager.add({
286 type: "error",
287 title: gt("Unable to add to chat"),
288 description: gt("Open a chat for this project and try again."),
289 });
290 return;
291 }
292 const inserted = composer.insertTextAtEnd(`${mention} `, { ensureLeadingBoundary: true });
293 if (!inserted) {
294 toastManager.add({
295 type: "error",
296 title: gt("Unable to add to chat"),
297 description: gt("The chat isn't ready to accept input right now."),
298 });
299 }
300 }
301 }).then((result) => {
302 if (!AsyncResult.isSuccess(result)) throw Cause.squash(result.cause);
303 });
304 },
305 );
306​
307 const loadingDirectoriesRef = useRef(loadingDirectories);
308 const revalidateDirectory = useStableCallback(revalidate);
309 const dragMention = createFileTreeDragMentionController(
310 hostFolder ? { mentionPath: (path: string) => joinHostPath(cwd, path) } : {},
311 );
312 const { model } = useFileTree({
313 composition: {
314 contextMenu: {
315 triggerMode: "right-click",
316 onOpen: (item, context) => {
317 showEntryContextMenu(item, context);
318 },
319 },
320 },
321 dragAndDrop: { canDrop: () => false },
322 density: "compact",
323 fileTreeSearchMode: "hide-non-matches",
324 flattenEmptyDirectories: true,
325 initialExpansion: "closed",
326 icons: T3_PIERRE_ICONS,
327 onSelectionChange: (selectedPaths) => {
328 // Update drag selection even for reveals so subsequent drags cannot use stale paths.
329 dragMention.handleSelectionChange(selectedPaths);
330 if (syncingSelectionRef.current) return;
331 if (dragMention.isDragInProgress()) {
332 return;
333 }
334 const selectedPath = selectedPaths.at(-1)?.replace(/\/$/, "");
335 if (selectedPath && entryKindsRef.current.get(selectedPath) === "file") {
336 treeSelectionPathRef.current = selectedPath;
337 onOpenFile(panelPath(selectedPath));
338 }
339 },
340 paths: [],
341 renderRowDecoration: ({ item, row }) => {
342 const path = item.path.replace(/\/$/, "");
343 const open = row.kind === "directory" && row.isExpanded;
344 // Pierre calls this for the rows it renders, which is the only sign of what is on screen.
345 revalidateDirectory(open ? path : path.slice(0, Math.max(0, path.lastIndexOf("/"))));
346 return open && loadingDirectoriesRef.current.has(path)
347 ? { icon: "t3-tree-icon-loading", title: gt("Loading…") }
348 : null;
349 },
350 search: false,
351 onSearchChange: (value) => setQuery(value ?? ""),
352 unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
353 });
354 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- makes the Pierre tree model re-render row decorations when loading directories change
355 useEffect(() => {
356 if (loadingDirectoriesRef.current === loadingDirectories) return;
357 loadingDirectoriesRef.current = loadingDirectories;
358 model.setComposition(model.getComposition());
359 }, [loadingDirectories, model]);
360 const search = useFileTreeSearch(model);
361 // Pierre restores the unfiltered tree when a search has no matches.
362 const hasNoSearchMatches = search.value.trim().length > 0 && search.matchingPaths.length === 0;
363 const allDirectoriesExpanded = useFileTreeSelector(model, (currentModel) =>
364 areAllDirectoriesExpanded(currentModel, expandableDirectoryPaths),
365 );
366 const toggleAllDirectories = () => {
367 const expanded = !(expandAll || allDirectoriesExpanded);
368 setExpandAll(expanded);
369 setAllDirectoriesExpanded(
370 model,
371 expanded ? expandableDirectoryPaths : directoryPaths,
372 expanded,
373 );
374 };
375 const closeSearch = () => {
376 setQuery("");
377 search.close();
378 };
379 const searchInputRef = useRef<HTMLInputElement>(null);
380 const focusSearch = () => {
381 searchInputRef.current?.focus();
382 searchInputRef.current?.select();
383 };
384 const onPanelAction = useEffectEvent((action: PreviewAction) => {
385 // Hidden panel tabs stay mounted; only the visible Files tab answers.
386 if (action === "find" && searchInputRef.current?.getClientRects().length) focusSearch();
387 });
388 // 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
389 useEffect(() => {
390 if (!answersPanelFind) return;
391 return subscribePreviewAction(onPanelAction);
392 }, [answersPanelFind]);
393 const expandedPathsRef = useRef(new Set<string>());
394 const expansionRoot = `${environmentId}:${cwd}`;
395 // Folders expanded when the panel last unmounted; each reopens once lazy loading lists it.
396 const [pendingExpandedPaths] = useState(() => new Set(readExpandedDirectories(expansionRoot)));
397 // Folders just opened and not listed yet, with how many only-child folders may open below each.
398 // Pierre merges such a chain into one row that takes its open state from the last folder.
399 const openingPathsRef = useRef(new Map<string, number>());
400 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the Pierre tree model to load directories as they are expanded
401 useEffect(() => {
402 const currentPaths = new Set(directoryPaths);
403 for (const path of expandedPathsRef.current) {
404 if (!currentPaths.has(path)) expandedPathsRef.current.delete(path);
405 }
406 for (const path of openingPathsRef.current.keys()) {
407 if (!currentPaths.has(path)) openingPathsRef.current.delete(path);
408 }
409 let childrenByParent: ReadonlyMap<string, ProjectEntry | null> | null = null;
410 const openOnlyChild = (path: string) => {
411 const remaining = openingPathsRef.current.get(path);
412 if (remaining === undefined) return;
413 if (childrenByParent === null) childrenByParent = onlyChildren(directoryEntries);
414 const child = childrenByParent.get(path.replace(/\/$/, ""));
415 if (child === undefined) return;
416 // Like expand all, leave an ignored folder such as `node_modules` to open by hand.
417 const opensChild =
418 child?.kind === "directory" &&
419 (!child.ignored ||
420 directoryEntries.some((entry) => entry.ignored && treePath(entry) === path));
421 if (!opensChild || remaining === 0) {
422 openingPathsRef.current.delete(path);
423 return;
424 }
425 const childItem = model.getItem(treePath(child));
426 // The listing reaches the tree after this effect, which notifies again.
427 if (!childItem || !("expand" in childItem)) return;
428 openingPathsRef.current.delete(path);
429 if (childItem.isExpanded()) return;
430 openingPathsRef.current.set(treePath(child), remaining - 1);
431 childItem.expand();
432 };
433 // Restoring calls item.expand(), which notifies subscribers synchronously.
434 const loadExpanded = coalesceReentrantCalls(() => {
435 if (model.isSearchOpen()) return;
436 let changed = false;
437 for (const path of directoryPaths) {
438 const item = model.getItem(path);
439 const restored = item?.isDirectory() && pendingExpandedPaths.delete(path);
440 if (restored && item && "expand" in item) item.expand();
441 if (item?.isDirectory() && "isExpanded" in item && item.isExpanded()) {
442 if (!expandedPathsRef.current.has(path)) {
443 expandedPathsRef.current.add(path);
444 changed = true;
445 if (!restored && !openingPathsRef.current.has(path)) {
446 openingPathsRef.current.set(path, MAX_FOLDERS_OPENED_WITH_PARENT);
447 }
448 void load(path.replace(/\/$/, ""));
449 }
450 openOnlyChild(path);
451 } else {
452 if (item?.isDirectory() && expandedPathsRef.current.has(path)) setExpandAll(false);
453 openingPathsRef.current.delete(path);
454 if (expandedPathsRef.current.delete(path)) changed = true;
455 }
456 }
457 if (changed) {
458 writeExpandedDirectories(expansionRoot, [
459 ...expandedPathsRef.current,
460 ...pendingExpandedPaths,
461 ]);
462 }
463 });
464 loadExpanded();
465 return model.subscribe(loadExpanded);
466 }, [directoryEntries, directoryPaths, expansionRoot, load, model, pendingExpandedPaths]);
467 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes ignored-file status into the imperative Pierre tree model
468 useEffect(() => {
469 model.setGitStatus(
470 entries
471 .filter((entry) => entry.ignored)
472 .map((entry) => ({
473 path: treePath(entry),
474 status: "ignored",
475 })),
476 );
477 }, [entries, model]);
478 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- loads the selected file's ancestor directories and aborts on cleanup
479 useEffect(() => {
480 if (!selectedPath) return;
481 const controller = new AbortController();
482 void loadFileAncestors(selectedPath, load, { signal: controller.signal });
483 return () => {
484 controller.abort();
485 };
486 }, [load, selectedPath]);
487 const stopFollowingReveal = () => {
488 followedRevealRef.current = null;
489 };
490 const handleSearchValueChange = (value: string) => {
491 setQuery(value);
492 if (value.trim().length === 0) {
493 search.close();
494 return;
495 }
496 search.setValue(value);
497 };
498 const refreshDirectories = () => {
499 refresh();
500 // Renders the rows again, so each one on screen revalidates the folders it comes from.
501 model.setComposition(model.getComposition());
502 };
503 const handleRefresh = () => {
504 refreshDirectories();
505 if (query.trim()) pathSearch.refresh();
506 onRefreshSelectedFile?.();
507 };
508 useWorkspaceMutationRefresh({
509 mutationId: workspaceMutationId,
510 refresh: () => {
511 refreshDirectories();
512 if (query.trim()) pathSearch.refresh();
513 },
514 resourceKey: `files:${environmentId}:${cwd}`,
515 });
516​
517 // 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
518 useEffect(() => {
519 if (!ready) return;
520 if (previousTreePathsRef.current === treePaths) return;
521 entryKindsRef.current = entryKinds;
522 const previousTreePaths = previousTreePathsRef.current;
523 previousTreePathsRef.current = treePaths;
524 if (previousTreePaths === null) {
525 model.resetPaths(treePaths);
526 return;
527 }
528 const updates = buildFileTreePathUpdates(previousTreePaths, treePaths);
529 if (shouldRebuildFileTree(previousTreePaths, treePaths, updates)) {
530 // A reset keeps old search matches, so search closes first and recomputes afterwards.
531 const activeSearch = model.isSearchOpen() ? model.getSearchValue() : null;
532 if (activeSearch !== null) model.closeSearch();
533 model.resetPaths(treePaths, { initialExpandedPaths: [...expandedPathsRef.current] });
534 if (activeSearch !== null) model.setSearch(activeSearch);
535 } else if (updates.length > 0) {
536 model.batch(updates);
537 } else {
538 return;
539 }
540 if (followedRevealRef.current !== null) {
541 model.scrollToPath(followedRevealRef.current, { focus: false, offset: "center" });
542 }
543 }, [ready, entryKinds, model, treePaths]);
544​
545 // 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
546 useEffect(() => {
547 if (expandAll && !query.trim())
548 setAllDirectoriesExpanded(model, expandableDirectoryPaths, true);
549 }, [expandableDirectoryPaths, expandAll, model, query]);
550​
551 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reveals an externally selected path in the Pierre tree model by expanding, selecting and scrolling
552 useEffect(() => {
553 if (!selectedPath) {
554 handledRevealRef.current = null;
555 followedRevealRef.current = null;
556 return;
557 }
558 const selectedKind = entryKinds.get(selectedPath);
559 if (selectedKind === undefined) {
560 handledRevealRef.current = null;
561 return;
562 }
563 const revealRequest = { path: selectedPath, revealId: selectedPathRevealId };
564 const handledReveal = handledRevealRef.current;
565 // Refresh rebuilds treePaths; replaying handled reveals would close search and steal focus.
566 if (
567 handledReveal?.path === revealRequest.path &&
568 handledReveal.revealId === revealRequest.revealId
569 ) {
570 return;
571 }
572 const selectedTreePath = selectedKind === "directory" ? `${selectedPath}/` : selectedPath;
573 const selectedItem = model.getItem(selectedTreePath);
574 if (!selectedItem) return;
575​
576 // Reveal only external selections; tree selections are visible and re-revealing would close search.
577 const selectedInTree = model
578 .getSelectedPaths()
579 .some((path) => path.replace(/\/$/, "") === selectedPath);
580 if (selectedInTree && treeSelectionPathRef.current === selectedPath) {
581 treeSelectionPathRef.current = null;
582 handledRevealRef.current = revealRequest;
583 followedRevealRef.current = null;
584 return;
585 }
586 treeSelectionPathRef.current = null;
587 handledRevealRef.current = revealRequest;
588​
589 syncingSelectionRef.current = true;
590 setQuery("");
591 model.closeSearch();
592 for (const path of model.getSelectedPaths()) {
593 model.getItem(path)?.deselect();
594 }
595​
596 // Directory paths include trailing slashes; ancestor lookups must match.
597 const segments = selectedPath.split("/");
598 let ancestorPath = "";
599 for (const segment of segments.slice(0, -1)) {
600 ancestorPath = ancestorPath ? `${ancestorPath}/${segment}` : segment;
601 const item = model.getItem(`${ancestorPath}/`) ?? model.getItem(ancestorPath);
602 if (item && "expand" in item) item.expand();
603 }
604​
605 if ("expand" in selectedItem) selectedItem.expand();
606 selectedItem.select();
607 model.scrollToPath(selectedTreePath, {
608 focus: true,
609 offset: "center",
610 });
611 followedRevealRef.current = selectedTreePath;
612 queueMicrotask(() => {
613 syncingSelectionRef.current = false;
614 });
615 }, [entryKinds, model, selectedPath, selectedPathRevealId]);
616​
617 return (
618 <div
619 className="flex min-h-0 flex-1 flex-col bg-background"
620 data-file-browser-panel={`${environmentId}:${cwd}`}
621 // Capture runs before the tree's shadow-internal row handler opens the menu.
622 onContextMenuCapture={(event) => {
623 contextMenuPointerRef.current = {
624 x: event.clientX,
625 y: event.clientY,
626 at: event.timeStamp,
627 source: contextMenuSourceOf(event),
628 };
629 }}
630 // Capture dragstart before the tree selects the row so selection sees the drag flag.
631 onDragStartCapture={(event) => dragMention.handleDragStart(event.nativeEvent)}
632 onDragEnd={() => dragMention.handleDragEnd((path) => model.getItem(path)?.deselect())}
633 onWheel={stopFollowingReveal}
634 onPointerDown={stopFollowingReveal}
635 onTouchStart={stopFollowingReveal}
636 onKeyDown={(event) => {
637 stopFollowingReveal();
638 const isModPressed = isMacPlatform(navigator.platform) ? event.metaKey : event.ctrlKey;
639 if (!isModPressed || event.altKey || event.shiftKey || event.key.toLowerCase() !== "f")
640 return;
641 event.preventDefault();
642 focusSearch();
643 }}
644 >
645 <div
646 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"
647 data-surface-subheader
648 >
649 <RefreshFilesButton isPending={isPending} onRefresh={handleRefresh} />
650 <FileSearchField
651 ref={searchInputRef}
652 name="project-files-search"
653 ariaLabel={gt("Search {projectName} files", { projectName })}
654 value={search.value}
655 onValueChange={handleSearchValueChange}
656 onClose={closeSearch}
657 />
658 {directoryPaths.length > 0 && !hostFolder ? (
659 <SharedTooltipTrigger
660 render={
661 <Button
662 type="button"
663 size="icon-xs"
664 variant="ghost"
665 aria-label={
666 expandAll || allDirectoriesExpanded
667 ? gt("Collapse all folders")
668 : gt("Expand all folders")
669 }
670 onClick={toggleAllDirectories}
671 />
672 }
673 label={
674 expandAll || allDirectoriesExpanded
675 ? gt("Collapse all folders")
676 : gt("Expand all folders")
677 }
678 >
679 {allDirectoriesExpanded ? (
680 <ChevronsDownUpIcon className="size-3.5" />
681 ) : (
682 <ChevronsUpDownIcon className="size-3.5" />
683 )}
684 </SharedTooltipTrigger>
685 ) : null}
686 </div>
687 {error || pathSearch.error ? (
688 <button
689 type="button"
690 onClick={handleRefresh}
691 className="p-4 text-left text-xs leading-relaxed text-destructive"
692 >
693 {gt("{error} Click to retry.", { error: error ?? pathSearch.error })}
694 </button>
695 ) : null}
696 {query.trim() && pathSearch.truncated && !pathSearch.isPending ? (
697 <div className="px-3 py-1 text-xs text-muted-foreground">
698 <T>More matches available. Refine your search.</T>
699 </div>
700 ) : null}
701 {(!ready || pathSearch.isPending) && (
702 <div
703 role="status"
704 className={
705 entries.length > 0 && !hasNoSearchMatches
706 ? "sr-only"
707 : "px-3 py-1 text-xs text-muted-foreground"
708 }
709 >
710 <T>Loading files…</T>
711 </div>
712 )}
713 {hasNoSearchMatches ? (
714 ready && !isPending && !pathSearch.isPending && !error && !pathSearch.error ? (
715 <div role="status" className="px-3 py-4 text-xs text-muted-foreground">
716 <T>No matching files.</T>
717 </div>
718 ) : null
719 ) : (
720 <FileTree
721 model={model}
722 aria-label={gt("{projectName} files", { projectName })}
723 className="min-h-0 flex-1 overflow-hidden"
724 onClickCapture={(event) => {
725 if (
726 event.defaultPrevented ||
727 event.button !== 0 ||
728 event.ctrlKey ||
729 event.metaKey ||
730 event.shiftKey ||
731 event.altKey ||
732 dragMention.isDragInProgress()
733 ) {
734 return;
735 }
736 // Pierre emits no change for its sole selected row; read before the click to avoid double opens.
737 const selected = model.getSelectedPaths();
738 const path = selected.length === 1 ? selected[0] : undefined;
739 if (!path || entryKindsRef.current.get(path) !== "file") return;
740 const clickedSelectedRow = event.nativeEvent
741 .composedPath()
742 .some(
743 (node) =>
744 node instanceof HTMLElement && node.getAttribute("data-item-path") === path,
745 );
746 if (!clickedSelectedRow) return;
747 treeSelectionPathRef.current = path;
748 onOpenFile(panelPath(path));
749 }}
750 style={pierreTreeStyle(resolvedTheme)}
751 onPointerOver={titleClippedPierreTreeRow}
752 />
753 )}
754 </div>
755 );