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