Skip to content

armgit / ui

Public Imported from GitHub
0
TypeScript

Refresh file system source code snippet

Andrew Luo2d5da23fd4d5
diff --git a/apps/v4/components/file-system-source-code.tsx b/apps/v4/components/file-system-source-code.tsx
index 259d6ce..8f5b9a4 100644
--- a/apps/v4/components/file-system-source-code.tsx
+++ b/apps/v4/components/file-system-source-code.tsx
@@ -5,7 +5,7 @@ import { DocsSourceCodeBlock } from "@/components/docs-code-block"
// Generated from components/ui/file-system.tsx — keep in sync when the
// component changes.
export const fileSystemSourceCode =
- '"use client"\n\nimport * as React from "react"\nimport {\n ArrowLeft01Icon,\n ArrowRight01Icon,\n Cancel01Icon,\n File01Icon,\n GalleryThumbnailsIcon,\n GridViewIcon,\n LayoutThreeColumnIcon,\n LeftToRightListBulletIcon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { prepareFileTreeInput } from "@pierre/trees"\nimport { FileTree as PierreFileTree, useFileTree } from "@pierre/trees/react"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogTitle,\n} from "@/components/ui/dialog"\nimport { DocxViewerPreview } from "@/components/ui/docx-viewer"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { PDFViewer } from "@/components/ui/pdf-viewer"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"\nimport { XlsxViewerPreview } from "@/components/ui/xlsx-viewer"\n\nexport type FileSystemView = "icons" | "list" | "columns" | "gallery"\n\nexport type FileSystemFolderItem = {\n kind: "folder"\n /** Folder prefix, e.g. `"invoices/2026/"`. A trailing slash is added when missing. */\n path: string\n name?: string\n parentPath?: string\n /** Set when children exist but are not in `items` yet; enables `loadChildren`. */\n hasChildren?: boolean\n createdAt?: string\n updatedAt?: string\n}\n\nexport type FileSystemFileItem = {\n kind: "file"\n /** Display/canonical path, e.g. `"invoices/2026/jan.pdf"`. */\n path: string\n /** Original object key (S3/R2). Defaults to `path`. */\n key?: string\n name?: string\n parentPath?: string\n contentType?: string\n size?: number\n createdAt?: string\n updatedAt?: string\n etag?: string\n /** Optional if already public/presigned. Otherwise resolved via `getFileUrl`. */\n url?: string\n /** Externally generated thumbnail. The component never renders documents itself. */\n previewImageUrl?: string | null\n /**\n * Externally generated page thumbnails (first entry is the cover). When a\n * file has more than one page, large thumbnails show a hover pager.\n */\n previewImageUrls?: string[] | null\n /**\n * Total page count when it exceeds `previewImageUrls.length`; the pager\n * loads the remaining pages on demand via `loadPreviewImageUrl`.\n */\n previewPageCount?: number\n /** Thumbnail aspect ratio (width / height). Defaults to a portrait page. */\n previewAspectRatio?: number\n metadata?: Record<string, string>\n}\n\nexport type FileSystemItem = FileSystemFolderItem | FileSystemFileItem\n\nexport type FileSystemLoadChildrenArgs = {\n path: string\n cursor: string | null\n}\n\nexport type FileSystemLoadChildrenResult = {\n items: FileSystemItem[]\n nextCursor?: string | null\n}\n\nexport type FileSystemProps = {\n /** Flat manifest. Folders are optional; missing prefixes are inferred from file paths. */\n items: FileSystemItem[]\n className?: string\n /** Label for the root folder. */\n title?: string\n defaultView?: FileSystemView\n view?: FileSystemView\n onViewChange?: (view: FileSystemView) => void\n /** Folder prefix to open initially, e.g. `"invoices/"`. */\n defaultPath?: string\n onSelectionChange?: (item: FileSystemItem | null) => void\n /**\n * Called on file open (double-click), replacing the built-in behavior. By\n * default PDF, DOCX, XLSX, and image files open in a viewer dialog and\n * other files open their resolved URL in a new tab.\n */\n onFileOpen?: (file: FileSystemFileItem, url: string | null) => void\n /** Resolve a URL (e.g. presigned) for a file without one. */\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n /** Lazily fetch children for folders with `hasChildren` and no loaded entries. */\n loadChildren?: (\n args: FileSystemLoadChildrenArgs\n ) => Promise<FileSystemLoadChildrenResult>\n /** Custom preview node for files without `previewImageUrl`. */\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n /**\n * Lazily render a page thumbnail beyond the eagerly provided\n * `previewImageUrls` (the pager calls this as pages come into view).\n */\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n}\n\ntype FolderEntry = FileSystemFolderItem & {\n name: string\n parentPath: string\n}\n\ntype FileEntry = FileSystemFileItem & {\n key: string\n name: string\n parentPath: string\n}\n\ntype FileSystemEntry = FolderEntry | FileEntry\n\ntype FileSystemIndex = {\n children: Map<string, FileSystemEntry[]>\n files: Map<string, FileEntry>\n folders: Map<string, FolderEntry>\n}\n\nfunction normalizeFolderPath(path: string) {\n if (!path || path === "/") return ""\n return path.endsWith("/") ? path : `${path}/`\n}\n\nfunction pathName(path: string) {\n const trimmed = path.endsWith("/") ? path.slice(0, -1) : path\n const separatorIndex = trimmed.lastIndexOf("/")\n return separatorIndex === -1 ? trimmed : trimmed.slice(separatorIndex + 1)\n}\n\nfunction pathParent(path: string) {\n const trimmed = path.endsWith("/") ? path.slice(0, -1) : path\n const separatorIndex = trimmed.lastIndexOf("/")\n return separatorIndex === -1 ? "" : trimmed.slice(0, separatorIndex + 1)\n}\n\nfunction fileExtension(name: string) {\n const dotIndex = name.lastIndexOf(".")\n return dotIndex === -1 ? "" : name.slice(dotIndex + 1).toLowerCase()\n}\n\nconst FILE_KIND_LABELS: Record<string, string> = {\n csv: "CSV Document",\n doc: "Word Document",\n docx: "Word Document",\n gif: "GIF Image",\n jpeg: "JPEG Image",\n jpg: "JPEG Image",\n md: "Markdown Document",\n pdf: "PDF Document",\n png: "PNG Image",\n ppt: "PowerPoint Presentation",\n pptx: "PowerPoint Presentation",\n svg: "SVG Image",\n tsv: "TSV Document",\n txt: "Plain Text",\n webp: "WebP Image",\n xls: "Excel Workbook",\n xlsx: "Excel Workbook",\n zip: "ZIP Archive",\n}\n\nfunction fileKindLabel(file: FileEntry) {\n const byExtension = FILE_KIND_LABELS[fileExtension(file.name)]\n\n if (byExtension) return byExtension\n if (file.contentType?.startsWith("image/")) return "Image"\n\n return file.contentType ?? "Document"\n}\n\nexport type FileSystemViewerKind = "docx" | "image" | "pdf" | "xlsx"\n\nfunction viewerKindForFile(\n file: FileSystemFileItem\n): FileSystemViewerKind | null {\n if (file.contentType?.startsWith("image/")) return "image"\n if (file.contentType === "application/pdf") return "pdf"\n\n const name = (file.name ?? file.path).toLowerCase()\n\n if (name.endsWith(".pdf")) return "pdf"\n if (name.endsWith(".docx")) return "docx"\n if (name.endsWith(".xlsx")) return "xlsx"\n if (/\\.(avif|gif|jpe?g|png|svg|webp)$/.test(name)) return "image"\n\n return null\n}\n\n// PDF and DOCX pages want height; spreadsheets want width; images get a\n// roomy but contained frame.\nconst VIEWER_DIALOG_CLASSNAMES: Record<FileSystemViewerKind, string> = {\n docx: "h-[88vh] w-[min(96vw,68rem)] max-w-none",\n image: "max-h-[88vh] w-fit max-w-[min(96vw,64rem)]",\n pdf: "h-[88vh] w-[min(96vw,68rem)] max-w-none",\n xlsx: "h-[85vh] w-[min(96vw,100rem)] max-w-none",\n}\n\nfunction formatByteSize(size: number | undefined) {\n if (size === undefined) return null\n if (size < 1000) return `${size} bytes`\n\n const units = ["KB", "MB", "GB", "TB"]\n let value = size\n\n for (const unit of units) {\n value /= 1000\n if (value < 1000 || unit === "TB") {\n return `${value >= 100 ? Math.round(value) : value.toFixed(value >= 10 ? 1 : 2).replace(/\\.?0+$/, "")} ${unit}`\n }\n }\n\n return null\n}\n\nfunction formatTimestamp(value: string | undefined) {\n if (!value) return null\n\n const date = new Date(value)\n\n if (Number.isNaN(date.getTime())) return null\n\n const day = date.toLocaleDateString("en-US", {\n day: "numeric",\n month: "short",\n year: "numeric",\n })\n const time = date.toLocaleTimeString("en-US", {\n hour: "numeric",\n minute: "2-digit",\n })\n\n return `${day} at ${time}`\n}\n\nfunction buildFileSystemIndex(items: FileSystemItem[]): FileSystemIndex {\n const folders = new Map<string, FolderEntry>()\n const files = new Map<string, FileEntry>()\n\n const ensureFolderChain = (folderPath: string) => {\n let path = normalizeFolderPath(folderPath)\n\n while (path && !folders.has(path)) {\n folders.set(path, {\n kind: "folder",\n name: pathName(path),\n parentPath: pathParent(path),\n path,\n })\n path = pathParent(path)\n }\n }\n\n for (const item of items) {\n if (item.kind === "folder") {\n const path = normalizeFolderPath(item.path)\n\n if (!path) continue\n\n folders.set(path, {\n ...item,\n name: item.name ?? pathName(path),\n parentPath: normalizeFolderPath(item.parentPath ?? pathParent(path)),\n path,\n })\n ensureFolderChain(pathParent(path))\n } else {\n if (!item.path) continue\n\n files.set(item.path, {\n ...item,\n key: item.key ?? item.path,\n name: item.name ?? pathName(item.path),\n parentPath: normalizeFolderPath(\n item.parentPath ?? pathParent(item.path)\n ),\n })\n ensureFolderChain(pathParent(item.path))\n }\n }\n\n const children = new Map<string, FileSystemEntry[]>()\n const pushChild = (entry: FileSystemEntry) => {\n const siblings = children.get(entry.parentPath)\n\n if (siblings) {\n siblings.push(entry)\n } else {\n children.set(entry.parentPath, [entry])\n }\n }\n\n for (const folder of folders.values()) pushChild(folder)\n for (const file of files.values()) pushChild(file)\n for (const siblings of children.values()) {\n siblings.sort((left, right) =>\n left.name.localeCompare(right.name, undefined, {\n numeric: true,\n sensitivity: "base",\n })\n )\n }\n\n return { children, files, folders }\n}\n\nfunction folderHasChildren(index: FileSystemIndex, folder: FolderEntry) {\n return (\n (index.children.get(folder.path)?.length ?? 0) > 0 ||\n folder.hasChildren === true\n )\n}\n\n// A single SVG source so the same glyph renders as a React element, inside the\n// @pierre/trees shadow DOM (via CSS url()), and stays pixel-identical in both.\nconst FOLDER_GLYPH_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 50" width="64" height="50"><defs><linearGradient id="fs-folder-back" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#3dabf5"/><stop offset="1" stop-color="#1d84dd"/></linearGradient><linearGradient id="fs-folder-front" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#7accfb"/><stop offset="1" stop-color="#37a0ef"/></linearGradient></defs><path d="M5 10c0-3.31 2.69-6 6-6h10.9c1.6 0 3.13.7 4.18 1.9l1.5 1.73a3.5 3.5 0 0 0 2.64 1.22H54c2.76 0 5 2.24 5 5V40c0 3.87-3.13 7-7 7H12c-3.87 0-7-3.13-7-7V10Z" fill="url(#fs-folder-back)"/><path d="M5 15.5h54V40c0 3.87-3.13 7-7 7H12c-3.87 0-7-3.13-7-7V15.5Z" fill="url(#fs-folder-front)"/></svg>`\n\nconst FOLDER_GLYPH_DATA_URL = `data:image/svg+xml,${encodeURIComponent(FOLDER_GLYPH_SVG)}`\n\nfunction FileSystemFolderGlyph({ className }: { className?: string }) {\n return (\n <img\n src={FOLDER_GLYPH_DATA_URL}\n alt=""\n aria-hidden="true"\n draggable={false}\n className={className}\n />\n )\n}\n\nfunction escapeXmlAttribute(value: string) {\n return value\n .replaceAll("&", "&amp;")\n .replaceAll("<", "&lt;")\n .replaceAll(">", "&gt;")\n .replaceAll(\'"\', "&quot;")\n}\n\nfunction FileGenericPreview({ file }: { file: FileEntry }) {\n const extension = fileExtension(file.name)\n\n return (\n <div className="flex size-full flex-col items-center justify-center gap-1.5 bg-white text-neutral-400 dark:bg-neutral-100">\n <HugeiconsIcon icon={File01Icon} className="size-1/3 min-h-4 min-w-4" />\n {extension ? (\n <span className="text-[min(0.625rem,18cqw)] font-semibold tracking-wide uppercase">\n {extension}\n </span>\n ) : null}\n </div>\n )\n}\n\nfunction filePreviewUrls(file: FileSystemFileItem) {\n if (file.previewImageUrls?.length) return file.previewImageUrls\n return file.previewImageUrl ? [file.previewImageUrl] : []\n}\n\n// djb2 — cheap stable hash for remount keys derived from path lists.\nfunction hashString(value: string) {\n let hash = 5381\n\n for (let index = 0; index < value.length; index += 1) {\n hash = ((hash << 5) + hash + value.charCodeAt(index)) | 0\n }\n return hash\n}\n\nfunction FileVisual({\n file,\n className,\n loadPreviewImageUrl,\n pageable = false,\n previewAspectRatio,\n previewClassName,\n renderFilePreview,\n}: {\n file: FileEntry\n className?: string\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n /** Show a hover pager over multi-page thumbnails. */\n pageable?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n}) {\n const previewUrls = filePreviewUrls(file)\n const canLoadLazily = pageable && Boolean(loadPreviewImageUrl)\n const totalPages = Math.max(\n previewUrls.length,\n canLoadLazily ? (file.previewPageCount ?? 0) : 0\n )\n const [pageIndex, setPageIndex] = React.useState(0)\n const [lazyPageUrls, setLazyPageUrls] = React.useState<\n Record<number, string>\n >({})\n const clampedPageIndex = Math.min(pageIndex, Math.max(totalPages - 1, 0))\n const previewUrl =\n previewUrls[clampedPageIndex] ?? lazyPageUrls[clampedPageIndex] ?? null\n const resolvedAspectRatio = file.previewAspectRatio ?? previewAspectRatio\n const isLazyPagePending =\n canLoadLazily && !previewUrl && clampedPageIndex < totalPages\n\n const fileRef = React.useRef(file)\n\n React.useEffect(() => {\n fileRef.current = file\n })\n\n React.useEffect(() => {\n setPageIndex(0)\n setLazyPageUrls({})\n }, [file.path])\n\n // Keyed by path (not object identity) so manifest churn doesn\'t re-request\n // the page already being loaded.\n React.useEffect(() => {\n if (!isLazyPagePending || !loadPreviewImageUrl) return\n\n let isCurrent = true\n\n void loadPreviewImageUrl(fileRef.current, clampedPageIndex)\n .then((url) => {\n if (isCurrent && url) {\n setLazyPageUrls((previous) => ({\n ...previous,\n [clampedPageIndex]: url,\n }))\n }\n })\n .catch(() => {})\n\n return () => {\n isCurrent = false\n }\n }, [clampedPageIndex, file.path, isLazyPagePending, loadPreviewImageUrl])\n\n const customPreview =\n !previewUrl && !isLazyPagePending ? renderFilePreview?.(file) : null\n const showPager = pageable && totalPages > 1\n const thumbnail = (\n <FileThumbnail\n file={{ name: file.name, type: file.contentType ?? "" }}\n className={cn("@container", !showPager && className)}\n previewAspectRatio={resolvedAspectRatio}\n previewClassName={cn("bg-white dark:bg-neutral-100", previewClassName)}\n previewImageUrl={previewUrl ?? undefined}\n isLoading={isLazyPagePending}\n previewContent={\n previewUrl || isLazyPagePending\n ? undefined\n : (customPreview ?? <FileGenericPreview file={file} />)\n }\n />\n )\n\n if (!showPager) return thumbnail\n\n return (\n <div className={cn("group/pager relative", className)}>\n {thumbnail}\n <div className="absolute inset-x-0 bottom-1.5 flex items-center justify-center gap-1 opacity-0 transition-opacity group-focus-within/pager:opacity-100 group-hover/pager:opacity-100">\n <button\n type="button"\n aria-label="Previous page"\n disabled={clampedPageIndex === 0}\n onClick={(event) => {\n event.stopPropagation()\n setPageIndex((previous) => Math.max(0, previous - 1))\n }}\n onDoubleClick={(event) => event.stopPropagation()}\n className="flex size-6 items-center justify-center rounded-md bg-background/80 text-foreground shadow-xs backdrop-blur-sm transition-colors outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-3.5" />\n </button>\n <span className="rounded-md bg-background/80 px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground tabular-nums shadow-xs backdrop-blur-sm">\n {clampedPageIndex + 1}/{totalPages}\n </span>\n <button\n type="button"\n aria-label="Next page"\n disabled={clampedPageIndex >= totalPages - 1}\n onClick={(event) => {\n event.stopPropagation()\n setPageIndex((previous) => Math.min(totalPages - 1, previous + 1))\n }}\n onDoubleClick={(event) => event.stopPropagation()}\n className="flex size-6 items-center justify-center rounded-md bg-background/80 text-foreground shadow-xs backdrop-blur-sm transition-colors outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-3.5" />\n </button>\n </div>\n </div>\n )\n}\n\nconst VIEW_OPTIONS: Array<{\n icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]\n label: string\n value: FileSystemView\n}> = [\n { icon: GridViewIcon, label: "Grid", value: "icons" },\n { icon: LeftToRightListBulletIcon, label: "List", value: "list" },\n { icon: LayoutThreeColumnIcon, label: "Columns", value: "columns" },\n { icon: GalleryThumbnailsIcon, label: "Gallery", value: "gallery" },\n]\n\nexport function FileSystem({\n items,\n className,\n title = "Files",\n defaultView = "icons",\n view: viewProp,\n onViewChange,\n defaultPath = "",\n onSelectionChange,\n onFileOpen,\n getFileUrl,\n loadChildren,\n loadPreviewImageUrl,\n renderFilePreview,\n}: FileSystemProps) {\n const [internalView, setInternalView] = React.useState(defaultView)\n const view = viewProp ?? internalView\n const setView = React.useCallback(\n (nextView: FileSystemView) => {\n setInternalView(nextView)\n onViewChange?.(nextView)\n },\n [onViewChange]\n )\n\n const [loadedItems, setLoadedItems] = React.useState<FileSystemItem[]>([])\n const allItems = React.useMemo(\n () => (loadedItems.length ? [...items, ...loadedItems] : items),\n [items, loadedItems]\n )\n const index = React.useMemo(() => buildFileSystemIndex(allItems), [allItems])\n\n const [history, setHistory] = React.useState(() => ({\n index: 0,\n stack: [normalizeFolderPath(defaultPath)],\n }))\n const currentPath = history.stack[history.index] ?? ""\n const canGoBack = history.index > 0\n const canGoForward = history.index < history.stack.length - 1\n\n const [selectedPath, setSelectedPath] = React.useState<string | null>(null)\n const selectedEntry = React.useMemo(() => {\n if (selectedPath === null) return null\n\n return (\n index.files.get(selectedPath) ?? index.folders.get(selectedPath) ?? null\n )\n }, [index, selectedPath])\n\n const selectEntry = React.useCallback(\n (entry: FileSystemEntry | null) => {\n setSelectedPath(entry?.path ?? null)\n onSelectionChange?.(entry)\n },\n [onSelectionChange]\n )\n\n // Below this width the tabs view switcher no longer fits in the toolbar.\n const rootRef = React.useRef<HTMLDivElement | null>(null)\n const [isCompact, setIsCompact] = React.useState(false)\n\n React.useEffect(() => {\n const root = rootRef.current\n\n if (!root || typeof ResizeObserver === "undefined") return\n\n const observer = new ResizeObserver((observerEntries) => {\n const width = observerEntries[0]?.contentRect.width\n\n if (width !== undefined) setIsCompact(width < 480)\n })\n\n observer.observe(root)\n return () => observer.disconnect()\n }, [])\n\n const requestedFoldersRef = React.useRef(new Set<string>())\n const [loadingFolders, setLoadingFolders] = React.useState<Set<string>>(\n () => new Set()\n )\n const ensureChildren = React.useCallback(\n (folderPath: string) => {\n if (!loadChildren) return\n\n const folder = index.folders.get(folderPath)\n\n if (!folder?.hasChildren) return\n if (index.children.get(folderPath)?.length) return\n if (requestedFoldersRef.current.has(folderPath)) return\n\n requestedFoldersRef.current.add(folderPath)\n setLoadingFolders((previous) => new Set(previous).add(folderPath))\n\n void (async () => {\n try {\n let cursor: string | null = null\n\n do {\n const result = await loadChildren({ cursor, path: folderPath })\n\n if (result.items.length) {\n setLoadedItems((previous) => [...previous, ...result.items])\n }\n cursor = result.nextCursor ?? null\n } while (cursor)\n } catch {\n requestedFoldersRef.current.delete(folderPath)\n } finally {\n setLoadingFolders((previous) => {\n const next = new Set(previous)\n\n next.delete(folderPath)\n return next\n })\n }\n })()\n },\n [index, loadChildren]\n )\n\n const navigateTo = React.useCallback(\n (folderPath: string) => {\n const path = normalizeFolderPath(folderPath)\n\n setHistory((previous) => {\n if (previous.stack[previous.index] === path) return previous\n\n const stack = [...previous.stack.slice(0, previous.index + 1), path]\n\n return { index: stack.length - 1, stack }\n })\n selectEntry(null)\n ensureChildren(path)\n },\n [ensureChildren, selectEntry]\n )\n\n React.useEffect(() => {\n ensureChildren(currentPath)\n }, [currentPath, ensureChildren])\n\n // Navigation unmounts the focused row, dropping focus to <body> and killing\n // the ⌘ shortcuts; reclaim focus onto the component root when that happens.\n const hasNavigatedRef = React.useRef(false)\n\n React.useEffect(() => {\n if (!hasNavigatedRef.current) {\n hasNavigatedRef.current = true\n return\n }\n\n const root = rootRef.current\n\n if (root && document.activeElement === document.body) {\n root.focus()\n }\n }, [currentPath])\n\n const [openedFile, setOpenedFile] = React.useState<{\n file: FileEntry\n kind: FileSystemViewerKind\n url: string\n } | null>(null)\n\n const openFile = React.useCallback(\n (file: FileEntry) => {\n void (async () => {\n let url = file.url ?? null\n\n if (!url && getFileUrl) {\n try {\n url = await getFileUrl(file)\n } catch {\n url = null\n }\n }\n if (onFileOpen) {\n onFileOpen(file, url)\n return\n }\n\n const kind = viewerKindForFile(file)\n\n if (kind && url) {\n setOpenedFile({ file, kind, url })\n } else if (url && typeof window !== "undefined") {\n window.open(url, "_blank", "noopener,noreferrer")\n }\n })()\n },\n [getFileUrl, onFileOpen]\n )\n\n const openEntry = React.useCallback(\n (entry: FileSystemEntry) => {\n if (entry.kind === "folder") {\n navigateTo(entry.path)\n } else {\n openFile(entry)\n }\n },\n [navigateTo, openFile]\n )\n\n // Selecting a lazy folder (columns view, keyboard nav) prefetches children.\n const selectAndPrefetchEntry = React.useCallback(\n (entry: FileSystemEntry | null) => {\n selectEntry(entry)\n if (entry?.kind === "folder") ensureChildren(entry.path)\n },\n [ensureChildren, selectEntry]\n )\n\n const goBack = React.useCallback(() => {\n setHistory((previous) => ({\n ...previous,\n index: Math.max(0, previous.index - 1),\n }))\n selectEntry(null)\n }, [selectEntry])\n\n const goForward = React.useCallback(() => {\n setHistory((previous) => ({\n ...previous,\n index: Math.min(previous.stack.length - 1, previous.index + 1),\n }))\n selectEntry(null)\n }, [selectEntry])\n\n const currentEntries = index.children.get(currentPath) ?? []\n const currentFolderName =\n currentPath === "" ? title : pathName(currentPath) || title\n const isLoadingCurrentFolder = loadingFolders.has(currentPath)\n\n const viewProps: FileSystemViewProps = {\n currentPath,\n entries: currentEntries,\n getFileUrl,\n index,\n loadPreviewImageUrl,\n loadingFolders,\n onOpen: openEntry,\n onSelect: selectAndPrefetchEntry,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n }\n\n const openedFileName = openedFile\n ? (openedFile.file.name ?? openedFile.file.path)\n : ""\n const activeViewOption = VIEW_OPTIONS.find((option) => option.value === view)\n const viewerCloseToolbarAction = (\n <DialogClose\n aria-label="Close preview"\n render={<Button type="button" variant="ghost" size="icon-sm" />}\n >\n <HugeiconsIcon icon={Cancel01Icon} className="size-4" />\n </DialogClose>\n )\n\n return (\n <div\n ref={rootRef}\n tabIndex={-1}\n className={cn(\n "flex h-[480px] min-h-0 flex-col overflow-hidden rounded-xl border bg-background text-foreground outline-none",\n className\n )}\n >\n <div className="grid h-12 shrink-0 grid-cols-[1fr_auto_1fr] items-center gap-2 border-b bg-muted/40 px-2">\n <div className="flex min-w-0 items-center gap-0.5">\n <button\n type="button"\n aria-label="Back"\n title="Back"\n disabled={!canGoBack}\n onClick={goBack}\n className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4.5" />\n </button>\n <button\n type="button"\n aria-label="Forward"\n title="Forward"\n disabled={!canGoForward}\n onClick={goForward}\n className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-4.5" />\n </button>\n <span className="ml-1.5 truncate text-sm font-semibold">\n {currentFolderName}\n </span>\n </div>\n {isCompact ? (\n <Select\n value={view}\n onValueChange={(value) => setView(value as FileSystemView)}\n >\n <SelectTrigger size="sm" aria-label="View" className="min-w-32">\n <SelectValue>\n {activeViewOption ? (\n <span className="flex items-center gap-2">\n <HugeiconsIcon\n icon={activeViewOption.icon}\n className="size-4"\n />\n {activeViewOption.label}\n </span>\n ) : null}\n </SelectValue>\n </SelectTrigger>\n <SelectContent>\n {VIEW_OPTIONS.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n <span className="flex items-center gap-2">\n <HugeiconsIcon icon={option.icon} className="size-4" />\n {option.label}\n </span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n ) : (\n <Tabs\n value={view}\n onValueChange={(value) => setView(value as FileSystemView)}\n className="gap-0"\n >\n <TabsList className="h-8 p-0.5">\n {VIEW_OPTIONS.map((option) => (\n <TabsTrigger\n key={option.value}\n value={option.value}\n aria-label={`${option.label} view`}\n title={option.label}\n className="h-7 grow-0 px-2.5 sm:h-7"\n >\n <HugeiconsIcon icon={option.icon} className="size-4" />\n </TabsTrigger>\n ))}\n </TabsList>\n </Tabs>\n )}\n <div />\n </div>\n <div className="relative min-h-0 flex-1">\n {isLoadingCurrentFolder && currentEntries.length === 0 ? (\n <FileSystemEmptyState label="Loading…" isLoading />\n ) : currentEntries.length === 0 && view !== "columns" ? (\n <FileSystemEmptyState label="This folder is empty" />\n ) : view === "icons" ? (\n <FileSystemIconsView {...viewProps} />\n ) : view === "list" ? (\n <FileSystemListView {...viewProps} />\n ) : view === "columns" ? (\n <FileSystemColumnsView {...viewProps} />\n ) : (\n <FileSystemGalleryView {...viewProps} />\n )}\n </div>\n <div\n aria-live="polite"\n className="flex h-7 shrink-0 items-center justify-center gap-1 border-t bg-muted/40 px-3 text-xs text-muted-foreground"\n >\n <span>\n {currentEntries.length}{" "}\n {currentEntries.length === 1 ? "item" : "items"}\n </span>\n {selectedEntry ? <span>· “{selectedEntry.name}” selected</span> : null}\n </div>\n <Dialog\n open={openedFile !== null}\n onOpenChange={(open) => {\n if (!open) setOpenedFile(null)\n }}\n >\n {openedFile ? (\n <DialogContent\n className={cn(\n "overflow-hidden p-0",\n VIEWER_DIALOG_CLASSNAMES[openedFile.kind]\n )}\n showCloseButton={openedFile.kind === "image"}\n >\n <DialogTitle className="sr-only">{openedFileName}</DialogTitle>\n {openedFile.kind === "pdf" ? (\n <PDFViewer\n file={openedFile.url}\n className="h-full min-h-0 flex-1 overflow-hidden rounded-2xl"\n downloadFileName={openedFileName}\n showUpload={false}\n toolbarActions={viewerCloseToolbarAction}\n />\n ) : openedFile.kind === "docx" ? (\n <DocxViewerPreview\n src={openedFile.url}\n fileName={openedFileName}\n className="h-full min-h-0 flex-1"\n rounded\n showUpload={false}\n toolbarActions={viewerCloseToolbarAction}\n />\n ) : openedFile.kind === "xlsx" ? (\n <XlsxViewerPreview\n src={openedFile.url}\n fileName={openedFileName}\n className="h-full min-h-0 flex-1"\n rounded\n showUpload={false}\n toolbarActions={viewerCloseToolbarAction}\n />\n ) : (\n <img\n src={openedFile.url}\n alt={openedFileName}\n className="max-h-[88vh] w-auto max-w-full rounded-2xl object-contain"\n />\n )}\n </DialogContent>\n ) : null}\n </Dialog>\n </div>\n )\n}\n\ntype FileSystemViewProps = {\n currentPath: string\n entries: FileSystemEntry[]\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n index: FileSystemIndex\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n loadingFolders: Set<string>\n onOpen: (entry: FileSystemEntry) => void\n onSelect: (entry: FileSystemEntry | null) => void\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n selectedEntry: FileSystemEntry | null\n selectedPath: string | null\n}\n\n// Resolves a display URL for a file: its own `url`, else via `getFileUrl`.\n// Keyed by path/url (not object identity) so manifest churn — e.g. thumbnails\n// streaming in — doesn\'t re-trigger presign calls for the same file.\nfunction useResolvedFileUrl(\n file: FileEntry | null,\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n) {\n const [resolvedUrl, setResolvedUrl] = React.useState<string | null>(\n file?.url ?? null\n )\n const fileRef = React.useRef(file)\n\n React.useEffect(() => {\n fileRef.current = file\n })\n\n const filePath = file?.path ?? null\n const fileUrl = file?.url ?? null\n\n React.useEffect(() => {\n const currentFile = fileRef.current\n\n if (!currentFile || fileUrl) {\n setResolvedUrl(fileUrl)\n return\n }\n if (!getFileUrl) {\n setResolvedUrl(null)\n return\n }\n\n let isCurrent = true\n\n setResolvedUrl(null)\n void Promise.resolve(getFileUrl(currentFile))\n .then((url) => {\n if (isCurrent) setResolvedUrl(url)\n })\n .catch(() => {})\n\n return () => {\n isCurrent = false\n }\n }, [filePath, fileUrl, getFileUrl])\n\n return resolvedUrl\n}\n\nfunction FileSystemEmptyState({\n label,\n isLoading = false,\n}: {\n label: string\n isLoading?: boolean\n}) {\n return (\n <div\n className={cn(\n "flex size-full items-center justify-center text-sm text-muted-foreground",\n isLoading && "animate-pulse motion-reduce:animate-none"\n )}\n >\n {label}\n </div>\n )\n}\n\nconst ARROW_KEYS = new Set(["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"])\n\n// Selects (and focuses) the entry reached by an arrow key. Up/down use row\n// geometry so navigation follows the rendered auto-fill grid.\nfunction moveGridSelection({\n entries,\n itemRefs,\n key,\n onSelect,\n selectedPath,\n}: {\n entries: FileSystemEntry[]\n itemRefs: Map<string, HTMLButtonElement>\n key: string\n onSelect: (entry: FileSystemEntry | null) => void\n selectedPath: string | null\n}) {\n if (entries.length === 0) return false\n\n const currentIndex = entries.findIndex((entry) => entry.path === selectedPath)\n let nextEntry: FileSystemEntry | undefined\n\n if (currentIndex === -1) {\n nextEntry = entries[0]\n } else if (key === "ArrowLeft" || key === "ArrowRight") {\n nextEntry = entries[currentIndex + (key === "ArrowLeft" ? -1 : 1)]\n } else {\n const currentElement = itemRefs.get(entries[currentIndex].path)\n\n if (!currentElement) return false\n\n const currentRect = currentElement.getBoundingClientRect()\n let bestScore = Infinity\n\n for (const entry of entries) {\n if (entry.path === selectedPath) continue\n\n const rect = itemRefs.get(entry.path)?.getBoundingClientRect()\n\n if (!rect) continue\n\n const rowDelta =\n key === "ArrowDown"\n ? rect.top - currentRect.top\n : currentRect.top - rect.top\n\n if (rowDelta <= 1) continue\n\n const score = rowDelta * 1000 + Math.abs(rect.left - currentRect.left)\n\n if (score < bestScore) {\n bestScore = score\n nextEntry = entry\n }\n }\n }\n\n if (!nextEntry) return false\n\n onSelect(nextEntry)\n itemRefs.get(nextEntry.path)?.focus()\n return true\n}\n\nfunction FileSystemIconsView({\n entries,\n onOpen,\n onSelect,\n renderFilePreview,\n selectedPath,\n}: FileSystemViewProps) {\n const itemRefs = React.useRef(new Map<string, HTMLButtonElement>())\n\n return (\n <ScrollArea\n orientation="vertical"\n viewportClassName="p-3"\n viewportProps={{\n onClick: (event) => {\n if (event.target === event.currentTarget) onSelect(null)\n },\n }}\n >\n <div\n role="listbox"\n aria-label="Files"\n className="grid grid-cols-[repeat(auto-fill,minmax(6.5rem,1fr))] gap-x-1 gap-y-3"\n onKeyDown={(event) => {\n if (!ARROW_KEYS.has(event.key)) return\n if (\n moveGridSelection({\n entries,\n itemRefs: itemRefs.current,\n key: event.key,\n onSelect,\n selectedPath,\n })\n ) {\n event.preventDefault()\n }\n }}\n >\n {entries.map((entry) => {\n const isSelected = entry.path === selectedPath\n\n return (\n <button\n key={entry.path}\n type="button"\n role="option"\n aria-selected={isSelected}\n ref={(element) => {\n if (element) {\n itemRefs.current.set(entry.path, element)\n } else {\n itemRefs.current.delete(entry.path)\n }\n }}\n onClick={() => onSelect(entry)}\n onDoubleClick={() => onOpen(entry)}\n onKeyDown={(event) => {\n if (event.key === "Enter") onOpen(entry)\n }}\n className="group flex flex-col items-center gap-1.5 outline-none"\n >\n <span\n className={cn(\n "flex h-16 w-20 items-center justify-center rounded-lg p-1 transition-colors group-focus-visible:ring-2 group-focus-visible:ring-ring",\n isSelected && "bg-accent"\n )}\n >\n {entry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-13 w-auto drop-shadow-sm" />\n ) : (\n <FileVisual\n file={entry}\n className={cn(\n "rounded-sm shadow-xs",\n // Landscape thumbnails get extra width so they fill\n // the tile instead of rendering as a short sliver.\n (entry.previewAspectRatio ?? 0.78) > 1.2\n ? "w-[4.75rem]"\n : "w-12"\n )}\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )}\n </span>\n <span\n className={cn(\n "max-w-full rounded-sm px-1.5 py-px text-center text-xs leading-tight break-words",\n isSelected\n ? "bg-primary text-primary-foreground"\n : "text-foreground"\n )}\n >\n <span className="line-clamp-2">{entry.name}</span>\n </span>\n </button>\n )\n })}\n </div>\n </ScrollArea>\n )\n}\n\nfunction FileSystemListView({\n currentPath,\n index,\n onOpen,\n onSelect,\n selectedPath,\n}: FileSystemViewProps) {\n const relativePaths = React.useMemo(() => {\n const paths: string[] = []\n\n for (const path of index.files.keys()) {\n if (currentPath === "" || path.startsWith(currentPath)) {\n const relativePath = path.slice(currentPath.length)\n\n if (relativePath) paths.push(relativePath)\n }\n }\n return paths.sort()\n }, [currentPath, index])\n // Content-derived key: the tree only remounts when the path set actually\n // changes (a bare length check misses same-count replacements).\n const treeKey = React.useMemo(\n () => hashString(relativePaths.join("\\n")),\n [relativePaths]\n )\n\n if (relativePaths.length === 0) {\n return <FileSystemEmptyState label="This folder is empty" />\n }\n\n return (\n <div className="flex size-full flex-col">\n {/* Paddings match the tree\'s row geometry: name text starts 46px in\n (16px tree padding + 30px icon lane), metadata ends 24px from the\n right (16px tree padding + 8px decoration inset). */}\n <div className="flex shrink-0 items-center border-b py-1.5 pr-6 pl-[46px] text-xs font-medium text-muted-foreground">\n <span className="flex-1">Name</span>\n <span className="w-44 text-right">Date Modified</span>\n <span className="w-20 text-right">Size</span>\n </div>\n <FileSystemPierreTree\n key={`${currentPath}::${treeKey}`}\n currentPath={currentPath}\n index={index}\n initialSelectedPath={\n selectedPath?.startsWith(currentPath)\n ? selectedPath.slice(currentPath.length).replace(/\\/$/, "")\n : null\n }\n onOpen={onOpen}\n onSelect={onSelect}\n relativePaths={relativePaths}\n />\n </div>\n )\n}\n\nfunction FileSystemPierreTree({\n currentPath,\n index,\n initialSelectedPath,\n onOpen,\n onSelect,\n relativePaths,\n}: {\n currentPath: string\n index: FileSystemIndex\n initialSelectedPath: string | null\n onOpen: (entry: FileSystemEntry) => void\n onSelect: (entry: FileSystemEntry | null) => void\n relativePaths: string[]\n}) {\n const preparedInput = React.useMemo(\n () => prepareFileTreeInput(relativePaths, { sort: "default" }),\n [relativePaths]\n )\n // Inject per-file thumbnails into the tree\'s shadow DOM as sprite symbols\n // wrapping an <image>, remapped onto rows by file basename. The chevron is\n // remapped to the Hugeicons arrow so it matches the rest of the component;\n // the tree\'s rotation CSS keys off data-icon-name, which remapping keeps.\n const icons = React.useMemo(() => {\n const byFileName: Record<string, { name: string; viewBox: string }> = {}\n const symbols: string[] = [\n `<symbol id="file-system-chevron" viewBox="0 0 24 24"><path d="M18 9.00005C18 9.00005 13.5811 15 12 15C10.4188 15 6 9 6 9" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"/></symbol>`,\n ]\n\n for (const relativePath of relativePaths) {\n const file = index.files.get(`${currentPath}${relativePath}`)\n const coverUrl = file ? filePreviewUrls(file)[0] : undefined\n\n if (!file || !coverUrl) continue\n\n const baseName = file.name.toLowerCase()\n\n if (byFileName[baseName]) continue\n\n const symbolId = `file-system-thumbnail-${symbols.length}`\n\n symbols.push(\n `<symbol id="${symbolId}" viewBox="0 0 16 16"><clipPath id="${symbolId}-clip"><rect width="16" height="16" rx="2.5"/></clipPath><image href="${escapeXmlAttribute(coverUrl)}" width="16" height="16" preserveAspectRatio="xMidYMid slice" clip-path="url(#${symbolId}-clip)"/></symbol>`\n )\n byFileName[baseName] = { name: symbolId, viewBox: "0 0 16 16" }\n }\n\n return {\n byFileName,\n remap: {\n "file-tree-icon-chevron": {\n name: "file-system-chevron",\n viewBox: "0 0 24 24",\n },\n },\n spriteSheet: `<svg data-icon-sprite aria-hidden="true" width="0" height="0">${symbols.join("")}</svg>`,\n }\n }, [currentPath, index, relativePaths])\n const { model } = useFileTree({\n flattenEmptyDirectories: false,\n icons,\n initialExpansion: "closed",\n initialSelectedPaths: initialSelectedPath ? [initialSelectedPath] : [],\n itemHeight: 28,\n overscan: 12,\n preparedInput,\n renderRowDecoration: ({ row }) => {\n const entry =\n row.kind === "file"\n ? index.files.get(`${currentPath}${row.path}`)\n : index.folders.get(normalizeFolderPath(`${currentPath}${row.path}`))\n\n if (!entry) return null\n\n // The decoration lane renders one <span title>; CSS splits it into\n // aligned Date Modified (::before from title) and Size columns.\n const dateColumn =\n formatTimestamp(entry.updatedAt ?? entry.createdAt) ?? "—"\n\n if (entry.kind === "folder") {\n const childCount = index.children.get(entry.path)?.length\n\n return {\n text:\n childCount === undefined\n ? "—"\n : `${childCount} ${childCount === 1 ? "item" : "items"}`,\n title: dateColumn,\n }\n }\n\n return { text: formatByteSize(entry.size) ?? "—", title: dateColumn }\n },\n unsafeCSS: `\n button[data-type=\'item\']:not([data-item-selected]):hover {\n background: color-mix(in oklab, var(--color-accent) 50%, transparent);\n }\n button[data-type=\'item\'][data-item-selected] {\n background: var(--color-primary);\n color: var(--color-primary-foreground);\n }\n button[data-type=\'item\'][data-item-selected] *,\n button[data-type=\'item\'][data-item-selected] [data-item-section]::before,\n button[data-type=\'item\'][data-item-selected] svg {\n color: var(--color-primary-foreground) !important;\n }\n [data-item-section=\'decoration\'] > span {\n display: grid;\n grid-template-columns: 11rem 5rem;\n justify-items: end;\n white-space: nowrap;\n }\n [data-item-section=\'decoration\'] > span::before {\n content: attr(title);\n }\n button[data-type=\'item\'][data-item-type=\'folder\'] [data-item-section=\'content\'] {\n display: flex;\n align-items: center;\n min-width: 0;\n }\n button[data-type=\'item\'][data-item-type=\'folder\'] [data-item-section=\'content\']::before {\n content: "";\n flex: none;\n width: 18px;\n height: 14px;\n margin-right: 4px;\n background: url("${FOLDER_GLYPH_DATA_URL}") center / contain no-repeat;\n }\n `,\n onSelectionChange: (selectedPaths) => {\n const relativePath = selectedPaths[0]\n\n if (!relativePath) {\n onSelect(null)\n return\n }\n\n const absolutePath = `${currentPath}${relativePath}`\n const entry =\n index.files.get(absolutePath) ??\n index.folders.get(normalizeFolderPath(absolutePath)) ??\n null\n\n onSelect(entry)\n },\n })\n\n // Thumbnails can resolve after mount (e.g. generated client-side); push\n // sprite updates into the existing model instead of remounting the tree.\n React.useEffect(() => {\n model.setIcons(icons)\n }, [icons, model])\n\n return (\n <PierreFileTree\n model={model}\n className="block min-h-0 flex-1"\n onDoubleClick={(event) => {\n // Rows live in the tree\'s shadow DOM; composedPath surfaces the row\n // element so double-clicked files open like in the other views.\n for (const target of event.nativeEvent.composedPath()) {\n if (!(target instanceof HTMLElement)) continue\n const relativePath = target.dataset?.itemPath\n if (!relativePath) continue\n\n const file = index.files.get(`${currentPath}${relativePath}`)\n\n if (file) onOpen(file)\n return\n }\n }}\n style={\n {\n "--trees-bg-override": "transparent",\n "--trees-border-color-override": "var(--color-border)",\n "--trees-fg-override": "var(--color-foreground)",\n "--trees-selected-bg-override": "var(--color-primary)",\n } as React.CSSProperties\n }\n />\n )\n}\n\nfunction FileSystemColumnsView(props: FileSystemViewProps) {\n const {\n currentPath,\n index,\n loadPreviewImageUrl,\n loadingFolders,\n onOpen,\n onSelect,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n } = props\n const scrollContainerRef = React.useRef<HTMLDivElement | null>(null)\n const rowRefs = React.useRef(new Map<string, HTMLButtonElement>())\n\n const handleKeyDown = (event: React.KeyboardEvent) => {\n if (!ARROW_KEYS.has(event.key)) return\n\n let nextEntry: FileSystemEntry | null | undefined\n\n if (!selectedEntry || !selectedPath?.startsWith(currentPath)) {\n nextEntry = index.children.get(currentPath)?.[0]\n } else if (event.key === "ArrowUp" || event.key === "ArrowDown") {\n const siblings = index.children.get(selectedEntry.parentPath) ?? []\n const currentIndex = siblings.findIndex(\n (sibling) => sibling.path === selectedEntry.path\n )\n\n nextEntry = siblings[currentIndex + (event.key === "ArrowUp" ? -1 : 1)]\n } else if (event.key === "ArrowLeft") {\n if (selectedEntry.parentPath !== currentPath) {\n nextEntry = index.folders.get(selectedEntry.parentPath)\n }\n } else if (selectedEntry.kind === "folder") {\n nextEntry = index.children.get(selectedEntry.path)?.[0]\n }\n\n if (!nextEntry) return\n\n onSelect(nextEntry)\n rowRefs.current.get(nextEntry.path)?.focus()\n event.preventDefault()\n }\n\n const columnPaths = React.useMemo(() => {\n const paths = [currentPath]\n\n if (!selectedPath?.startsWith(currentPath)) return paths\n\n const targetFolder =\n selectedEntry?.kind === "folder"\n ? selectedEntry.path\n : (selectedEntry?.parentPath ?? currentPath)\n const relativePath = targetFolder.slice(currentPath.length)\n let walkedPath = currentPath\n\n for (const segment of relativePath.split("/")) {\n if (!segment) continue\n walkedPath = `${walkedPath}${segment}/`\n paths.push(walkedPath)\n }\n return paths\n }, [currentPath, selectedEntry, selectedPath])\n const columnPathSet = React.useMemo(() => new Set(columnPaths), [columnPaths])\n const selectedFile =\n selectedEntry?.kind === "file" ? (selectedEntry as FileEntry) : null\n const selectedFileSize = selectedFile\n ? formatByteSize(selectedFile.size)\n : null\n\n React.useEffect(() => {\n const container = scrollContainerRef.current\n\n if (container) container.scrollLeft = container.scrollWidth\n }, [columnPaths.length, selectedPath])\n\n return (\n <ScrollArea\n orientation="horizontal"\n viewportRef={scrollContainerRef}\n viewportClassName="overscroll-x-contain"\n >\n <div className="flex h-full w-max min-w-full" onKeyDown={handleKeyDown}>\n {columnPaths.map((columnPath) => (\n <ScrollArea\n key={columnPath || "(root)"}\n orientation="vertical"\n className="w-60 shrink-0 border-r"\n viewportClassName="flex flex-col gap-px p-1.5"\n viewportProps={{ "aria-label": "Files", role: "listbox" }}\n >\n {loadingFolders.has(columnPath) &&\n !index.children.get(columnPath)?.length ? (\n <div className="animate-pulse px-2 py-1.5 text-xs text-muted-foreground motion-reduce:animate-none">\n Loading…\n </div>\n ) : (\n (index.children.get(columnPath) ?? []).map((entry) => {\n const isSelected = entry.path === selectedPath\n const isOnTrail =\n entry.kind === "folder" && columnPathSet.has(entry.path)\n\n const coverUrl =\n entry.kind === "file" ? filePreviewUrls(entry)[0] : undefined\n\n return (\n <button\n key={entry.path}\n type="button"\n role="option"\n aria-selected={isSelected}\n ref={(element) => {\n if (element) {\n rowRefs.current.set(entry.path, element)\n } else {\n rowRefs.current.delete(entry.path)\n }\n }}\n onClick={() => onSelect(entry)}\n onDoubleClick={() => onOpen(entry)}\n onKeyDown={(event) => {\n if (event.key === "Enter") onOpen(entry)\n }}\n className={cn(\n "flex shrink-0 items-center gap-2 rounded-md px-2 py-1 text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",\n isSelected\n ? "bg-primary text-primary-foreground"\n : isOnTrail\n ? "bg-accent"\n : "hover:bg-accent/50"\n )}\n >\n {entry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-3.5 w-auto shrink-0" />\n ) : coverUrl ? (\n <img\n src={coverUrl}\n alt=""\n draggable={false}\n className="size-4 shrink-0 rounded-[3px] bg-white object-cover"\n />\n ) : (\n <HugeiconsIcon\n icon={File01Icon}\n className={cn(\n "size-4 shrink-0",\n !isSelected && "text-muted-foreground"\n )}\n />\n )}\n <span className="min-w-0 flex-1 truncate">\n {entry.name}\n </span>\n {entry.kind === "folder" &&\n folderHasChildren(index, entry) ? (\n <HugeiconsIcon\n icon={ArrowRight01Icon}\n className={cn(\n "size-3.5 shrink-0",\n !isSelected && "text-muted-foreground/60"\n )}\n />\n ) : null}\n </button>\n )\n })\n )}\n </ScrollArea>\n ))}\n {selectedFile ? (\n <ScrollArea\n orientation="vertical"\n className="min-w-72 flex-1"\n viewportClassName="flex justify-center p-4"\n >\n <div className="flex w-full max-w-lg flex-col items-stretch gap-3">\n {/* Width derives from the aspect ratio so the thumbnail grows\n with the pane up to a 20rem height cap. */}\n <div\n className="mx-auto w-full shrink-0"\n style={{\n maxWidth: `min(100%, ${(selectedFile.previewAspectRatio ?? 0.78) * 20}rem)`,\n }}\n >\n <FileVisual\n file={selectedFile}\n className="w-full"\n loadPreviewImageUrl={loadPreviewImageUrl}\n pageable\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n </div>\n <div className="text-center">\n <div className="text-sm font-semibold break-words">\n {selectedFile.name}\n </div>\n <div className="text-xs text-muted-foreground">\n {fileKindLabel(selectedFile)}\n {selectedFileSize ? ` - ${selectedFileSize}` : null}\n </div>\n </div>\n <FileSystemInformation entry={selectedFile} index={index} />\n </div>\n </ScrollArea>\n ) : null}\n </div>\n </ScrollArea>\n )\n}\n\nfunction FileSystemInformation({\n entry,\n index,\n}: {\n entry: FileSystemEntry\n index: FileSystemIndex\n}) {\n const rows: Array<[string, string]> = []\n const created = formatTimestamp(entry.createdAt)\n const updated = formatTimestamp(entry.updatedAt)\n\n if (created) rows.push(["Created", created])\n if (updated) rows.push(["Modified", updated])\n if (entry.kind === "file") {\n const size = formatByteSize(entry.size)\n\n if (size) rows.push(["Size", size])\n } else {\n const childCount = index.children.get(entry.path)?.length\n\n if (childCount !== undefined) {\n rows.push(["Items", `${childCount}`])\n }\n }\n\n if (rows.length === 0) return null\n\n return (\n <div className="border-t pt-3">\n <div className="mb-1.5 text-xs font-semibold">Information</div>\n <dl className="space-y-1">\n {rows.map(([label, value]) => (\n <div\n key={label}\n className="flex items-baseline justify-between gap-3 text-xs"\n >\n <dt className="shrink-0 text-muted-foreground">{label}</dt>\n <dd className="text-right" suppressHydrationWarning>\n {value}\n </dd>\n </div>\n ))}\n </dl>\n </div>\n )\n}\n\nfunction FileSystemGalleryView(props: FileSystemViewProps) {\n const {\n entries,\n getFileUrl,\n index,\n loadPreviewImageUrl,\n onOpen,\n onSelect,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n } = props\n const stripRefs = React.useRef(new Map<string, HTMLButtonElement>())\n const activeEntry =\n selectedEntry && entries.some((entry) => entry.path === selectedEntry.path)\n ? selectedEntry\n : (entries[0] ?? null)\n const activeFile = activeEntry?.kind === "file" ? activeEntry : null\n const activeViewerKind = activeFile ? viewerKindForFile(activeFile) : null\n const activeFileUrl = useResolvedFileUrl(activeFile, getFileUrl)\n const activeFileSize = activeFile ? formatByteSize(activeFile.size) : null\n\n const handleKeyDown = (event: React.KeyboardEvent) => {\n if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return\n if (entries.length === 0) return\n\n const currentIndex = activeEntry\n ? entries.findIndex((entry) => entry.path === activeEntry.path)\n : -1\n const nextEntry =\n entries[\n currentIndex === -1\n ? 0\n : currentIndex + (event.key === "ArrowLeft" ? -1 : 1)\n ]\n\n if (!nextEntry) return\n\n onSelect(nextEntry)\n stripRefs.current.get(nextEntry.path)?.focus()\n event.preventDefault()\n }\n\n return (\n <div className="flex size-full flex-col" onKeyDown={handleKeyDown}>\n <div className="flex min-h-0 flex-1">\n <div className="flex min-h-0 min-w-0 flex-1 items-center justify-center p-3">\n {activeEntry ? (\n activeEntry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-40 max-h-full w-auto drop-shadow-md" />\n ) : activeViewerKind === "image" && activeFileUrl ? (\n <img\n src={activeFileUrl}\n alt={activeEntry.name}\n className="max-h-full max-w-full rounded-lg object-contain"\n />\n ) : activeViewerKind === "pdf" && activeFileUrl ? (\n <div className="size-full overflow-hidden rounded-lg border">\n <PDFViewer\n key={activeEntry.path}\n file={activeFileUrl}\n className="h-full"\n showToolbar={false}\n />\n </div>\n ) : activeViewerKind === "docx" && activeFileUrl ? (\n <div className="size-full overflow-hidden rounded-lg border">\n <DocxViewerPreview\n key={activeEntry.path}\n src={activeFileUrl}\n fileName={activeEntry.name}\n className="h-full"\n showToolbar={false}\n />\n </div>\n ) : activeViewerKind === "xlsx" && activeFileUrl ? (\n <div className="size-full overflow-hidden rounded-lg border">\n <XlsxViewerPreview\n key={activeEntry.path}\n src={activeFileUrl}\n fileName={activeEntry.name}\n className="h-full"\n showToolbar={false}\n />\n </div>\n ) : (\n <FileVisual\n file={activeEntry}\n className="w-56 max-w-full"\n loadPreviewImageUrl={loadPreviewImageUrl}\n pageable\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )\n ) : null}\n </div>\n {activeEntry ? (\n <ScrollArea\n orientation="vertical"\n className="hidden w-64 shrink-0 border-l sm:block"\n viewportClassName="flex flex-col gap-3 p-4"\n >\n <div className="flex items-center gap-3">\n {activeFile ? (\n <FileVisual\n file={activeFile}\n className={cn(\n "shrink-0 rounded-sm",\n (activeFile.previewAspectRatio ?? 0.78) > 1.2\n ? "w-16"\n : "w-9"\n )}\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n ) : (\n <FileSystemFolderGlyph className="h-8 w-auto shrink-0" />\n )}\n <div className="min-w-0 flex-1">\n <div className="text-sm font-semibold break-words">\n {activeEntry.name}\n </div>\n <div className="text-xs text-muted-foreground">\n {activeFile ? fileKindLabel(activeFile) : "Folder"}\n {activeFileSize ? ` - ${activeFileSize}` : null}\n </div>\n </div>\n </div>\n <FileSystemInformation entry={activeEntry} index={index} />\n </ScrollArea>\n ) : null}\n </div>\n <ScrollArea\n orientation="horizontal"\n className="h-auto w-full shrink-0 border-t"\n >\n <div\n role="listbox"\n aria-label="Files"\n className="flex w-max min-w-full items-center gap-1.5 p-2"\n >\n {entries.map((entry) => {\n const isActive = entry.path === (activeEntry?.path ?? selectedPath)\n\n return (\n <button\n key={entry.path}\n type="button"\n role="option"\n aria-selected={isActive}\n ref={(element) => {\n if (element) {\n stripRefs.current.set(entry.path, element)\n } else {\n stripRefs.current.delete(entry.path)\n }\n }}\n onClick={() => onSelect(entry)}\n onDoubleClick={() => onOpen(entry)}\n onKeyDown={(event) => {\n if (event.key === "Enter") onOpen(entry)\n }}\n title={entry.name}\n className={cn(\n "flex size-14 shrink-0 items-center justify-center rounded-md border border-transparent p-1 outline-none focus-visible:ring-2 focus-visible:ring-ring",\n isActive && "border-ring/40 bg-accent"\n )}\n >\n {entry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-9 w-auto" />\n ) : (\n <FileVisual\n file={entry}\n className="w-9 rounded-sm"\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )}\n </button>\n )\n })}\n </div>\n </ScrollArea>\n </div>\n )\n}\n'
+ '"use client"\n\nimport * as React from "react"\nimport {\n ArrowLeft01Icon,\n ArrowRight01Icon,\n Cancel01Icon,\n File01Icon,\n GalleryThumbnailsIcon,\n GridViewIcon,\n LayoutThreeColumnIcon,\n LeftToRightListBulletIcon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { prepareFileTreeInput } from "@pierre/trees"\nimport { FileTree as PierreFileTree, useFileTree } from "@pierre/trees/react"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogTitle,\n} from "@/components/ui/dialog"\nimport { DocxViewerPreview } from "@/components/ui/docx-viewer"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { PDFViewer } from "@/components/ui/pdf-viewer"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Spinner } from "@/components/ui/spinner"\nimport { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"\nimport { XlsxViewerPreview } from "@/components/ui/xlsx-viewer"\n\nexport type FileSystemView = "icons" | "list" | "columns" | "gallery"\n\nexport type FileSystemFolderItem = {\n kind: "folder"\n /** Folder prefix, e.g. `"invoices/2026/"`. A trailing slash is added when missing. */\n path: string\n name?: string\n parentPath?: string\n /** Set when children exist but are not in `items` yet; enables `loadChildren`. */\n hasChildren?: boolean\n createdAt?: string\n updatedAt?: string\n}\n\nexport type FileSystemFileItem = {\n kind: "file"\n /** Display/canonical path, e.g. `"invoices/2026/jan.pdf"`. */\n path: string\n /** Original object key (S3/R2). Defaults to `path`. */\n key?: string\n name?: string\n parentPath?: string\n contentType?: string\n size?: number\n createdAt?: string\n updatedAt?: string\n etag?: string\n /** Optional if already public/presigned. Otherwise resolved via `getFileUrl`. */\n url?: string\n /** Externally generated thumbnail. The component never renders documents itself. */\n previewImageUrl?: string | null\n /**\n * Externally generated page thumbnails (first entry is the cover). When a\n * file has more than one page, large thumbnails show a hover pager.\n */\n previewImageUrls?: string[] | null\n /**\n * Total page count when it exceeds `previewImageUrls.length`; the pager\n * loads the remaining pages on demand via `loadPreviewImageUrl`.\n */\n previewPageCount?: number\n /** Thumbnail aspect ratio (width / height). Defaults to a portrait page. */\n previewAspectRatio?: number\n metadata?: Record<string, string>\n}\n\nexport type FileSystemItem = FileSystemFolderItem | FileSystemFileItem\n\nexport type FileSystemLoadChildrenArgs = {\n path: string\n cursor: string | null\n}\n\nexport type FileSystemLoadChildrenResult = {\n items: FileSystemItem[]\n nextCursor?: string | null\n}\n\nexport type FileSystemProps = {\n /** Flat manifest. Folders are optional; missing prefixes are inferred from file paths. */\n items: FileSystemItem[]\n className?: string\n /** Label for the root folder. */\n title?: string\n defaultView?: FileSystemView\n view?: FileSystemView\n onViewChange?: (view: FileSystemView) => void\n /** Folder prefix to open initially, e.g. `"invoices/"`. */\n defaultPath?: string\n onSelectionChange?: (item: FileSystemItem | null) => void\n /**\n * Called on file open (double-click), replacing the built-in behavior. By\n * default PDF, DOCX, XLSX, and image files open in a viewer dialog and\n * other files open their resolved URL in a new tab.\n */\n onFileOpen?: (file: FileSystemFileItem, url: string | null) => void\n /** Resolve a URL (e.g. presigned) for a file without one. */\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n /** Lazily fetch children for folders with `hasChildren` and no loaded entries. */\n loadChildren?: (\n args: FileSystemLoadChildrenArgs\n ) => Promise<FileSystemLoadChildrenResult>\n /** Custom preview node for files without `previewImageUrl`. */\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n /**\n * Lazily render a page thumbnail beyond the eagerly provided\n * `previewImageUrls` (the pager calls this as pages come into view).\n */\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n}\n\ntype FolderEntry = FileSystemFolderItem & {\n name: string\n parentPath: string\n}\n\ntype FileEntry = FileSystemFileItem & {\n key: string\n name: string\n parentPath: string\n}\n\ntype FileSystemEntry = FolderEntry | FileEntry\n\ntype FileSystemIndex = {\n children: Map<string, FileSystemEntry[]>\n files: Map<string, FileEntry>\n folders: Map<string, FolderEntry>\n}\n\nfunction normalizeFolderPath(path: string) {\n if (!path || path === "/") return ""\n return path.endsWith("/") ? path : `${path}/`\n}\n\nfunction pathName(path: string) {\n const trimmed = path.endsWith("/") ? path.slice(0, -1) : path\n const separatorIndex = trimmed.lastIndexOf("/")\n return separatorIndex === -1 ? trimmed : trimmed.slice(separatorIndex + 1)\n}\n\nfunction pathParent(path: string) {\n const trimmed = path.endsWith("/") ? path.slice(0, -1) : path\n const separatorIndex = trimmed.lastIndexOf("/")\n return separatorIndex === -1 ? "" : trimmed.slice(0, separatorIndex + 1)\n}\n\nfunction fileExtension(name: string) {\n const dotIndex = name.lastIndexOf(".")\n return dotIndex === -1 ? "" : name.slice(dotIndex + 1).toLowerCase()\n}\n\nconst FILE_KIND_LABELS: Record<string, string> = {\n csv: "CSV Document",\n doc: "Word Document",\n docx: "Word Document",\n gif: "GIF Image",\n jpeg: "JPEG Image",\n jpg: "JPEG Image",\n md: "Markdown Document",\n pdf: "PDF Document",\n png: "PNG Image",\n ppt: "PowerPoint Presentation",\n pptx: "PowerPoint Presentation",\n svg: "SVG Image",\n tsv: "TSV Document",\n txt: "Plain Text",\n webp: "WebP Image",\n xls: "Excel Workbook",\n xlsx: "Excel Workbook",\n zip: "ZIP Archive",\n}\n\nfunction fileKindLabel(file: FileEntry) {\n const byExtension = FILE_KIND_LABELS[fileExtension(file.name)]\n\n if (byExtension) return byExtension\n if (file.contentType?.startsWith("image/")) return "Image"\n\n return file.contentType ?? "Document"\n}\n\nexport type FileSystemViewerKind = "docx" | "image" | "pdf" | "xlsx"\n\nfunction viewerKindForFile(\n file: FileSystemFileItem\n): FileSystemViewerKind | null {\n if (file.contentType?.startsWith("image/")) return "image"\n if (file.contentType === "application/pdf") return "pdf"\n\n const name = (file.name ?? file.path).toLowerCase()\n\n if (name.endsWith(".pdf")) return "pdf"\n if (name.endsWith(".docx")) return "docx"\n if (name.endsWith(".xlsx")) return "xlsx"\n if (/\\.(avif|gif|jpe?g|png|svg|webp)$/.test(name)) return "image"\n\n return null\n}\n\n// PDF and DOCX pages want height; spreadsheets want width; images get a\n// roomy but contained frame.\nconst VIEWER_DIALOG_CLASSNAMES: Record<FileSystemViewerKind, string> = {\n docx: "h-[88vh] w-[min(96vw,68rem)] max-w-none",\n image: "max-h-[88vh] w-fit max-w-[min(96vw,64rem)]",\n pdf: "h-[88vh] w-[min(96vw,68rem)] max-w-none",\n xlsx: "h-[85vh] w-[min(96vw,100rem)] max-w-none",\n}\n\nfunction formatByteSize(size: number | undefined) {\n if (size === undefined) return null\n if (size < 1000) return `${size} bytes`\n\n const units = ["KB", "MB", "GB", "TB"]\n let value = size\n\n for (const unit of units) {\n value /= 1000\n if (value < 1000 || unit === "TB") {\n return `${value >= 100 ? Math.round(value) : value.toFixed(value >= 10 ? 1 : 2).replace(/\\.?0+$/, "")} ${unit}`\n }\n }\n\n return null\n}\n\nfunction formatTimestamp(value: string | undefined) {\n if (!value) return null\n\n const date = new Date(value)\n\n if (Number.isNaN(date.getTime())) return null\n\n const day = date.toLocaleDateString("en-US", {\n day: "numeric",\n month: "short",\n year: "numeric",\n })\n const time = date.toLocaleTimeString("en-US", {\n hour: "numeric",\n minute: "2-digit",\n })\n\n return `${day} at ${time}`\n}\n\nfunction buildFileSystemIndex(items: FileSystemItem[]): FileSystemIndex {\n const folders = new Map<string, FolderEntry>()\n const files = new Map<string, FileEntry>()\n\n const ensureFolderChain = (folderPath: string) => {\n let path = normalizeFolderPath(folderPath)\n\n while (path && !folders.has(path)) {\n folders.set(path, {\n kind: "folder",\n name: pathName(path),\n parentPath: pathParent(path),\n path,\n })\n path = pathParent(path)\n }\n }\n\n for (const item of items) {\n if (item.kind === "folder") {\n const path = normalizeFolderPath(item.path)\n\n if (!path) continue\n\n folders.set(path, {\n ...item,\n name: item.name ?? pathName(path),\n parentPath: normalizeFolderPath(item.parentPath ?? pathParent(path)),\n path,\n })\n ensureFolderChain(pathParent(path))\n } else {\n if (!item.path) continue\n\n files.set(item.path, {\n ...item,\n key: item.key ?? item.path,\n name: item.name ?? pathName(item.path),\n parentPath: normalizeFolderPath(\n item.parentPath ?? pathParent(item.path)\n ),\n })\n ensureFolderChain(pathParent(item.path))\n }\n }\n\n const children = new Map<string, FileSystemEntry[]>()\n const pushChild = (entry: FileSystemEntry) => {\n const siblings = children.get(entry.parentPath)\n\n if (siblings) {\n siblings.push(entry)\n } else {\n children.set(entry.parentPath, [entry])\n }\n }\n\n for (const folder of folders.values()) pushChild(folder)\n for (const file of files.values()) pushChild(file)\n for (const siblings of children.values()) {\n siblings.sort((left, right) =>\n left.name.localeCompare(right.name, undefined, {\n numeric: true,\n sensitivity: "base",\n })\n )\n }\n\n return { children, files, folders }\n}\n\nfunction folderHasChildren(index: FileSystemIndex, folder: FolderEntry) {\n return (\n (index.children.get(folder.path)?.length ?? 0) > 0 ||\n folder.hasChildren === true\n )\n}\n\n// A single SVG source so the same glyph renders as a React element, inside the\n// @pierre/trees shadow DOM (via CSS url()), and stays pixel-identical in both.\nconst FOLDER_GLYPH_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 50" width="64" height="50"><defs><linearGradient id="fs-folder-back" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#3dabf5"/><stop offset="1" stop-color="#1d84dd"/></linearGradient><linearGradient id="fs-folder-front" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#7accfb"/><stop offset="1" stop-color="#37a0ef"/></linearGradient></defs><path d="M5 10c0-3.31 2.69-6 6-6h10.9c1.6 0 3.13.7 4.18 1.9l1.5 1.73a3.5 3.5 0 0 0 2.64 1.22H54c2.76 0 5 2.24 5 5V40c0 3.87-3.13 7-7 7H12c-3.87 0-7-3.13-7-7V10Z" fill="url(#fs-folder-back)"/><path d="M5 15.5h54V40c0 3.87-3.13 7-7 7H12c-3.87 0-7-3.13-7-7V15.5Z" fill="url(#fs-folder-front)"/></svg>`\n\nconst FOLDER_GLYPH_DATA_URL = `data:image/svg+xml,${encodeURIComponent(FOLDER_GLYPH_SVG)}`\n\nfunction FileSystemFolderGlyph({ className }: { className?: string }) {\n return (\n <img\n src={FOLDER_GLYPH_DATA_URL}\n alt=""\n aria-hidden="true"\n draggable={false}\n className={className}\n />\n )\n}\n\nfunction escapeXmlAttribute(value: string) {\n return value\n .replaceAll("&", "&amp;")\n .replaceAll("<", "&lt;")\n .replaceAll(">", "&gt;")\n .replaceAll(\'"\', "&quot;")\n}\n\nfunction FileGenericPreview({ file }: { file: FileEntry }) {\n const extension = fileExtension(file.name)\n\n return (\n <div className="flex size-full flex-col items-center justify-center gap-1.5 bg-white text-neutral-400 dark:bg-neutral-100">\n <HugeiconsIcon icon={File01Icon} className="size-1/3 min-h-4 min-w-4" />\n {extension ? (\n <span className="text-[min(0.625rem,18cqw)] font-semibold tracking-wide uppercase">\n {extension}\n </span>\n ) : null}\n </div>\n )\n}\n\nfunction filePreviewUrls(file: FileSystemFileItem) {\n if (file.previewImageUrls?.length) return file.previewImageUrls\n return file.previewImageUrl ? [file.previewImageUrl] : []\n}\n\n// djb2 — cheap stable hash for remount keys derived from path lists.\nfunction hashString(value: string) {\n let hash = 5381\n\n for (let index = 0; index < value.length; index += 1) {\n hash = ((hash << 5) + hash + value.charCodeAt(index)) | 0\n }\n return hash\n}\n\nfunction FileVisual({\n file,\n className,\n loadPreviewImageUrl,\n pageable = false,\n previewAspectRatio,\n previewClassName,\n renderFilePreview,\n}: {\n file: FileEntry\n className?: string\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n /** Show a hover pager over multi-page thumbnails. */\n pageable?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n}) {\n const previewUrls = filePreviewUrls(file)\n const canLoadLazily = pageable && Boolean(loadPreviewImageUrl)\n const totalPages = Math.max(\n previewUrls.length,\n canLoadLazily ? (file.previewPageCount ?? 0) : 0\n )\n const [pageIndex, setPageIndex] = React.useState(0)\n const [lazyPageUrls, setLazyPageUrls] = React.useState<\n Record<number, string>\n >({})\n const clampedPageIndex = Math.min(pageIndex, Math.max(totalPages - 1, 0))\n const previewUrl =\n previewUrls[clampedPageIndex] ?? lazyPageUrls[clampedPageIndex] ?? null\n const resolvedAspectRatio = file.previewAspectRatio ?? previewAspectRatio\n const isLazyPagePending =\n canLoadLazily && !previewUrl && clampedPageIndex < totalPages\n\n const fileRef = React.useRef(file)\n\n React.useEffect(() => {\n fileRef.current = file\n })\n\n React.useEffect(() => {\n setPageIndex(0)\n setLazyPageUrls({})\n }, [file.path])\n\n // Keyed by path (not object identity) so manifest churn doesn\'t re-request\n // the page already being loaded.\n React.useEffect(() => {\n if (!isLazyPagePending || !loadPreviewImageUrl) return\n\n let isCurrent = true\n\n void loadPreviewImageUrl(fileRef.current, clampedPageIndex)\n .then((url) => {\n if (isCurrent && url) {\n setLazyPageUrls((previous) => ({\n ...previous,\n [clampedPageIndex]: url,\n }))\n }\n })\n .catch(() => {})\n\n return () => {\n isCurrent = false\n }\n }, [clampedPageIndex, file.path, isLazyPagePending, loadPreviewImageUrl])\n\n const customPreview =\n !previewUrl && !isLazyPagePending ? renderFilePreview?.(file) : null\n const showPager = pageable && totalPages > 1\n const thumbnail = (\n <FileThumbnail\n file={{ name: file.name, type: file.contentType ?? "" }}\n className={cn("@container", !showPager && className)}\n previewAspectRatio={resolvedAspectRatio}\n previewClassName={cn("bg-white dark:bg-neutral-100", previewClassName)}\n previewImageUrl={previewUrl ?? undefined}\n isLoading={isLazyPagePending}\n previewContent={\n previewUrl || isLazyPagePending\n ? undefined\n : (customPreview ?? <FileGenericPreview file={file} />)\n }\n />\n )\n\n if (!showPager) return thumbnail\n\n return (\n <div className={cn("group/pager relative", className)}>\n {thumbnail}\n <div className="absolute inset-x-0 bottom-1.5 flex items-center justify-center gap-1 opacity-0 transition-opacity group-focus-within/pager:opacity-100 group-hover/pager:opacity-100">\n <button\n type="button"\n aria-label="Previous page"\n tabIndex={-1}\n disabled={clampedPageIndex === 0}\n onClick={(event) => {\n event.stopPropagation()\n setPageIndex((previous) => Math.max(0, previous - 1))\n }}\n onDoubleClick={(event) => event.stopPropagation()}\n className="flex size-6 items-center justify-center rounded-md bg-background/80 text-foreground shadow-xs backdrop-blur-sm transition-colors outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-3.5" />\n </button>\n <span className="rounded-md bg-background/80 px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground tabular-nums shadow-xs backdrop-blur-sm">\n {clampedPageIndex + 1}/{totalPages}\n </span>\n <button\n type="button"\n aria-label="Next page"\n tabIndex={-1}\n disabled={clampedPageIndex >= totalPages - 1}\n onClick={(event) => {\n event.stopPropagation()\n setPageIndex((previous) => Math.min(totalPages - 1, previous + 1))\n }}\n onDoubleClick={(event) => event.stopPropagation()}\n className="flex size-6 items-center justify-center rounded-md bg-background/80 text-foreground shadow-xs backdrop-blur-sm transition-colors outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-3.5" />\n </button>\n </div>\n </div>\n )\n}\n\nconst VIEW_OPTIONS: Array<{\n icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]\n label: string\n value: FileSystemView\n}> = [\n { icon: GridViewIcon, label: "Grid", value: "icons" },\n { icon: LeftToRightListBulletIcon, label: "List", value: "list" },\n { icon: LayoutThreeColumnIcon, label: "Columns", value: "columns" },\n { icon: GalleryThumbnailsIcon, label: "Gallery", value: "gallery" },\n]\n\nexport function FileSystem({\n items,\n className,\n title = "Files",\n defaultView = "icons",\n view: viewProp,\n onViewChange,\n defaultPath = "",\n onSelectionChange,\n onFileOpen,\n getFileUrl,\n loadChildren,\n loadPreviewImageUrl,\n renderFilePreview,\n}: FileSystemProps) {\n const [internalView, setInternalView] = React.useState(defaultView)\n const view = viewProp ?? internalView\n const setView = React.useCallback(\n (nextView: FileSystemView) => {\n setInternalView(nextView)\n onViewChange?.(nextView)\n },\n [onViewChange]\n )\n\n const [loadedItems, setLoadedItems] = React.useState<FileSystemItem[]>([])\n const allItems = React.useMemo(\n () => (loadedItems.length ? [...items, ...loadedItems] : items),\n [items, loadedItems]\n )\n const index = React.useMemo(() => buildFileSystemIndex(allItems), [allItems])\n\n const [history, setHistory] = React.useState(() => ({\n index: 0,\n stack: [normalizeFolderPath(defaultPath)],\n }))\n const currentPath = history.stack[history.index] ?? ""\n const canGoBack = history.index > 0\n const canGoForward = history.index < history.stack.length - 1\n\n const [selectedPath, setSelectedPath] = React.useState<string | null>(null)\n const selectedEntry = React.useMemo(() => {\n if (selectedPath === null) return null\n\n return (\n index.files.get(selectedPath) ?? index.folders.get(selectedPath) ?? null\n )\n }, [index, selectedPath])\n\n const selectEntry = React.useCallback(\n (entry: FileSystemEntry | null) => {\n setSelectedPath(entry?.path ?? null)\n onSelectionChange?.(entry)\n },\n [onSelectionChange]\n )\n\n // Below 480px the tabs view switcher no longer fits in the toolbar and\n // collapses into a select; below 360px the select label and the folder\n // name are dropped too, leaving icons only.\n const rootRef = React.useRef<HTMLDivElement | null>(null)\n const [headerLayout, setHeaderLayout] = React.useState<\n "full" | "compact" | "minimal"\n >("full")\n\n React.useEffect(() => {\n const root = rootRef.current\n\n if (!root || typeof ResizeObserver === "undefined") return\n\n const observer = new ResizeObserver((observerEntries) => {\n const width = observerEntries[0]?.contentRect.width\n\n if (width === undefined) return\n\n setHeaderLayout(\n width < 360 ? "minimal" : width < 480 ? "compact" : "full"\n )\n })\n\n observer.observe(root)\n return () => observer.disconnect()\n }, [])\n\n const requestedFoldersRef = React.useRef(new Set<string>())\n const [loadingFolders, setLoadingFolders] = React.useState<Set<string>>(\n () => new Set()\n )\n const ensureChildren = React.useCallback(\n (folderPath: string) => {\n if (!loadChildren) return\n\n const folder = index.folders.get(folderPath)\n\n if (!folder?.hasChildren) return\n if (index.children.get(folderPath)?.length) return\n if (requestedFoldersRef.current.has(folderPath)) return\n\n requestedFoldersRef.current.add(folderPath)\n setLoadingFolders((previous) => new Set(previous).add(folderPath))\n\n void (async () => {\n try {\n let cursor: string | null = null\n\n do {\n const result = await loadChildren({ cursor, path: folderPath })\n\n if (result.items.length) {\n setLoadedItems((previous) => [...previous, ...result.items])\n }\n cursor = result.nextCursor ?? null\n } while (cursor)\n } catch {\n requestedFoldersRef.current.delete(folderPath)\n } finally {\n setLoadingFolders((previous) => {\n const next = new Set(previous)\n\n next.delete(folderPath)\n return next\n })\n }\n })()\n },\n [index, loadChildren]\n )\n\n const navigateTo = React.useCallback(\n (folderPath: string) => {\n const path = normalizeFolderPath(folderPath)\n\n setHistory((previous) => {\n if (previous.stack[previous.index] === path) return previous\n\n const stack = [...previous.stack.slice(0, previous.index + 1), path]\n\n return { index: stack.length - 1, stack }\n })\n selectEntry(null)\n ensureChildren(path)\n },\n [ensureChildren, selectEntry]\n )\n\n React.useEffect(() => {\n ensureChildren(currentPath)\n }, [currentPath, ensureChildren])\n\n // Navigation unmounts the focused row, dropping focus to <body> and killing\n // the ⌘ shortcuts; reclaim focus onto the component root when that happens.\n const hasNavigatedRef = React.useRef(false)\n\n React.useEffect(() => {\n if (!hasNavigatedRef.current) {\n hasNavigatedRef.current = true\n return\n }\n\n const root = rootRef.current\n\n if (root && document.activeElement === document.body) {\n root.focus()\n }\n }, [currentPath])\n\n const [openedFile, setOpenedFile] = React.useState<{\n file: FileEntry\n kind: FileSystemViewerKind\n url: string\n } | null>(null)\n\n const openFile = React.useCallback(\n (file: FileEntry) => {\n void (async () => {\n let url = file.url ?? null\n\n if (!url && getFileUrl) {\n try {\n url = await getFileUrl(file)\n } catch {\n url = null\n }\n }\n if (onFileOpen) {\n onFileOpen(file, url)\n return\n }\n\n const kind = viewerKindForFile(file)\n\n if (kind && url) {\n setOpenedFile({ file, kind, url })\n } else if (url && typeof window !== "undefined") {\n window.open(url, "_blank", "noopener,noreferrer")\n }\n })()\n },\n [getFileUrl, onFileOpen]\n )\n\n const openEntry = React.useCallback(\n (entry: FileSystemEntry) => {\n if (entry.kind === "folder") {\n navigateTo(entry.path)\n } else {\n openFile(entry)\n }\n },\n [navigateTo, openFile]\n )\n\n // Selecting a lazy folder (columns view, keyboard nav) prefetches children.\n const selectAndPrefetchEntry = React.useCallback(\n (entry: FileSystemEntry | null) => {\n selectEntry(entry)\n if (entry?.kind === "folder") ensureChildren(entry.path)\n },\n [ensureChildren, selectEntry]\n )\n\n const goBack = React.useCallback(() => {\n setHistory((previous) => ({\n ...previous,\n index: Math.max(0, previous.index - 1),\n }))\n selectEntry(null)\n }, [selectEntry])\n\n const goForward = React.useCallback(() => {\n setHistory((previous) => ({\n ...previous,\n index: Math.min(previous.stack.length - 1, previous.index + 1),\n }))\n selectEntry(null)\n }, [selectEntry])\n\n const currentEntries = index.children.get(currentPath) ?? []\n const currentFolderName =\n currentPath === "" ? title : pathName(currentPath) || title\n const isLoadingCurrentFolder = loadingFolders.has(currentPath)\n\n const viewProps: FileSystemViewProps = {\n currentPath,\n entries: currentEntries,\n getFileUrl,\n index,\n loadPreviewImageUrl,\n loadingFolders,\n onOpen: openEntry,\n onSelect: selectAndPrefetchEntry,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n }\n\n const openedFileName = openedFile\n ? (openedFile.file.name ?? openedFile.file.path)\n : ""\n const activeViewOption = VIEW_OPTIONS.find((option) => option.value === view)\n const viewerCloseToolbarAction = (\n <DialogClose\n aria-label="Close preview"\n render={<Button type="button" variant="ghost" size="icon-sm" />}\n >\n <HugeiconsIcon icon={Cancel01Icon} className="size-4" />\n </DialogClose>\n )\n\n return (\n <div\n ref={rootRef}\n tabIndex={-1}\n className={cn(\n "flex h-[480px] min-h-0 flex-col overflow-hidden rounded-xl border bg-background text-foreground outline-none",\n className\n )}\n >\n <div className="grid h-12 shrink-0 grid-cols-[1fr_auto_1fr] items-center gap-2 border-b bg-muted/40 px-2">\n <div className="flex min-w-0 items-center gap-0.5">\n <button\n type="button"\n aria-label="Back"\n title="Back"\n disabled={!canGoBack}\n onClick={goBack}\n className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4.5" />\n </button>\n <button\n type="button"\n aria-label="Forward"\n title="Forward"\n disabled={!canGoForward}\n onClick={goForward}\n className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-4.5" />\n </button>\n {headerLayout !== "minimal" ? (\n <span className="ml-1.5 truncate text-sm font-semibold">\n {currentFolderName}\n </span>\n ) : null}\n </div>\n {headerLayout !== "full" ? (\n <Select\n value={view}\n onValueChange={(value) => setView(value as FileSystemView)}\n >\n <SelectTrigger\n size="sm"\n aria-label="View"\n className={cn(headerLayout !== "minimal" && "min-w-32")}\n >\n <SelectValue>\n {activeViewOption ? (\n <span className="flex items-center gap-2">\n <HugeiconsIcon\n icon={activeViewOption.icon}\n className="size-4"\n />\n {headerLayout !== "minimal" ? activeViewOption.label : null}\n </span>\n ) : null}\n </SelectValue>\n </SelectTrigger>\n <SelectContent>\n {VIEW_OPTIONS.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n <span className="flex items-center gap-2">\n <HugeiconsIcon icon={option.icon} className="size-4" />\n {option.label}\n </span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n ) : (\n <Tabs\n value={view}\n onValueChange={(value) => setView(value as FileSystemView)}\n className="gap-0"\n >\n <TabsList className="h-8 p-0.5">\n {VIEW_OPTIONS.map((option) => (\n <TabsTrigger\n key={option.value}\n value={option.value}\n aria-label={`${option.label} view`}\n title={option.label}\n className="h-7 grow-0 px-2.5 sm:h-7"\n >\n <HugeiconsIcon icon={option.icon} className="size-4" />\n </TabsTrigger>\n ))}\n </TabsList>\n </Tabs>\n )}\n <div />\n </div>\n <div className="relative min-h-0 flex-1">\n {isLoadingCurrentFolder && currentEntries.length === 0 ? (\n <FileSystemEmptyState label="Loading…" isLoading />\n ) : currentEntries.length === 0 && view !== "columns" ? (\n <FileSystemEmptyState label="This folder is empty" />\n ) : view === "icons" ? (\n <FileSystemIconsView {...viewProps} />\n ) : view === "list" ? (\n <FileSystemListView {...viewProps} />\n ) : view === "columns" ? (\n <FileSystemColumnsView {...viewProps} />\n ) : (\n <FileSystemGalleryView {...viewProps} />\n )}\n </div>\n <div\n aria-live="polite"\n className="flex h-7 shrink-0 items-center justify-center gap-1 border-t bg-muted/40 px-3 text-xs text-muted-foreground"\n >\n <span>\n {currentEntries.length}{" "}\n {currentEntries.length === 1 ? "item" : "items"}\n </span>\n {selectedEntry ? <span>· “{selectedEntry.name}” selected</span> : null}\n </div>\n <Dialog\n open={openedFile !== null}\n onOpenChange={(open) => {\n if (!open) setOpenedFile(null)\n }}\n >\n {openedFile ? (\n <DialogContent\n className={cn(\n "overflow-hidden p-0",\n VIEWER_DIALOG_CLASSNAMES[openedFile.kind]\n )}\n showCloseButton={openedFile.kind === "image"}\n >\n <DialogTitle className="sr-only">{openedFileName}</DialogTitle>\n {openedFile.kind === "pdf" ? (\n <PDFViewer\n file={openedFile.url}\n className="h-full min-h-0 flex-1 overflow-hidden rounded-2xl"\n downloadFileName={openedFileName}\n showUpload={false}\n toolbarActions={viewerCloseToolbarAction}\n />\n ) : openedFile.kind === "docx" ? (\n <DocxViewerPreview\n src={openedFile.url}\n fileName={openedFileName}\n className="h-full min-h-0 flex-1"\n rounded\n showUpload={false}\n toolbarActions={viewerCloseToolbarAction}\n />\n ) : openedFile.kind === "xlsx" ? (\n <XlsxViewerPreview\n src={openedFile.url}\n fileName={openedFileName}\n className="h-full min-h-0 flex-1"\n rounded\n showUpload={false}\n toolbarActions={viewerCloseToolbarAction}\n />\n ) : (\n <img\n src={openedFile.url}\n alt={openedFileName}\n className="max-h-[88vh] w-auto max-w-full rounded-2xl object-contain"\n />\n )}\n </DialogContent>\n ) : null}\n </Dialog>\n </div>\n )\n}\n\ntype FileSystemViewProps = {\n currentPath: string\n entries: FileSystemEntry[]\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n index: FileSystemIndex\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n loadingFolders: Set<string>\n onOpen: (entry: FileSystemEntry) => void\n onSelect: (entry: FileSystemEntry | null) => void\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n selectedEntry: FileSystemEntry | null\n selectedPath: string | null\n}\n\n// Resolves a display URL for a file: its own `url`, else via `getFileUrl`.\n// Keyed by path/url (not object identity) so manifest churn — e.g. thumbnails\n// streaming in — doesn\'t re-trigger presign calls for the same file.\nfunction useResolvedFileUrl(\n file: FileEntry | null,\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n) {\n const [state, setState] = React.useState<{\n isResolving: boolean\n url: string | null\n }>({ isResolving: false, url: file?.url ?? null })\n const fileRef = React.useRef(file)\n\n React.useEffect(() => {\n fileRef.current = file\n })\n\n const filePath = file?.path ?? null\n const fileUrl = file?.url ?? null\n\n React.useEffect(() => {\n const currentFile = fileRef.current\n\n if (!currentFile || fileUrl || !getFileUrl) {\n setState({ isResolving: false, url: fileUrl })\n return\n }\n\n let isCurrent = true\n\n setState({ isResolving: true, url: null })\n void Promise.resolve(getFileUrl(currentFile))\n .then((url) => {\n if (isCurrent) setState({ isResolving: false, url })\n })\n .catch(() => {\n if (isCurrent) setState({ isResolving: false, url: null })\n })\n\n return () => {\n isCurrent = false\n }\n }, [filePath, fileUrl, getFileUrl])\n\n return state\n}\n\n// Returns `value` once it has stopped changing for `delay` ms. Gallery\n// navigation scrubs past files quickly; heavy previews (document viewers,\n// presigned URL resolution) only kick in for the file the user lands on.\nfunction useSettledValue<T>(value: T, delay: number): T {\n const [settled, setSettled] = React.useState(value)\n\n React.useEffect(() => {\n if (Object.is(settled, value)) return\n\n const timeout = window.setTimeout(() => setSettled(value), delay)\n\n return () => window.clearTimeout(timeout)\n }, [delay, settled, value])\n\n return settled\n}\n\nfunction FileSystemEmptyState({\n label,\n isLoading = false,\n}: {\n label: string\n isLoading?: boolean\n}) {\n return (\n <div\n className={cn(\n "flex size-full items-center justify-center text-sm text-muted-foreground",\n isLoading && "animate-pulse motion-reduce:animate-none"\n )}\n >\n {label}\n </div>\n )\n}\n\nconst ARROW_KEYS = new Set(["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"])\n\n// Selects (and focuses) the entry reached by an arrow key. Up/down use row\n// geometry so navigation follows the rendered auto-fill grid.\nfunction moveGridSelection({\n entries,\n itemRefs,\n key,\n onSelect,\n selectedPath,\n}: {\n entries: FileSystemEntry[]\n itemRefs: Map<string, HTMLButtonElement>\n key: string\n onSelect: (entry: FileSystemEntry | null) => void\n selectedPath: string | null\n}) {\n if (entries.length === 0) return false\n\n const currentIndex = entries.findIndex((entry) => entry.path === selectedPath)\n let nextEntry: FileSystemEntry | undefined\n\n if (currentIndex === -1) {\n nextEntry = entries[0]\n } else if (key === "ArrowLeft" || key === "ArrowRight") {\n nextEntry = entries[currentIndex + (key === "ArrowLeft" ? -1 : 1)]\n } else {\n const currentElement = itemRefs.get(entries[currentIndex].path)\n\n if (!currentElement) return false\n\n const currentRect = currentElement.getBoundingClientRect()\n let bestScore = Infinity\n\n for (const entry of entries) {\n if (entry.path === selectedPath) continue\n\n const rect = itemRefs.get(entry.path)?.getBoundingClientRect()\n\n if (!rect) continue\n\n const rowDelta =\n key === "ArrowDown"\n ? rect.top - currentRect.top\n : currentRect.top - rect.top\n\n if (rowDelta <= 1) continue\n\n const score = rowDelta * 1000 + Math.abs(rect.left - currentRect.left)\n\n if (score < bestScore) {\n bestScore = score\n nextEntry = entry\n }\n }\n }\n\n if (!nextEntry) return false\n\n onSelect(nextEntry)\n itemRefs.get(nextEntry.path)?.focus()\n return true\n}\n\nfunction FileSystemIconsView({\n entries,\n onOpen,\n onSelect,\n renderFilePreview,\n selectedPath,\n}: FileSystemViewProps) {\n const itemRefs = React.useRef(new Map<string, HTMLButtonElement>())\n // Roving tabindex: the grid is a single tab stop (the selected tile, or the\n // first one), so Shift+Tab returns to the toolbar like in the list view.\n const tabStopPath = entries.some((entry) => entry.path === selectedPath)\n ? selectedPath\n : (entries[0]?.path ?? null)\n\n return (\n <ScrollArea\n orientation="vertical"\n viewportClassName="p-3"\n viewportProps={{\n onClick: (event) => {\n if (event.target === event.currentTarget) onSelect(null)\n },\n }}\n >\n <div\n role="listbox"\n aria-label="Files"\n className="grid grid-cols-[repeat(auto-fill,minmax(6.5rem,1fr))] gap-x-1 gap-y-3"\n onKeyDown={(event) => {\n if (!ARROW_KEYS.has(event.key)) return\n if (\n moveGridSelection({\n entries,\n itemRefs: itemRefs.current,\n key: event.key,\n onSelect,\n selectedPath,\n })\n ) {\n event.preventDefault()\n }\n }}\n >\n {entries.map((entry) => {\n const isSelected = entry.path === selectedPath\n\n return (\n <button\n key={entry.path}\n type="button"\n role="option"\n aria-selected={isSelected}\n tabIndex={entry.path === tabStopPath ? 0 : -1}\n ref={(element) => {\n if (element) {\n itemRefs.current.set(entry.path, element)\n } else {\n itemRefs.current.delete(entry.path)\n }\n }}\n onClick={() => onSelect(entry)}\n onDoubleClick={() => onOpen(entry)}\n onKeyDown={(event) => {\n if (event.key === "Enter") onOpen(entry)\n }}\n className="group flex flex-col items-center gap-1.5 outline-none"\n >\n <span\n className={cn(\n "flex h-16 w-20 items-center justify-center rounded-lg p-1 transition-colors group-focus-visible:ring-2 group-focus-visible:ring-ring",\n isSelected && "bg-accent"\n )}\n >\n {entry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-13 w-auto drop-shadow-sm" />\n ) : (\n <FileVisual\n file={entry}\n className={cn(\n "rounded-sm shadow-xs",\n // Landscape thumbnails get extra width so they fill\n // the tile instead of rendering as a short sliver.\n (entry.previewAspectRatio ?? 0.78) > 1.2\n ? "w-[4.75rem]"\n : "w-12"\n )}\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )}\n </span>\n <span\n className={cn(\n "max-w-full rounded-sm px-1.5 py-px text-center text-xs leading-tight break-words",\n isSelected\n ? "bg-primary text-primary-foreground"\n : "text-foreground"\n )}\n >\n <span className="line-clamp-2">{entry.name}</span>\n </span>\n </button>\n )\n })}\n </div>\n </ScrollArea>\n )\n}\n\nfunction FileSystemListView({\n currentPath,\n index,\n onOpen,\n onSelect,\n selectedPath,\n}: FileSystemViewProps) {\n const relativePaths = React.useMemo(() => {\n const paths: string[] = []\n\n for (const path of index.files.keys()) {\n if (currentPath === "" || path.startsWith(currentPath)) {\n const relativePath = path.slice(currentPath.length)\n\n if (relativePath) paths.push(relativePath)\n }\n }\n return paths.sort()\n }, [currentPath, index])\n // Content-derived key: the tree only remounts when the path set actually\n // changes (a bare length check misses same-count replacements).\n const treeKey = React.useMemo(\n () => hashString(relativePaths.join("\\n")),\n [relativePaths]\n )\n\n if (relativePaths.length === 0) {\n return <FileSystemEmptyState label="This folder is empty" />\n }\n\n return (\n <div className="flex size-full flex-col">\n {/* Paddings match the tree\'s row geometry: name text starts 46px in\n (16px tree padding + 30px icon lane), metadata ends 24px from the\n right (16px tree padding + 8px decoration inset). */}\n <div className="flex shrink-0 items-center border-b py-1.5 pr-6 pl-[46px] text-xs font-medium text-muted-foreground">\n <span className="flex-1">Name</span>\n <span className="w-44 text-right">Date Modified</span>\n <span className="w-20 text-right">Size</span>\n </div>\n <FileSystemPierreTree\n key={`${currentPath}::${treeKey}`}\n currentPath={currentPath}\n index={index}\n initialSelectedPath={\n selectedPath?.startsWith(currentPath)\n ? selectedPath.slice(currentPath.length).replace(/\\/$/, "")\n : null\n }\n onOpen={onOpen}\n onSelect={onSelect}\n relativePaths={relativePaths}\n />\n </div>\n )\n}\n\nfunction FileSystemPierreTree({\n currentPath,\n index,\n initialSelectedPath,\n onOpen,\n onSelect,\n relativePaths,\n}: {\n currentPath: string\n index: FileSystemIndex\n initialSelectedPath: string | null\n onOpen: (entry: FileSystemEntry) => void\n onSelect: (entry: FileSystemEntry | null) => void\n relativePaths: string[]\n}) {\n const preparedInput = React.useMemo(\n () => prepareFileTreeInput(relativePaths, { sort: "default" }),\n [relativePaths]\n )\n // Inject per-file thumbnails into the tree\'s shadow DOM as sprite symbols\n // wrapping an <image>, remapped onto rows by file basename. The chevron is\n // remapped to the Hugeicons arrow so it matches the rest of the component;\n // the tree\'s rotation CSS keys off data-icon-name, which remapping keeps.\n const icons = React.useMemo(() => {\n const byFileName: Record<string, { name: string; viewBox: string }> = {}\n const symbols: string[] = [\n `<symbol id="file-system-chevron" viewBox="0 0 24 24"><path d="M18 9.00005C18 9.00005 13.5811 15 12 15C10.4188 15 6 9 6 9" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"/></symbol>`,\n ]\n\n for (const relativePath of relativePaths) {\n const file = index.files.get(`${currentPath}${relativePath}`)\n const coverUrl = file ? filePreviewUrls(file)[0] : undefined\n\n if (!file || !coverUrl) continue\n\n const baseName = file.name.toLowerCase()\n\n if (byFileName[baseName]) continue\n\n const symbolId = `file-system-thumbnail-${symbols.length}`\n\n symbols.push(\n `<symbol id="${symbolId}" viewBox="0 0 16 16"><clipPath id="${symbolId}-clip"><rect width="16" height="16" rx="2.5"/></clipPath><image href="${escapeXmlAttribute(coverUrl)}" width="16" height="16" preserveAspectRatio="xMidYMid slice" clip-path="url(#${symbolId}-clip)"/></symbol>`\n )\n byFileName[baseName] = { name: symbolId, viewBox: "0 0 16 16" }\n }\n\n return {\n byFileName,\n remap: {\n "file-tree-icon-chevron": {\n name: "file-system-chevron",\n viewBox: "0 0 24 24",\n },\n },\n spriteSheet: `<svg data-icon-sprite aria-hidden="true" width="0" height="0">${symbols.join("")}</svg>`,\n }\n }, [currentPath, index, relativePaths])\n const { model } = useFileTree({\n flattenEmptyDirectories: false,\n icons,\n initialExpansion: "closed",\n initialSelectedPaths: initialSelectedPath ? [initialSelectedPath] : [],\n itemHeight: 28,\n overscan: 12,\n preparedInput,\n renderRowDecoration: ({ row }) => {\n const entry =\n row.kind === "file"\n ? index.files.get(`${currentPath}${row.path}`)\n : index.folders.get(normalizeFolderPath(`${currentPath}${row.path}`))\n\n if (!entry) return null\n\n // The decoration lane renders one <span title>; CSS splits it into\n // aligned Date Modified (::before from title) and Size columns.\n const dateColumn =\n formatTimestamp(entry.updatedAt ?? entry.createdAt) ?? "—"\n\n if (entry.kind === "folder") {\n const childCount = index.children.get(entry.path)?.length\n\n return {\n text:\n childCount === undefined\n ? "—"\n : `${childCount} ${childCount === 1 ? "item" : "items"}`,\n title: dateColumn,\n }\n }\n\n return { text: formatByteSize(entry.size) ?? "—", title: dateColumn }\n },\n unsafeCSS: `\n button[data-type=\'item\']:not([data-item-selected]):hover {\n background: color-mix(in oklab, var(--color-accent) 50%, transparent);\n }\n button[data-type=\'item\'][data-item-selected] {\n background: var(--color-primary);\n color: var(--color-primary-foreground);\n }\n button[data-type=\'item\'][data-item-selected] *,\n button[data-type=\'item\'][data-item-selected] [data-item-section]::before,\n button[data-type=\'item\'][data-item-selected] svg {\n color: var(--color-primary-foreground) !important;\n }\n [data-item-section=\'decoration\'] > span {\n display: grid;\n grid-template-columns: 11rem 5rem;\n justify-items: end;\n white-space: nowrap;\n }\n [data-item-section=\'decoration\'] > span::before {\n content: attr(title);\n }\n button[data-type=\'item\'][data-item-type=\'folder\'] [data-item-section=\'content\'] {\n display: flex;\n align-items: center;\n min-width: 0;\n }\n button[data-type=\'item\'][data-item-type=\'folder\'] [data-item-section=\'content\']::before {\n content: "";\n flex: none;\n width: 18px;\n height: 14px;\n margin-right: 4px;\n background: url("${FOLDER_GLYPH_DATA_URL}") center / contain no-repeat;\n }\n `,\n onSelectionChange: (selectedPaths) => {\n const relativePath = selectedPaths[0]\n\n if (!relativePath) {\n onSelect(null)\n return\n }\n\n const absolutePath = `${currentPath}${relativePath}`\n const entry =\n index.files.get(absolutePath) ??\n index.folders.get(normalizeFolderPath(absolutePath)) ??\n null\n\n onSelect(entry)\n },\n })\n\n // Thumbnails can resolve after mount (e.g. generated client-side); push\n // sprite updates into the existing model instead of remounting the tree.\n React.useEffect(() => {\n model.setIcons(icons)\n }, [icons, model])\n\n // The tree\'s arrow keys move focus and only select on click/Enter; mirror\n // focus into the (single) selection so arrowing selects like Finder. Shift\n // ranges keep the focused row selected, so they pass through untouched.\n React.useEffect(() => {\n let lastFocusedPath = model.getFocusedPath()\n\n return model.subscribe(() => {\n const focusedPath = model.getFocusedPath()\n\n if (focusedPath === lastFocusedPath) return\n\n lastFocusedPath = focusedPath\n\n if (!focusedPath) return\n\n const item = model.getItem(focusedPath)\n\n if (!item || item.isSelected()) return\n\n for (const path of model.getSelectedPaths()) {\n model.getItem(path)?.deselect()\n }\n item.select()\n })\n }, [model])\n\n return (\n <PierreFileTree\n model={model}\n className="block min-h-0 flex-1"\n onDoubleClick={(event) => {\n // Rows live in the tree\'s shadow DOM; composedPath surfaces the row\n // element so double-clicked files open like in the other views.\n for (const target of event.nativeEvent.composedPath()) {\n if (!(target instanceof HTMLElement)) continue\n const relativePath = target.dataset?.itemPath\n if (!relativePath) continue\n\n const file = index.files.get(`${currentPath}${relativePath}`)\n\n if (file) onOpen(file)\n return\n }\n }}\n style={\n {\n "--trees-bg-override": "transparent",\n "--trees-border-color-override": "var(--color-border)",\n "--trees-fg-override": "var(--color-foreground)",\n // Match the focus-visible ring used by the tabs and the other\n // views (`ring-2 ring-ring`) instead of the tree\'s accent blue.\n "--trees-focus-ring-color-override": "var(--color-ring)",\n "--trees-focus-ring-width-override": "2px",\n "--trees-selected-bg-override": "var(--color-primary)",\n "--trees-selected-focused-border-color-override": "var(--color-ring)",\n } as React.CSSProperties\n }\n />\n )\n}\n\nfunction FileSystemColumnsView(props: FileSystemViewProps) {\n const {\n currentPath,\n index,\n loadPreviewImageUrl,\n loadingFolders,\n onOpen,\n onSelect,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n } = props\n const scrollContainerRef = React.useRef<HTMLDivElement | null>(null)\n const rowRefs = React.useRef(new Map<string, HTMLButtonElement>())\n\n // The selection highlight tracks every keypress; mounting the trailing\n // child column and the preview pane is deferred so holding an arrow key\n // doesn\'t pay that DOM churn per step.\n const deferredSelectedEntry = React.useDeferredValue(selectedEntry)\n const deferredSelectedPath = React.useDeferredValue(selectedPath)\n const pendingFocusPathRef = React.useRef<string | null>(null)\n\n const handleKeyDown = (event: React.KeyboardEvent) => {\n if (!ARROW_KEYS.has(event.key)) return\n\n let nextEntry: FileSystemEntry | null | undefined\n\n if (!selectedEntry || !selectedPath?.startsWith(currentPath)) {\n nextEntry = index.children.get(currentPath)?.[0]\n } else if (event.key === "ArrowUp" || event.key === "ArrowDown") {\n const siblings = index.children.get(selectedEntry.parentPath) ?? []\n const currentIndex = siblings.findIndex(\n (sibling) => sibling.path === selectedEntry.path\n )\n\n nextEntry = siblings[currentIndex + (event.key === "ArrowUp" ? -1 : 1)]\n } else if (event.key === "ArrowLeft") {\n if (selectedEntry.parentPath !== currentPath) {\n nextEntry = index.folders.get(selectedEntry.parentPath)\n }\n } else if (selectedEntry.kind === "folder") {\n nextEntry = index.children.get(selectedEntry.path)?.[0]\n }\n\n if (!nextEntry) return\n\n onSelect(nextEntry)\n\n const row = rowRefs.current.get(nextEntry.path)\n\n if (row) {\n pendingFocusPathRef.current = null\n row.focus()\n } else {\n // The target row lives in a deferred column that hasn\'t mounted yet;\n // focus it from the effect below once it exists.\n pendingFocusPathRef.current = nextEntry.path\n }\n event.preventDefault()\n }\n\n React.useEffect(() => {\n const path = pendingFocusPathRef.current\n\n if (!path) return\n\n const row = rowRefs.current.get(path)\n\n if (row) {\n pendingFocusPathRef.current = null\n row.focus()\n }\n })\n\n const columnPaths = React.useMemo(() => {\n const paths = [currentPath]\n\n if (!deferredSelectedPath?.startsWith(currentPath)) return paths\n\n const targetFolder =\n deferredSelectedEntry?.kind === "folder"\n ? deferredSelectedEntry.path\n : (deferredSelectedEntry?.parentPath ?? currentPath)\n const relativePath = targetFolder.slice(currentPath.length)\n let walkedPath = currentPath\n\n for (const segment of relativePath.split("/")) {\n if (!segment) continue\n walkedPath = `${walkedPath}${segment}/`\n paths.push(walkedPath)\n }\n return paths\n }, [currentPath, deferredSelectedEntry, deferredSelectedPath])\n const columnPathSet = React.useMemo(() => new Set(columnPaths), [columnPaths])\n // Roving tabindex: all columns together form a single tab stop (the\n // selected row when its column is mounted, else the first row), so\n // Shift+Tab returns to the toolbar like in the list view.\n const tabStopPath = React.useMemo(() => {\n if (selectedPath) {\n for (const columnPath of columnPaths) {\n if (\n index.children\n .get(columnPath)\n ?.some((entry) => entry.path === selectedPath)\n ) {\n return selectedPath\n }\n }\n }\n return index.children.get(columnPaths[0] ?? "")?.[0]?.path ?? null\n }, [columnPaths, index, selectedPath])\n const selectedFile =\n deferredSelectedEntry?.kind === "file"\n ? (deferredSelectedEntry as FileEntry)\n : null\n const selectedFileSize = selectedFile\n ? formatByteSize(selectedFile.size)\n : null\n\n React.useEffect(() => {\n const container = scrollContainerRef.current\n\n if (container) container.scrollLeft = container.scrollWidth\n }, [columnPaths.length, deferredSelectedPath])\n\n return (\n <ScrollArea\n orientation="horizontal"\n viewportRef={scrollContainerRef}\n viewportClassName="overscroll-x-contain"\n >\n <div className="flex h-full w-max min-w-full" onKeyDown={handleKeyDown}>\n {columnPaths.map((columnPath) => (\n <ScrollArea\n key={columnPath || "(root)"}\n orientation="vertical"\n className="w-60 shrink-0 border-r"\n viewportClassName="flex flex-col gap-px p-1.5"\n viewportProps={{ "aria-label": "Files", role: "listbox" }}\n >\n {loadingFolders.has(columnPath) &&\n !index.children.get(columnPath)?.length ? (\n <div className="animate-pulse px-2 py-1.5 text-xs text-muted-foreground motion-reduce:animate-none">\n Loading…\n </div>\n ) : (\n (index.children.get(columnPath) ?? []).map((entry) => {\n const isSelected = entry.path === selectedPath\n const isOnTrail =\n entry.kind === "folder" && columnPathSet.has(entry.path)\n\n const coverUrl =\n entry.kind === "file" ? filePreviewUrls(entry)[0] : undefined\n\n return (\n <button\n key={entry.path}\n type="button"\n role="option"\n aria-selected={isSelected}\n tabIndex={entry.path === tabStopPath ? 0 : -1}\n ref={(element) => {\n if (element) {\n rowRefs.current.set(entry.path, element)\n } else {\n rowRefs.current.delete(entry.path)\n }\n }}\n onClick={() => onSelect(entry)}\n onDoubleClick={() => onOpen(entry)}\n onKeyDown={(event) => {\n if (event.key === "Enter") onOpen(entry)\n }}\n className={cn(\n "flex shrink-0 items-center gap-2 rounded-md px-2 py-1 text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",\n isSelected\n ? "bg-primary text-primary-foreground"\n : isOnTrail\n ? "bg-accent"\n : "hover:bg-accent/50"\n )}\n >\n {entry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-3.5 w-auto shrink-0" />\n ) : coverUrl ? (\n <img\n src={coverUrl}\n alt=""\n draggable={false}\n className="size-4 shrink-0 rounded-[3px] bg-white object-cover"\n />\n ) : (\n <HugeiconsIcon\n icon={File01Icon}\n className={cn(\n "size-4 shrink-0",\n !isSelected && "text-muted-foreground"\n )}\n />\n )}\n <span className="min-w-0 flex-1 truncate">\n {entry.name}\n </span>\n {entry.kind === "folder" &&\n folderHasChildren(index, entry) ? (\n <HugeiconsIcon\n icon={ArrowRight01Icon}\n className={cn(\n "size-3.5 shrink-0",\n !isSelected && "text-muted-foreground/60"\n )}\n />\n ) : null}\n </button>\n )\n })\n )}\n </ScrollArea>\n ))}\n {selectedFile ? (\n <ScrollArea\n orientation="vertical"\n className="min-w-72 flex-1"\n viewportClassName="flex justify-center p-4"\n >\n <div className="flex w-full max-w-lg flex-col items-stretch gap-3">\n {/* Width derives from the aspect ratio so the thumbnail grows\n with the pane up to a 20rem height cap. */}\n <div\n className="mx-auto w-full shrink-0"\n style={{\n maxWidth: `min(100%, ${(selectedFile.previewAspectRatio ?? 0.78) * 20}rem)`,\n }}\n >\n <FileVisual\n file={selectedFile}\n className="w-full"\n loadPreviewImageUrl={loadPreviewImageUrl}\n pageable\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n </div>\n <div className="text-center">\n <div className="text-sm font-semibold break-words">\n {selectedFile.name}\n </div>\n <div className="text-xs text-muted-foreground">\n {fileKindLabel(selectedFile)}\n {selectedFileSize ? ` - ${selectedFileSize}` : null}\n </div>\n </div>\n <FileSystemInformation entry={selectedFile} index={index} />\n </div>\n </ScrollArea>\n ) : null}\n </div>\n </ScrollArea>\n )\n}\n\nfunction FileSystemInformation({\n entry,\n index,\n}: {\n entry: FileSystemEntry\n index: FileSystemIndex\n}) {\n const rows: Array<[string, string]> = []\n const created = formatTimestamp(entry.createdAt)\n const updated = formatTimestamp(entry.updatedAt)\n\n if (created) rows.push(["Created", created])\n if (updated) rows.push(["Modified", updated])\n if (entry.kind === "file") {\n const size = formatByteSize(entry.size)\n\n if (size) rows.push(["Size", size])\n } else {\n const childCount = index.children.get(entry.path)?.length\n\n if (childCount !== undefined) {\n rows.push(["Items", `${childCount}`])\n }\n }\n\n if (rows.length === 0) return null\n\n return (\n <div className="border-t pt-3">\n <div className="mb-1.5 text-xs font-semibold">Information</div>\n <dl className="space-y-1">\n {rows.map(([label, value]) => (\n <div\n key={label}\n className="flex items-baseline justify-between gap-3 text-xs"\n >\n <dt className="shrink-0 text-muted-foreground">{label}</dt>\n <dd className="text-right" suppressHydrationWarning>\n {value}\n </dd>\n </div>\n ))}\n </dl>\n </div>\n )\n}\n\nfunction FileSystemGalleryView(props: FileSystemViewProps) {\n const {\n entries,\n getFileUrl,\n index,\n loadPreviewImageUrl,\n onOpen,\n onSelect,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n } = props\n const stripRefs = React.useRef(new Map<string, HTMLButtonElement>())\n const activeEntry =\n selectedEntry && entries.some((entry) => entry.path === selectedEntry.path)\n ? selectedEntry\n : (entries[0] ?? null)\n const activeFile = activeEntry?.kind === "file" ? activeEntry : null\n const activeViewerKind = activeFile ? viewerKindForFile(activeFile) : null\n // While arrow keys are scrubbing the strip, the center pane shows a\n // spinner; the full-size viewer (and its URL resolution) mounts once the\n // selection settles so each keystroke stays cheap.\n const settledPath = useSettledValue(activeEntry?.path ?? null, 200)\n const isSettled = settledPath === (activeEntry?.path ?? null)\n const { isResolving, url: activeFileUrl } = useResolvedFileUrl(\n isSettled ? activeFile : null,\n getFileUrl\n )\n const isStageLoading =\n activeFile !== null &&\n (!isSettled || (activeViewerKind !== null && isResolving))\n const activeFileSize = activeFile ? formatByteSize(activeFile.size) : null\n\n const handleKeyDown = (event: React.KeyboardEvent) => {\n if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return\n if (entries.length === 0) return\n\n const currentIndex = activeEntry\n ? entries.findIndex((entry) => entry.path === activeEntry.path)\n : -1\n const nextEntry =\n entries[\n currentIndex === -1\n ? 0\n : currentIndex + (event.key === "ArrowLeft" ? -1 : 1)\n ]\n\n if (!nextEntry) return\n\n onSelect(nextEntry)\n stripRefs.current.get(nextEntry.path)?.focus()\n event.preventDefault()\n }\n\n return (\n <div className="flex size-full flex-col" onKeyDown={handleKeyDown}>\n {/* The strip comes first in DOM order (rendered below via order-last)\n so the filmstrip is the view\'s single tab stop: Shift+Tab exits to\n the toolbar instead of landing inside the embedded viewers. */}\n <ScrollArea\n orientation="horizontal"\n className="order-last h-auto w-full shrink-0 border-t"\n >\n <div\n role="listbox"\n aria-label="Files"\n className="flex w-max min-w-full items-center gap-1.5 p-2"\n >\n {entries.map((entry) => {\n const isActive = entry.path === (activeEntry?.path ?? selectedPath)\n\n return (\n <button\n key={entry.path}\n type="button"\n role="option"\n aria-selected={isActive}\n tabIndex={isActive ? 0 : -1}\n ref={(element) => {\n if (element) {\n stripRefs.current.set(entry.path, element)\n } else {\n stripRefs.current.delete(entry.path)\n }\n }}\n onClick={() => onSelect(entry)}\n onDoubleClick={() => onOpen(entry)}\n onKeyDown={(event) => {\n if (event.key === "Enter") onOpen(entry)\n }}\n title={entry.name}\n className={cn(\n "flex size-14 shrink-0 items-center justify-center rounded-md border border-transparent p-1 outline-none focus-visible:ring-2 focus-visible:ring-ring",\n isActive && "border-ring/40 bg-accent"\n )}\n >\n {entry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-9 w-auto" />\n ) : (\n <FileVisual\n file={entry}\n className="w-9 rounded-sm"\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )}\n </button>\n )\n })}\n </div>\n </ScrollArea>\n <div className="flex min-h-0 flex-1">\n <div className="flex min-h-0 min-w-0 flex-1 items-center justify-center p-3">\n {activeEntry ? (\n activeEntry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-40 max-h-full w-auto drop-shadow-md" />\n ) : isStageLoading ? (\n <Spinner className="size-6 text-muted-foreground" />\n ) : activeViewerKind === "image" && activeFileUrl ? (\n <img\n src={activeFileUrl}\n alt={activeEntry.name}\n className="max-h-full max-w-full rounded-lg object-contain"\n />\n ) : activeViewerKind === "pdf" && activeFileUrl ? (\n <div className="size-full overflow-hidden rounded-lg border">\n <PDFViewer\n key={activeEntry.path}\n file={activeFileUrl}\n className="h-full"\n showToolbar={false}\n />\n </div>\n ) : activeViewerKind === "docx" && activeFileUrl ? (\n <div className="size-full overflow-hidden rounded-lg border">\n <DocxViewerPreview\n key={activeEntry.path}\n src={activeFileUrl}\n fileName={activeEntry.name}\n className="h-full"\n showToolbar={false}\n />\n </div>\n ) : activeViewerKind === "xlsx" && activeFileUrl ? (\n <div className="size-full overflow-hidden rounded-lg border">\n <XlsxViewerPreview\n key={activeEntry.path}\n src={activeFileUrl}\n fileName={activeEntry.name}\n className="h-full"\n showToolbar={false}\n />\n </div>\n ) : (\n <FileVisual\n file={activeEntry}\n className="w-56 max-w-full"\n loadPreviewImageUrl={loadPreviewImageUrl}\n pageable\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )\n ) : null}\n </div>\n {activeEntry ? (\n <ScrollArea\n orientation="vertical"\n className="hidden w-64 shrink-0 border-l sm:block"\n viewportClassName="flex flex-col gap-3 p-4"\n >\n <div className="flex items-center gap-3">\n {activeFile ? (\n <FileVisual\n file={activeFile}\n className={cn(\n "shrink-0 rounded-sm",\n (activeFile.previewAspectRatio ?? 0.78) > 1.2\n ? "w-16"\n : "w-9"\n )}\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n ) : (\n <FileSystemFolderGlyph className="h-8 w-auto shrink-0" />\n )}\n <div className="min-w-0 flex-1">\n <div className="text-sm font-semibold break-words">\n {activeEntry.name}\n </div>\n <div className="text-xs text-muted-foreground">\n {activeFile ? fileKindLabel(activeFile) : "Folder"}\n {activeFileSize ? ` - ${activeFileSize}` : null}\n </div>\n </div>\n </div>\n <FileSystemInformation entry={activeEntry} index={index} />\n </ScrollArea>\n ) : null}\n </div>\n </div>\n )\n}\n'
export function FileSystemSourceCode() {
return (
diff --git a/apps/v4/components/ui/file-system.tsx b/apps/v4/components/ui/file-system.tsx
index 3b16881..16c20c2 100644
--- a/apps/v4/components/ui/file-system.tsx
+++ b/apps/v4/components/ui/file-system.tsx
@@ -34,6 +34,7 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
+import { Spinner } from "@/components/ui/spinner"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { XlsxViewerPreview } from "@/components/ui/xlsx-viewer"
@@ -500,6 +501,7 @@ function FileVisual({
<button
type="button"
aria-label="Previous page"
+ tabIndex={-1}
disabled={clampedPageIndex === 0}
onClick={(event) => {
event.stopPropagation()
@@ -516,6 +518,7 @@ function FileVisual({
<button
type="button"
aria-label="Next page"
+ tabIndex={-1}
disabled={clampedPageIndex >= totalPages - 1}
onClick={(event) => {
event.stopPropagation()
@@ -599,9 +602,13 @@ export function FileSystem({
[onSelectionChange]
)
- // Below this width the tabs view switcher no longer fits in the toolbar.
+ // Below 480px the tabs view switcher no longer fits in the toolbar and
+ // collapses into a select; below 360px the select label and the folder
+ // name are dropped too, leaving icons only.
const rootRef = React.useRef<HTMLDivElement | null>(null)
- const [isCompact, setIsCompact] = React.useState(false)
+ const [headerLayout, setHeaderLayout] = React.useState<
+ "full" | "compact" | "minimal"
+ >("full")
React.useEffect(() => {
const root = rootRef.current
@@ -611,7 +618,11 @@ export function FileSystem({
const observer = new ResizeObserver((observerEntries) => {
const width = observerEntries[0]?.contentRect.width
- if (width !== undefined) setIsCompact(width < 480)
+ if (width === undefined) return
+
+ setHeaderLayout(
+ width < 360 ? "minimal" : width < 480 ? "compact" : "full"
+ )
})
observer.observe(root)
@@ -834,16 +845,22 @@ export function FileSystem({
>
<HugeiconsIcon icon={ArrowRight01Icon} className="size-4.5" />
</button>
- <span className="ml-1.5 truncate text-sm font-semibold">
- {currentFolderName}
- </span>
+ {headerLayout !== "minimal" ? (
+ <span className="ml-1.5 truncate text-sm font-semibold">
+ {currentFolderName}
+ </span>
+ ) : null}
</div>
- {isCompact ? (
+ {headerLayout !== "full" ? (
<Select
value={view}
onValueChange={(value) => setView(value as FileSystemView)}
>
- <SelectTrigger size="sm" aria-label="View" className="min-w-32">
+ <SelectTrigger
+ size="sm"
+ aria-label="View"
+ className={cn(headerLayout !== "minimal" && "min-w-32")}
+ >
<SelectValue>
{activeViewOption ? (
<span className="flex items-center gap-2">
@@ -851,7 +868,7 @@ export function FileSystem({
icon={activeViewOption.icon}
className="size-4"
/>
- {activeViewOption.label}
+ {headerLayout !== "minimal" ? activeViewOption.label : null}
</span>
) : null}
</SelectValue>
@@ -994,9 +1011,10 @@ function useResolvedFileUrl(
file: FileEntry | null,
getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>
) {
- const [resolvedUrl, setResolvedUrl] = React.useState<string | null>(
- file?.url ?? null
- )
+ const [state, setState] = React.useState<{
+ isResolving: boolean
+ url: string | null
+ }>({ isResolving: false, url: file?.url ?? null })
const fileRef = React.useRef(file)
React.useEffect(() => {
@@ -1009,30 +1027,45 @@ function useResolvedFileUrl(
React.useEffect(() => {
const currentFile = fileRef.current
- if (!currentFile || fileUrl) {
- setResolvedUrl(fileUrl)
- return
- }
- if (!getFileUrl) {
- setResolvedUrl(null)
+ if (!currentFile || fileUrl || !getFileUrl) {
+ setState({ isResolving: false, url: fileUrl })
return
}
let isCurrent = true
- setResolvedUrl(null)
+ setState({ isResolving: true, url: null })
void Promise.resolve(getFileUrl(currentFile))
.then((url) => {
- if (isCurrent) setResolvedUrl(url)
+ if (isCurrent) setState({ isResolving: false, url })
+ })
+ .catch(() => {
+ if (isCurrent) setState({ isResolving: false, url: null })
})
- .catch(() => {})
return () => {
isCurrent = false
}
}, [filePath, fileUrl, getFileUrl])
- return resolvedUrl
+ return state
+}
+
+// Returns `value` once it has stopped changing for `delay` ms. Gallery
+// navigation scrubs past files quickly; heavy previews (document viewers,
+// presigned URL resolution) only kick in for the file the user lands on.
+function useSettledValue<T>(value: T, delay: number): T {
+ const [settled, setSettled] = React.useState(value)
+
+ React.useEffect(() => {
+ if (Object.is(settled, value)) return
+
+ const timeout = window.setTimeout(() => setSettled(value), delay)
+
+ return () => window.clearTimeout(timeout)
+ }, [delay, settled, value])
+
+ return settled
}
function FileSystemEmptyState({
@@ -1126,6 +1159,11 @@ function FileSystemIconsView({
selectedPath,
}: FileSystemViewProps) {
const itemRefs = React.useRef(new Map<string, HTMLButtonElement>())
+ // Roving tabindex: the grid is a single tab stop (the selected tile, or the
+ // first one), so Shift+Tab returns to the toolbar like in the list view.
+ const tabStopPath = entries.some((entry) => entry.path === selectedPath)
+ ? selectedPath
+ : (entries[0]?.path ?? null)
return (
<ScrollArea
@@ -1165,6 +1203,7 @@ function FileSystemIconsView({
type="button"
role="option"
aria-selected={isSelected}
+ tabIndex={entry.path === tabStopPath ? 0 : -1}
ref={(element) => {
if (element) {
itemRefs.current.set(entry.path, element)
@@ -1431,6 +1470,32 @@ function FileSystemPierreTree({
model.setIcons(icons)
}, [icons, model])
+ // The tree's arrow keys move focus and only select on click/Enter; mirror
+ // focus into the (single) selection so arrowing selects like Finder. Shift
+ // ranges keep the focused row selected, so they pass through untouched.
+ React.useEffect(() => {
+ let lastFocusedPath = model.getFocusedPath()
+
+ return model.subscribe(() => {
+ const focusedPath = model.getFocusedPath()
+
+ if (focusedPath === lastFocusedPath) return
+
+ lastFocusedPath = focusedPath
+
+ if (!focusedPath) return
+
+ const item = model.getItem(focusedPath)
+
+ if (!item || item.isSelected()) return
+
+ for (const path of model.getSelectedPaths()) {
+ model.getItem(path)?.deselect()
+ }
+ item.select()
+ })
+ }, [model])
+
return (
<PierreFileTree
model={model}
@@ -1454,7 +1519,12 @@ function FileSystemPierreTree({
"--trees-bg-override": "transparent",
"--trees-border-color-override": "var(--color-border)",
"--trees-fg-override": "var(--color-foreground)",
+ // Match the focus-visible ring used by the tabs and the other
+ // views (`ring-2 ring-ring`) instead of the tree's accent blue.
+ "--trees-focus-ring-color-override": "var(--color-ring)",
+ "--trees-focus-ring-width-override": "2px",
"--trees-selected-bg-override": "var(--color-primary)",
+ "--trees-selected-focused-border-color-override": "var(--color-ring)",
} as React.CSSProperties
}
/>
@@ -1476,6 +1546,13 @@ function FileSystemColumnsView(props: FileSystemViewProps) {
const scrollContainerRef = React.useRef<HTMLDivElement | null>(null)
const rowRefs = React.useRef(new Map<string, HTMLButtonElement>())
+ // The selection highlight tracks every keypress; mounting the trailing
+ // child column and the preview pane is deferred so holding an arrow key
+ // doesn't pay that DOM churn per step.
+ const deferredSelectedEntry = React.useDeferredValue(selectedEntry)
+ const deferredSelectedPath = React.useDeferredValue(selectedPath)
+ const pendingFocusPathRef = React.useRef<string | null>(null)
+
const handleKeyDown = (event: React.KeyboardEvent) => {
if (!ARROW_KEYS.has(event.key)) return
@@ -1501,19 +1578,42 @@ function FileSystemColumnsView(props: FileSystemViewProps) {
if (!nextEntry) return
onSelect(nextEntry)
- rowRefs.current.get(nextEntry.path)?.focus()
+
+ const row = rowRefs.current.get(nextEntry.path)
+
+ if (row) {
+ pendingFocusPathRef.current = null
+ row.focus()
+ } else {
+ // The target row lives in a deferred column that hasn't mounted yet;
+ // focus it from the effect below once it exists.
+ pendingFocusPathRef.current = nextEntry.path
+ }
event.preventDefault()
}
+ React.useEffect(() => {
+ const path = pendingFocusPathRef.current
+
+ if (!path) return
+
+ const row = rowRefs.current.get(path)
+
+ if (row) {
+ pendingFocusPathRef.current = null
+ row.focus()
+ }
+ })
+
const columnPaths = React.useMemo(() => {
const paths = [currentPath]
- if (!selectedPath?.startsWith(currentPath)) return paths
+ if (!deferredSelectedPath?.startsWith(currentPath)) return paths
const targetFolder =
- selectedEntry?.kind === "folder"
- ? selectedEntry.path
- : (selectedEntry?.parentPath ?? currentPath)
+ deferredSelectedEntry?.kind === "folder"
+ ? deferredSelectedEntry.path
+ : (deferredSelectedEntry?.parentPath ?? currentPath)
const relativePath = targetFolder.slice(currentPath.length)
let walkedPath = currentPath
@@ -1523,10 +1623,29 @@ function FileSystemColumnsView(props: FileSystemViewProps) {
paths.push(walkedPath)
}
return paths
- }, [currentPath, selectedEntry, selectedPath])
+ }, [currentPath, deferredSelectedEntry, deferredSelectedPath])
const columnPathSet = React.useMemo(() => new Set(columnPaths), [columnPaths])
+ // Roving tabindex: all columns together form a single tab stop (the
+ // selected row when its column is mounted, else the first row), so
+ // Shift+Tab returns to the toolbar like in the list view.
+ const tabStopPath = React.useMemo(() => {
+ if (selectedPath) {
+ for (const columnPath of columnPaths) {
+ if (
+ index.children
+ .get(columnPath)
+ ?.some((entry) => entry.path === selectedPath)
+ ) {
+ return selectedPath
+ }
+ }
+ }
+ return index.children.get(columnPaths[0] ?? "")?.[0]?.path ?? null
+ }, [columnPaths, index, selectedPath])
const selectedFile =
- selectedEntry?.kind === "file" ? (selectedEntry as FileEntry) : null
+ deferredSelectedEntry?.kind === "file"
+ ? (deferredSelectedEntry as FileEntry)
+ : null
const selectedFileSize = selectedFile
? formatByteSize(selectedFile.size)
: null
@@ -1535,7 +1654,7 @@ function FileSystemColumnsView(props: FileSystemViewProps) {
const container = scrollContainerRef.current
if (container) container.scrollLeft = container.scrollWidth
- }, [columnPaths.length, selectedPath])
+ }, [columnPaths.length, deferredSelectedPath])
return (
<ScrollArea
@@ -1572,6 +1691,7 @@ function FileSystemColumnsView(props: FileSystemViewProps) {
type="button"
role="option"
aria-selected={isSelected}
+ tabIndex={entry.path === tabStopPath ? 0 : -1}
ref={(element) => {
if (element) {
rowRefs.current.set(entry.path, element)
@@ -1738,7 +1858,18 @@ function FileSystemGalleryView(props: FileSystemViewProps) {
: (entries[0] ?? null)
const activeFile = activeEntry?.kind === "file" ? activeEntry : null
const activeViewerKind = activeFile ? viewerKindForFile(activeFile) : null
- const activeFileUrl = useResolvedFileUrl(activeFile, getFileUrl)
+ // While arrow keys are scrubbing the strip, the center pane shows a
+ // spinner; the full-size viewer (and its URL resolution) mounts once the
+ // selection settles so each keystroke stays cheap.
+ const settledPath = useSettledValue(activeEntry?.path ?? null, 200)
+ const isSettled = settledPath === (activeEntry?.path ?? null)
+ const { isResolving, url: activeFileUrl } = useResolvedFileUrl(
+ isSettled ? activeFile : null,
+ getFileUrl
+ )
+ const isStageLoading =
+ activeFile !== null &&
+ (!isSettled || (activeViewerKind !== null && isResolving))
const activeFileSize = activeFile ? formatByteSize(activeFile.size) : null
const handleKeyDown = (event: React.KeyboardEvent) => {
@@ -1764,11 +1895,68 @@ function FileSystemGalleryView(props: FileSystemViewProps) {
return (
<div className="flex size-full flex-col" onKeyDown={handleKeyDown}>
+ {/* The strip comes first in DOM order (rendered below via order-last)
+ so the filmstrip is the view's single tab stop: Shift+Tab exits to
+ the toolbar instead of landing inside the embedded viewers. */}
+ <ScrollArea
+ orientation="horizontal"
+ className="order-last h-auto w-full shrink-0 border-t"
+ >
+ <div
+ role="listbox"
+ aria-label="Files"
+ className="flex w-max min-w-full items-center gap-1.5 p-2"
+ >
+ {entries.map((entry) => {
+ const isActive = entry.path === (activeEntry?.path ?? selectedPath)
+
+ return (
+ <button
+ key={entry.path}
+ type="button"
+ role="option"
+ aria-selected={isActive}
+ tabIndex={isActive ? 0 : -1}
+ ref={(element) => {
+ if (element) {
+ stripRefs.current.set(entry.path, element)
+ } else {
+ stripRefs.current.delete(entry.path)
+ }
+ }}
+ onClick={() => onSelect(entry)}
+ onDoubleClick={() => onOpen(entry)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") onOpen(entry)
+ }}
+ title={entry.name}
+ className={cn(
+ "flex size-14 shrink-0 items-center justify-center rounded-md border border-transparent p-1 outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ isActive && "border-ring/40 bg-accent"
+ )}
+ >
+ {entry.kind === "folder" ? (
+ <FileSystemFolderGlyph className="h-9 w-auto" />
+ ) : (
+ <FileVisual
+ file={entry}
+ className="w-9 rounded-sm"
+ previewAspectRatio={0.78}
+ renderFilePreview={renderFilePreview}
+ />
+ )}
+ </button>
+ )
+ })}
+ </div>
+ </ScrollArea>
<div className="flex min-h-0 flex-1">
<div className="flex min-h-0 min-w-0 flex-1 items-center justify-center p-3">
{activeEntry ? (
activeEntry.kind === "folder" ? (
<FileSystemFolderGlyph className="h-40 max-h-full w-auto drop-shadow-md" />
+ ) : isStageLoading ? (
+ <Spinner className="size-6 text-muted-foreground" />
) : activeViewerKind === "image" && activeFileUrl ? (
<img
src={activeFileUrl}
@@ -1852,57 +2040,6 @@ function FileSystemGalleryView(props: FileSystemViewProps) {
</ScrollArea>
) : null}
</div>
- <ScrollArea
- orientation="horizontal"
- className="h-auto w-full shrink-0 border-t"
- >
- <div
- role="listbox"
- aria-label="Files"
- className="flex w-max min-w-full items-center gap-1.5 p-2"
- >
- {entries.map((entry) => {
- const isActive = entry.path === (activeEntry?.path ?? selectedPath)
-
- return (
- <button
- key={entry.path}
- type="button"
- role="option"
- aria-selected={isActive}
- ref={(element) => {
- if (element) {
- stripRefs.current.set(entry.path, element)
- } else {
- stripRefs.current.delete(entry.path)
- }
- }}
- onClick={() => onSelect(entry)}
- onDoubleClick={() => onOpen(entry)}
- onKeyDown={(event) => {
- if (event.key === "Enter") onOpen(entry)
- }}
- title={entry.name}
- className={cn(
- "flex size-14 shrink-0 items-center justify-center rounded-md border border-transparent p-1 outline-none focus-visible:ring-2 focus-visible:ring-ring",
- isActive && "border-ring/40 bg-accent"
- )}
- >
- {entry.kind === "folder" ? (
- <FileSystemFolderGlyph className="h-9 w-auto" />
- ) : (
- <FileVisual
- file={entry}
- className="w-9 rounded-sm"
- previewAspectRatio={0.78}
- renderFilePreview={renderFilePreview}
- />
- )}
- </button>
- )
- })}
- </div>
- </ScrollArea>
</div>
)
}
diff --git a/apps/v4/content/docs/components/file-system.mdx b/apps/v4/content/docs/components/file-system.mdx
index 4bf196e..ce7d76c 100644
--- a/apps/v4/content/docs/components/file-system.mdx
+++ b/apps/v4/content/docs/components/file-system.mdx
@@ -127,15 +127,17 @@ The list view tree is derived from file paths, so lazy folders (`hasChildren` wi
### Keyboard Navigation
- **Grid** — arrow keys move the selection in all four directions, following the rendered grid; Enter opens.
-- **List** — full keyboard support from `@pierre/trees` (arrows, type-ahead, expand/collapse).
+- **List** — full keyboard support from `@pierre/trees` (arrows, type-ahead, expand/collapse); arrow keys move the selection like Finder, and Shift-arrows extend it.
- **Columns** — up/down move within a column, left selects the parent folder, right steps into the selected folder; Enter opens.
- **Gallery** — left/right move through the filmstrip; Enter opens.
+Every view is a single tab stop — <kbd>Tab</kbd> lands on the selected item and <kbd>Shift+Tab</kbd> returns to the view switcher, matching the list tree's behavior.
+
Finder-style shortcuts work everywhere in the component: <kbd>⌘↑</kbd> goes to the enclosing folder, <kbd>⌘↓</kbd> opens the selection, and <kbd>⌘[</kbd> / <kbd>⌘]</kbd> navigate back and forward through history (Ctrl works in place of ⌘).
When the component is narrower than 480px, the toolbar swaps the tabs view switcher for a compact select.
-The gallery view embeds the full viewers — PDF, DOCX, and XLSX files render in their toolbar-less viewer (the XLSX sheet switcher stays), and images scale to fill the stage.
+The gallery view embeds the full viewers — PDF, DOCX, and XLSX files render in their toolbar-less viewer (the XLSX sheet switcher stays), and images scale to fill the stage. While arrow keys are scrubbing the filmstrip the stage shows a spinner; the full viewer mounts once the selection settles, so holding an arrow key stays smooth.
### Multi-Page Thumbnails