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

FileBrowserPanel.tsx

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