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

FileBrowserPanel.tsx

658 lines25.2 KB

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