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

FileBrowserPanel.tsx

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