import { FullAccessIcon, RestrictedAccessIcon, WorkspaceIcon } from "@/components/icons/product-icons"; import type { HTMLAttributes, ReactElement } from "react"; import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react"; import { ArrowLeft, ArrowRight, Check, ChevronDown, ChevronRight, FolderSearch, History, Search, Star } from "lucide-react"; import { useTranslation } from "react-i18next"; import { ToggleButton } from "@/components/ui/toggle-button"; import { Button } from "@/components/ui/button"; import { floatingItemClassName, floatingItemFocusClassName } from "@/components/ui/floating-surface"; import { HoverHint } from "@/components/ui/tooltip"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import { Input, SearchInput } from "@/components/ui/input"; import { Dialog, DialogContent, DialogTrigger, DialogTitle, DialogDescription } from "@/components/ui/dialog"; import { SidebarSelectionHighlight, SIDEBAR_SELECTION_ITEM_CLASS } from "@/components/SidebarSelectionHighlight"; import type { WorkspaceScopePayload, ProjectDirectory, WorkspaceDirectoriesPayload, WorkspacesPayload } from "@/lib/types"; import { createWorkspaceDirectoryCache } from "@/lib/workspace-directory-cache"; import { useMediaQuery } from "@/hooks/useMediaQuery"; import { cn } from "@/lib/utils"; import { isAbsoluteWorkspacePath, projectNameFromPath, sameWorkspacePath, scopeWithAccessMode, workspaceBreadcrumbs, workspacePathCompletionQuery, workspaceDirectoryPrefix, selectedProjectScope, type BrowseWorkspaceDirectories } from "@/lib/workspace"; function WorkspaceFavoriteButton({ path, pinned, busy, onToggle }: { path: string; pinned: boolean; busy: boolean; onToggle: () => void; }) { const { t } = useTranslation(); const label = t(pinned ? "workspace.picker.unpin" : "workspace.picker.pin", { name: projectNameFromPath(path) }); return ( ); } type PickerOption = ProjectDirectory & { kind: "directory" | "manual" }; type PickerColumn = { path: string; parent: string | null; options: PickerOption[]; selectedPath: string | null; hidden: boolean }; type PickerAncestor = Pick; type PickerVisit = { path: string; ancestors: PickerAncestor[]; filter: string; scrollLeft: number | null; scrollTops: number[] }; type PickerHistory = { visits: PickerVisit[]; index: number; previous: PickerVisit | null; revision: number }; function directoryVisit(path: string, ancestors: PickerAncestor[] = [], scrollTops: number[] = []): PickerVisit { return { path, ancestors: ancestors.map(({ path, parent, selectedPath }) => ({ path, parent, selectedPath })), filter: "", scrollLeft: null, scrollTops }; } function PickerToolButton({ label, disabled, onClick, children }: { label: string; disabled?: boolean; onClick: () => void; children: ReactElement; }) { return ; } const DIRECTORY_ROW_HEIGHT = 44; const DIRECTORY_OVERSCAN = 4; function WorkspaceDirectoryColumn({ options, activeIndex, selectedPath, initialScrollTop, visitRevision, renderOption, children, style, className, ...props }: { options: PickerOption[]; activeIndex: number | null; selectedPath: string | null; initialScrollTop: number; visitRevision: number; renderOption: (option: PickerOption, index: number) => ReactElement; } & HTMLAttributes) { const viewportRef = useRef(null); const [firstRow, setFirstRow] = useState(0); const [visibleRows, setVisibleRows] = useState(1); useLayoutEffect(() => { const viewport = viewportRef.current; if (!viewport) return; // Measure the available slot so rounding the viewport cannot feed back into // its own measurement. Whole rows fit at both edges when scrolling settles. const slot = viewport.parentElement!; const measure = () => setVisibleRows(Math.floor(slot.clientHeight / DIRECTORY_ROW_HEIGHT)); measure(); const observer = new ResizeObserver(measure); observer.observe(slot); return () => observer.disconnect(); }, []); useLayoutEffect(() => { const viewport = viewportRef.current; if (!viewport) return; viewport.scrollTop = initialScrollTop; setFirstRow(Math.floor(viewport.scrollTop / DIRECTORY_ROW_HEIGHT)); }, [options, initialScrollTop, visitRevision]); useLayoutEffect(() => { const viewport = viewportRef.current; if (!viewport || activeIndex === null) return; const top = activeIndex * DIRECTORY_ROW_HEIGHT; const bottom = top + DIRECTORY_ROW_HEIGHT; if (top < viewport.scrollTop) viewport.scrollTop = top; else if (bottom > viewport.scrollTop + viewport.clientHeight) viewport.scrollTop = Math.max(0, bottom - viewport.clientHeight); setFirstRow(Math.floor(viewport.scrollTop / DIRECTORY_ROW_HEIGHT)); }, [activeIndex, visibleRows, options]); const start = Math.max(0, firstRow - DIRECTORY_OVERSCAN); const end = Math.min(options.length, firstRow + visibleRows + DIRECTORY_OVERSCAN); // Proximity snapping allows jumps to rows before their virtual DOM mounts. return (
setFirstRow(Math.floor(event.currentTarget.scrollTop / DIRECTORY_ROW_HEIGHT))}> {options.slice(start, end).map((option, offset) => { const index = start + offset; return
{renderOption(option, index)}
; })}
{children}
); } function WorkspaceDirectorySkeleton() { const { t } = useTranslation(); const viewportRef = useRef(null); const [rows, setRows] = useState(1); useLayoutEffect(() => { const viewport = viewportRef.current; if (!viewport) return; const measure = () => setRows(Math.max(1, Math.floor(viewport.clientHeight / DIRECTORY_ROW_HEIGHT))); measure(); const observer = new ResizeObserver(measure); observer.observe(viewport); return () => observer.disconnect(); }, []); const widths = ["64%", "78%", "52%", "70%", "60%", "74%"]; return (
{t("workspace.picker.loading")}
); } function WorkspacePickerPath({ path }: { path: string }) { const parts = workspacePathCompletionQuery(path); return ( {parts?.path ?? path} {parts?.query && {parts.query}} ); } export function WorkspaceProjectPicker({ disabled, scope, defaultScope, controls, error, onLoadProjects, onResolveProject, onFavoriteProject, onBrowseDirectories, layoutAnchor, onChange }: { layoutAnchor?: HTMLElement | null; disabled?: boolean; scope: WorkspaceScopePayload | null; defaultScope: WorkspaceScopePayload | null; controls: WorkspacesPayload["controls"] | null; error?: string | null; onResolveProject?: (path: string) => Promise; onLoadProjects?: () => Promise; onFavoriteProject?: (path: string, pinned: boolean) => Promise; onBrowseDirectories?: BrowseWorkspaceDirectories; onChange?: (scope: WorkspaceScopePayload) => void; }) { const { t } = useTranslation(); const [open, setOpen] = useState(false); const [pathDraft, setPathDraft] = useState(""); const [editingPath, setEditingPath] = useState(false); const [showLocations, setShowLocations] = useState(false); const [hoveredLocation, setHoveredLocation] = useState(null); const [history, setHistory] = useState(() => ({ visits: [directoryVisit(scope?.project_path ?? defaultScope?.project_path ?? "")], index: 0, previous: null, revision: 0, })); const currentVisit = history.visits[history.index]; const basePath = currentVisit.path; const filterQuery = currentVisit.filter; const compact = useMediaQuery("(max-width: 639px)"); const [catalog, setCatalog] = useState(null); const [directory, setDirectory] = useState(null); const [loading, setLoading] = useState(false); const [showHidden, setShowHidden] = useState(false); const [ancestorData, setAncestorData] = useState<{ hidden: boolean; listings: WorkspaceDirectoriesPayload[] }>({ hidden: false, listings: [] }); const [revision, setRevision] = useState(0); const [directoryError, setDirectoryError] = useState(null); const [pathError, setPathError] = useState(null); const [pickingFolder, setPickingFolder] = useState(false); const [favoriteBusy, setFavoriteBusy] = useState(false); const [activeIndex, setActiveIndex] = useState(0); const [activeColumn, setActiveColumn] = useState(0); const [highlightActive, setHighlightActive] = useState(false); const columnsRef = useRef(null); const breadcrumbRef = useRef(null); const attachBreadcrumb = useCallback((element: HTMLElement | null) => { breadcrumbRef.current = element; // Dialog portals mount after the parent's layout effect on first open. if (element) window.requestAnimationFrame(() => { if (element.isConnected) element.scrollLeft = element.scrollWidth; }); }, []); const [columnsElement, setColumnsElement] = useState(null); const attachColumns = useCallback((element: HTMLDivElement | null) => { columnsRef.current = element; setColumnsElement(element); }, []); const [visibleColumns, setVisibleColumns] = useState(3); const pickerSession = useRef(0); const completionRequest = useRef(0); const triggerRef = useRef(null); const [keyboardInteraction, setKeyboardInteraction] = useState(false); const openedWithKeyboard = useRef(false); const inputRef = useRef(null); const confirmRef = useRef(null); const optionsId = useId(); const errorId = useId(); const currentProjectScope = selectedProjectScope(scope, defaultScope); const displayedScope = scope ?? defaultScope; const projectLabel = displayedScope ? displayedScope.project_name || projectNameFromPath(displayedScope.project_path) : ""; const visible = !!defaultScope && !!onChange && controls?.can_change_project !== false; const canBrowse = controls?.can_browse_directories === true && !!onBrowseDirectories; const directoryCache = useMemo(() => onBrowseDirectories ? createWorkspaceDirectoryCache(onBrowseDirectories) : null, [onBrowseDirectories]); const previousColumns = useMemo(() => currentVisit.ancestors.map(ancestor => { const listing = directoryCache?.peek(ancestor.path, "", showHidden, true) ?? (ancestorData.hidden === showHidden ? ancestorData.listings.find(listing => sameWorkspacePath(listing.path, ancestor.path)) : undefined); return { ...ancestor, hidden: showHidden, options: listing?.entries.map(entry => ({ ...entry, kind: "directory" as const })) ?? [] }; }), [currentVisit.ancestors, directoryCache, showHidden, ancestorData]); const absoluteDraft = isAbsoluteWorkspacePath(pathDraft); const requestedPath = editingPath && absoluteDraft ? pathDraft.trim() : basePath; const previewingPath = editingPath && !sameWorkspacePath(pathDraft.trim(), basePath); const displayedAncestors = previewingPath ? [] : previousColumns; const currentColumnIndex = displayedAncestors.length; const columnCount = Math.min(visibleColumns, currentColumnIndex + 1); const folderQuery = editingPath ? "" : filterQuery.trim(); useEffect(() => { pickerSession.current += 1; completionRequest.current += 1; if (!open) return; setActiveColumn(0); setHighlightActive(false); const initialPath = scope?.project_path ?? defaultScope?.project_path ?? ""; setPathDraft(canBrowse ? workspaceDirectoryPrefix(initialPath) : currentProjectScope?.project_path ?? ""); setHistory(current => ({ visits: [directoryVisit(initialPath)], index: 0, previous: null, revision: current.revision + 1 })); setEditingPath(false); setShowLocations(false); setHoveredLocation(null); setDirectory(null); setActiveIndex(0); setPathError(null); }, [scope?.project_path, defaultScope?.project_path, open, canBrowse]); useEffect(() => { if (!open || !onLoadProjects) return; let active = true; setCatalog(null); onLoadProjects().then(payload => { if (active) setCatalog(payload); }).catch((err: Error) => { if (active) setPathError(err.message); }); return () => { active = false; }; }, [onLoadProjects, open]); useEffect(() => { if (!open || !canBrowse || !directoryCache) return; if (editingPath && !absoluteDraft) { setDirectory(null); setLoading(false); return; } let active = true; const apply = (result: WorkspaceDirectoriesPayload) => { if (!active) return; setDirectory(result); setLoading(false); }; setDirectoryError(null); const cached = directoryCache.peek(requestedPath, folderQuery, showHidden, true); if (cached) { apply(cached); return; } setLoading(true); setDirectory(null); const typing = !!folderQuery || editingPath && !/[\\/]$/.test(pathDraft); const timer = window.setTimeout(() => { directoryCache.load(requestedPath, folderQuery, showHidden, true).then(apply).catch((err: Error) => { if (active) { setDirectoryError(err.message); setLoading(false); } }); }, typing ? 150 : 0); return () => { active = false; window.clearTimeout(timer); }; }, [open, canBrowse, directoryCache, requestedPath, folderQuery, showHidden, revision, absoluteDraft, pathDraft, editingPath]); useEffect(() => { if (disabled) setOpen(false); }, [disabled]); useEffect(() => { if (!error || !visible || disabled) return; const frame = window.requestAnimationFrame(() => triggerRef.current?.focus()); return () => window.cancelAnimationFrame(frame); }, [disabled, error, visible]); useEffect(() => { if (!open || pickingFolder) return; const frame = window.requestAnimationFrame(() => { if (editingPath || !canBrowse) inputRef.current?.focus(); }); return () => window.cancelAnimationFrame(frame); }, [open, pickingFolder, pathError, editingPath, canBrowse]); const ancestorPaths = JSON.stringify(currentVisit.ancestors.map(column => column.path)); useEffect(() => { if (!open || !canBrowse || !directoryCache) return; const paths: string[] = JSON.parse(ancestorPaths); if (!paths.length) { setAncestorData(current => current.listings.length ? { hidden: showHidden, listings: [] } : current); return; } let active = true; Promise.all(paths.map(path => directoryCache.load(path, "", showHidden, true))).then(results => { if (!active) return; setAncestorData({ hidden: showHidden, listings: results }); }).catch((err: Error) => { if (active) setPathError(err.message); }); return () => { active = false; }; }, [open, canBrowse, directoryCache, ancestorPaths, showHidden]); useLayoutEffect(() => { const viewport = columnsElement; if (!open || !viewport) return; const measure = () => setVisibleColumns(Math.max(1, Math.min(3, Math.floor(viewport.clientWidth / 240)))); measure(); const observer = new ResizeObserver(measure); observer.observe(viewport); return () => observer.disconnect(); }, [open, columnsElement]); useEffect(() => { const viewport = columnsElement; if (!open || !viewport) return; const onWheel = (event: WheelEvent) => { setKeyboardInteraction(false); if (!event.shiftKey || event.ctrlKey || event.metaKey || viewport.scrollWidth <= viewport.clientWidth) return; const delta = event.deltaX || event.deltaY; if (!delta) return; event.preventDefault(); const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? viewport.clientWidth : 1; viewport.scrollLeft = Math.max(0, Math.min(viewport.scrollWidth - viewport.clientWidth, viewport.scrollLeft + delta * unit)); }; viewport.addEventListener("wheel", onWheel, { passive: false }); return () => viewport.removeEventListener("wheel", onWheel); }, [open, columnsElement]); useLayoutEffect(() => { const viewport = columnsRef.current; if (!viewport) return; viewport.scrollLeft = !previewingPath && currentVisit.scrollLeft !== null ? currentVisit.scrollLeft : viewport.clientWidth * Math.max(0, currentColumnIndex + 1 - columnCount) / columnCount; }, [history.revision, currentColumnIndex, columnCount, currentVisit.scrollLeft, previewingPath]); useLayoutEffect(() => { const viewport = columnsRef.current; if (!viewport || !highlightActive) return; const width = viewport.clientWidth / columnCount; const left = activeColumn * width; const right = left + width; if (left < viewport.scrollLeft) viewport.scrollLeft = left; else if (right > viewport.scrollLeft + viewport.clientWidth) viewport.scrollLeft = right - viewport.clientWidth; }, [activeColumn, highlightActive, columnCount]); function changeDraft(value: string, query = "") { setHighlightActive(false); setActiveColumn(sameWorkspacePath(value.trim(), basePath) ? previousColumns.length : 0); completionRequest.current += 1; setPathDraft(value); const absolute = isAbsoluteWorkspacePath(value); const cached = absolute ? directoryCache?.peek(value.trim(), query, showHidden, true) : null; setDirectory(cached ?? null); setLoading(canBrowse && absolute && !cached); setDirectoryError(null); setPathError(null); setActiveIndex(0); } function focusDirectory() { window.requestAnimationFrame(() => columnsRef.current?.querySelector("[data-current-directory]")?.focus()); } function captureVisit(): PickerVisit { // A draft preview is not a committed navigation visit. if (previewingPath) return currentVisit; const viewport = columnsRef.current; const scrollTops = [...currentVisit.scrollTops]; viewport?.querySelectorAll('[data-workspace-column]').forEach(column => { scrollTops[Number(column.dataset.workspaceColumn)] = column.scrollTop; }); return { ...currentVisit, scrollLeft: viewport?.scrollLeft ?? null, scrollTops }; } function visitDirectory(visit: PickerVisit, keepEditing = false, historyIndex?: number) { const departed = captureVisit(); setShowLocations(false); setEditingPath(keepEditing); setHistory(current => { const visits = [...current.visits]; visits[current.index] = departed; const previous = sameWorkspacePath(departed.path, visit.path) ? current.previous : departed; if (historyIndex !== undefined) return { visits, index: historyIndex, previous, revision: current.revision + 1 }; if (sameWorkspacePath(departed.path, visit.path)) { visits[current.index] = visit; return { visits, index: current.index, previous, revision: current.revision + 1 }; } return { visits: [...visits.slice(0, current.index + 1), visit], index: current.index + 1, previous, revision: current.revision + 1 }; }); changeDraft(workspaceDirectoryPrefix(visit.path), visit.filter); setActiveColumn(visit.ancestors.length); setRevision(value => value + 1); if (keepEditing) inputRef.current?.focus(); else focusDirectory(); } function navigate(path: string, columnIndex?: number, keepEditing = false) { const source = columnIndex === undefined ? undefined : columns[columnIndex]; const ancestors = columnIndex === undefined ? [] : columns.slice(0, columnIndex); if (source?.options.length && !sameWorkspacePath(source.path, path)) ancestors.push({ ...source, selectedPath: path }); visitDirectory(directoryVisit(path, ancestors, captureVisit().scrollTops.slice(0, ancestors.length)), keepEditing); } function setFilterQuery(filter: string) { setHistory(current => { const visits = [...current.visits]; const visit = visits[current.index]; visits[current.index] = { ...visit, filter, scrollTops: visit.scrollTops.slice(0, visit.ancestors.length) }; return { ...current, visits }; }); } const applyProjectPath = useCallback((path: string, name?: string) => { const base = scope ?? defaultScope; const trimmed = path.trim(); if (!base || !onChange) return; if (!trimmed || !isAbsoluteWorkspacePath(trimmed)) { setPathError(t("workspace.dialog.absolutePathRequired")); return; } onChange({ ...base, project_path: trimmed, project_name: name || projectNameFromPath(trimmed) }); setPathError(null); setOpen(false); }, [defaultScope, onChange, scope, t]); const chooseProject = useCallback(async (path: string, name?: string) => { const session = pickerSession.current; if (controls?.can_resolve_project !== true || !onResolveProject) { applyProjectPath(path, name); return; } setPickingFolder(true); setPathError(null); try { const project = await onResolveProject(path); if (session === pickerSession.current) applyProjectPath(project.path, project.name); } catch (err) { if (session === pickerSession.current) setPathError((err as Error).message); } finally { setPickingFolder(false); } }, [applyProjectPath, controls?.can_resolve_project, onResolveProject]); const favorites = catalog?.favorite_projects ?? []; const canFavorite = catalog?.controls.can_manage_favorites === true && !!onFavoriteProject; const isFavorite = (path: string) => favorites.some(item => sameWorkspacePath(item.path, path)); function favoriteButton(path: string) { return canFavorite ? { void toggleFavorite(path); inputRef.current?.focus(); }} /> : null; } const toggleFavorite = async (path: string) => { if (!onFavoriteProject || favoriteBusy) return; const session = pickerSession.current; setFavoriteBusy(true); setPathError(null); try { const favorites = await onFavoriteProject(path, !isFavorite(path)); if (session === pickerSession.current) setCatalog(current => current ? { ...current, favorite_projects: favorites } : current); } catch (err) { if (session === pickerSession.current) setPathError((err as Error).message); } finally { setFavoriteBusy(false); } }; const recentProjects = [ ...(catalog?.recent_projects ?? []), ...(defaultScope ? [{ name: projectNameFromPath(defaultScope.project_path), path: defaultScope.project_path }] : []), ...(currentProjectScope ? [{ name: projectLabel, path: currentProjectScope.project_path }] : []), ].filter((project, index, all) => all.findIndex(item => sameWorkspacePath(item.path, project.path)) === index && !isFavorite(project.path)); const options = useMemo(() => { if (directory && !loading) return directory.entries.map(entry => ({ ...entry, kind: "directory" })); return !canBrowse && absoluteDraft ? [{ name: projectNameFromPath(pathDraft.trim()), path: pathDraft.trim(), kind: "manual" }] : []; }, [directory, loading, canBrowse, absoluteDraft, pathDraft]); function openShortcut(project: ProjectDirectory) { if (!canBrowse) { void chooseProject(project.path, project.name); return; } navigate(project.path); } const columns: PickerColumn[] = [...displayedAncestors, { path: directory?.path ?? requestedPath, parent: directory?.parent ?? null, options, selectedPath: null, hidden: showHidden }]; const activeOptions = columns[activeColumn]?.options ?? options; const activeOption = Math.min(activeIndex, Math.max(activeOptions.length - 1, 0)); const browsedSelectionPath = directoryError || directory?.partial ? null : directory?.path ?? basePath; const resolvedDraftPath = !loading && directory && !directory.partial ? directory.path : null; const selectionPath = canBrowse ? editingPath ? resolvedDraftPath : browsedSelectionPath : (pathDraft.trim() ? absoluteDraft ? pathDraft.trim() : null : scope?.project_path ?? defaultScope?.project_path); const displayedError = pathError ?? error ?? directoryError; const currentPath = editingPath ? basePath : directory?.path ?? basePath; let savedSelectionJoin: "top" | "bottom" | null = null; for (const projects of [favorites, recentProjects]) { const selectedIndex = projects.findIndex(project => sameWorkspacePath(project.path, currentPath)); if (selectedIndex < 0 || !hoveredLocation) continue; if (selectedIndex > 0 && sameWorkspacePath(projects[selectedIndex - 1].path, hoveredLocation)) savedSelectionJoin = "top"; else if (selectedIndex + 1 < projects.length && sameWorkspacePath(projects[selectedIndex + 1].path, hoveredLocation)) savedSelectionJoin = "bottom"; } const breadcrumbs = workspaceBreadcrumbs(currentPath); const hostName = catalog?.host?.name ?? directory?.host; useLayoutEffect(() => { if (breadcrumbRef.current) breadcrumbRef.current.scrollLeft = breadcrumbRef.current.scrollWidth; }, [currentPath, editingPath, open]); function editPath() { const visit = captureVisit(); setHistory(current => { const visits = [...current.visits]; visits[current.index] = visit; return { ...current, visits }; }); setEditingPath(true); changeDraft(workspaceDirectoryPrefix(currentPath)); window.requestAnimationFrame(() => inputRef.current?.select()); } function cancelPathEditing(focusColumns = true) { setEditingPath(false); changeDraft(workspaceDirectoryPrefix(basePath), filterQuery.trim()); if (focusColumns) focusDirectory(); } async function completePath(keepEditing = true) { if (!absoluteDraft) { setPathError(t("workspace.dialog.absolutePathRequired")); return; } const request = workspacePathCompletionQuery(pathDraft) ?? { path: basePath, query: "" }; if (!directoryCache || !canBrowse) return; const id = ++completionRequest.current; const session = pickerSession.current; try { const result = await directoryCache.load(requestedPath, folderQuery, showHidden || request.query.startsWith("."), true); if (id !== completionRequest.current || session !== pickerSession.current) return; if (!result.partial) { navigate(result.path, undefined, keepEditing); return; } const prefix = request.query.toLocaleLowerCase(); const first = result.entries.find(entry => entry.name.toLocaleLowerCase().startsWith(prefix)); if (first) navigate(first.path, undefined, keepEditing); else setPathError(t("workspace.picker.pathNotFound")); } catch (err) { if (id === completionRequest.current && session === pickerSession.current) setPathError((err as Error).message); } } function activate(option: PickerOption, columnIndex = activeColumn) { if (pickingFolder) return; if (canBrowse && option.kind !== "manual") navigate(option.path, columnIndex); else void chooseProject(option.path, option.kind === "manual" ? undefined : option.name); } function moveHistory(offset: number) { const index = history.index + offset; if (index >= 0 && index < history.visits.length) visitDirectory(history.visits[index], false, index); } const filterToolbar = canBrowse && !(compact && editingPath) &&
{compact && }
{ setFilterQuery(event.target.value); setActiveIndex(0); setActiveColumn(currentColumnIndex); setHighlightActive(false); }} className={cn("h-11 rounded-[var(--picker-field-radius)] border-transparent pl-8 text-[16px] leading-5 shadow-none sm:h-9 sm:text-[13px]", compact ? "bg-muted/60" : "bg-background/80")} />
; if (!visible || !defaultScope || !onChange) return null; return (
{ event.preventDefault(); if (canBrowse) focusDirectory(); else inputRef.current?.focus(); }} onPointerDownCapture={() => setKeyboardInteraction(false)} onKeyDownCapture={event => { if (!["Alt", "Control", "Meta", "Shift"].includes(event.key)) setKeyboardInteraction(true); if (!canBrowse || pickingFolder || event.nativeEvent.isComposing) return; if ((event.metaKey || event.ctrlKey) && event.shiftKey && event.key.toLowerCase() === "g") { event.preventDefault(); editPath(); } }} onEscapeKeyDown={event => { if (editingPath) { event.preventDefault(); cancelPathEditing(); } }} onCloseAutoFocus={event => { if (!openedWithKeyboard.current) event.preventDefault(); }}> {t("workspace.picker.title")} {t("workspace.picker.description")}
{canBrowse &&
moveHistory(-1)}> {!compact && = history.visits.length - 1} onClick={() => moveHistory(1)}>} history.previous && visitDirectory(history.previous)}>
}
{editingPath || !canBrowse ? changeDraft(event.target.value)} onBlur={event => { if (canBrowse && !keyboardInteraction && event.relatedTarget !== confirmRef.current) cancelPathEditing(false); }} placeholder={t("workspace.dialog.manual")} aria-label={t("workspace.dialog.manual")} aria-invalid={displayedError ? true : undefined} aria-describedby={displayedError ? errorId : undefined} className="h-9 min-w-0 flex-1 rounded-[var(--picker-field-radius)] border-transparent shadow-none focus-visible:ring-0 text-[16px] leading-5 sm:text-[13px]" onKeyDown={event => { if (event.nativeEvent.isComposing) return; if (event.key === "Tab" && !event.shiftKey && canBrowse && absoluteDraft && !/[\\/]$/.test(pathDraft)) { event.preventDefault(); void completePath(); } else if (event.key === "Enter") { event.preventDefault(); if (!canBrowse) void chooseProject(pathDraft); else if ((event.ctrlKey || event.metaKey) && selectionPath) void chooseProject(selectionPath); else void completePath(false); } }} /> : }
{!compact && filterToolbar}
{compact && filterToolbar}
{(!compact || showLocations || !canBrowse) && }
{columns.map((column, columnIndex) => (!compact || columnIndex === currentColumnIndex) && { if (event.target === event.currentTarget) { setActiveColumn(columnIndex); setActiveIndex(0); } }} onKeyDown={event => { if (event.target !== event.currentTarget || event.altKey || event.metaKey || event.ctrlKey || pickingFolder) return; const count = column.options.length; if (count && (event.key === "Home" || event.key === "End")) { event.preventDefault(); setHighlightActive(true); setActiveColumn(columnIndex); setActiveIndex(event.key === "Home" ? 0 : count - 1); } else if (count && event.key === "Enter") { event.preventDefault(); activate(column.options[Math.min(activeIndex, count - 1)], columnIndex); } }} renderOption={(option, index) =>
{favoriteButton(option.path)}
}> {columnIndex === currentColumnIndex && loading && } {columnIndex === currentColumnIndex && canBrowse && !loading && directory && !column.options.length && !displayedError &&

{t(folderQuery || directory.partial ? "workspace.picker.noMatches" : "workspace.picker.empty")}

} {columnIndex === currentColumnIndex && directory?.truncated &&

{t("workspace.picker.truncated")}

} {columnIndex === currentColumnIndex && displayedError &&
{directoryError && }
}
)}
{canBrowse && }
{error && !open && {error}}
); } export function WorkspaceAccessMenu({ scope, disabled, onChange, }: { scope: WorkspaceScopePayload; disabled?: boolean; onChange?: (scope: WorkspaceScopePayload) => void; }) { const { t } = useTranslation(); const coarsePointer = useMediaQuery("(pointer: coarse)"); const [open, setOpen] = useState(false); const restoreTriggerFocus = useRef(true); const descriptionId = useId(); const isFull = scope.access_mode === "full"; const label = t(isFull ? "thread.composer.workspace.full" : "thread.composer.workspace.default"); const description = t(isFull ? "thread.composer.workspace.fullDescription" : "thread.composer.workspace.defaultDescription"); const accessAriaLabel = `${t("thread.composer.workspace.accessAria")}: ${label}`; const AccessIcon = isFull ? FullAccessIcon : RestrictedAccessIcon; useEffect(() => { if (disabled || !onChange) setOpen(false); }, [disabled, onChange]); return ( { restoreTriggerFocus.current = false; }} onKeyDownCapture={() => { restoreTriggerFocus.current = true; }} onPointerDownOutside={() => { restoreTriggerFocus.current = false; }} onCloseAutoFocus={event => { if (!restoreTriggerFocus.current) event.preventDefault(); }} className="w-max min-w-[13rem] max-w-[calc(100vw-2rem)]"> {(["restricted", "full"] as const).map(mode => { const full = mode === "full"; const optionLabel = t(full ? "thread.composer.workspace.full" : "thread.composer.workspace.default"); const OptionIcon = full ? FullAccessIcon : RestrictedAccessIcon; return { if (!disabled && scope.access_mode !== mode) onChange?.(scopeWithAccessMode(scope, mode)); }}> {optionLabel} {scope.access_mode === mode && } ; })} ); }