TypeScript
Sync file system source and signature image lint
Andrew Luo1db70779f994
diff --git a/apps/v4/components/e-signature-docs.tsx b/apps/v4/components/e-signature-docs.tsxindex e6c4b91..2559029 100644--- a/apps/v4/components/e-signature-docs.tsx+++ b/apps/v4/components/e-signature-docs.tsx@@ -452,6 +452,7 @@ function SignatureFieldOverlay({onPointerDown={onDragStart}>{field.imageDataUrl ? (+ // eslint-disable-next-line @next/next/no-img-element -- Signature fields render user-drawn data URLs.<imgsrc={field.imageDataUrl}alt=""diff --git a/apps/v4/components/file-system-source-code.tsx b/apps/v4/components/file-system-source-code.tsxindex 5af21e4..3bf4707 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 ArrowDown01Icon,\n ArrowLeft01Icon,\n ArrowRight01Icon,\n ArrowUp01Icon,\n ArrowUpDownIcon,\n Calendar03Icon,\n Cancel01Icon,\n File01Icon,\n FilterIcon,\n GalleryThumbnailsIcon,\n GridViewIcon,\n LayoutThreeColumnIcon,\n LeftToRightListBulletIcon,\n Search01Icon,\n Tick02Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport {\n createFileTreeIconResolver,\n getBuiltInSpriteSheet,\n prepareFileTreeInput,\n type FileTreeSortComparator,\n type FileTreeSortEntry,\n} from "@pierre/trees"\nimport { FileTree as PierreFileTree, useFileTree } from "@pierre/trees/react"\nimport { createPortal } from "react-dom"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n Command,\n CommandEmpty,\n CommandGroup,\n CommandInput,\n CommandItem,\n CommandList,\n} from "@/components/ui/command"\nimport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogFooter,\n DialogHeader,\n DialogPanel,\n DialogTitle,\n} from "@/components/ui/dialog"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuSub,\n DropdownMenuSubContent,\n DropdownMenuSubTrigger,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { Input } from "@/components/ui/input"\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from "@/components/ui/popover"\nimport { ScrollArea, ScrollAreaPrimitive } 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"\n\nconst LazyPDFViewer = React.lazy(() =>\n import("@/components/ui/pdf-viewer").then((mod) => ({\n default: mod.PDFViewer,\n }))\n)\nconst LazyDocxViewerPreview = React.lazy(() =>\n import("@/components/ui/docx-viewer").then((mod) => ({\n default: mod.DocxViewerPreview,\n }))\n)\nconst LazyXlsxViewerPreview = React.lazy(() =>\n import("@/components/ui/xlsx-viewer").then((mod) => ({\n default: mod.XlsxViewerPreview,\n }))\n)\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 css: "CSS Stylesheet",\n csv: "CSV Document",\n doc: "Word Document",\n docx: "Word Document",\n gif: "GIF Image",\n go: "Go Source",\n jpeg: "JPEG Image",\n jpg: "JPEG Image",\n js: "JavaScript Source",\n json: "JSON Document",\n jsx: "JavaScript Source",\n md: "Markdown Document",\n mdx: "MDX Document",\n pdf: "PDF Document",\n png: "PNG Image",\n ppt: "PowerPoint Presentation",\n pptx: "PowerPoint Presentation",\n py: "Python Script",\n rs: "Rust Source",\n sh: "Shell Script",\n sql: "SQL Script",\n svg: "SVG Image",\n ts: "TypeScript Source",\n tsv: "TSV Document",\n tsx: "TypeScript Source",\n txt: "Plain Text",\n webp: "WebP Image",\n xls: "Excel Workbook",\n xlsx: "Excel Workbook",\n yaml: "YAML Document",\n yml: "YAML Document",\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\n// Folders sort under the "Folder" kind alphabetically among the file kinds,\n// like Finder\'s Kind sort.\nfunction entryKindLabel(entry: FileSystemEntry) {\n return entry.kind === "folder" ? "Folder" : fileKindLabel(entry)\n}\n\n// MIME types inferred from the extension when a file carries no\n// `contentType`, so the file-type filter can classify every manifest entry.\nconst EXTENSION_MIME_TYPES: Record<string, string> = {\n css: "text/css",\n csv: "text/csv",\n doc: "application/msword",\n docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",\n gif: "image/gif",\n go: "text/x-go",\n jpeg: "image/jpeg",\n jpg: "image/jpeg",\n js: "text/javascript",\n json: "application/json",\n jsx: "text/jsx",\n md: "text/markdown",\n mdx: "text/mdx",\n pdf: "application/pdf",\n png: "image/png",\n ppt: "application/vnd.ms-powerpoint",\n pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",\n py: "text/x-python",\n rs: "text/x-rust",\n sh: "application/x-sh",\n sql: "application/sql",\n svg: "image/svg+xml",\n ts: "text/x-typescript",\n tsv: "text/tab-separated-values",\n tsx: "text/x-typescript",\n txt: "text/plain",\n webp: "image/webp",\n xls: "application/vnd.ms-excel",\n xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",\n yaml: "text/yaml",\n yml: "text/yaml",\n zip: "application/zip",\n}\n\nconst FALLBACK_MIME_TYPE = "application/octet-stream"\nconst IPAD_MIN_WIDTH = 768\n\nconst MIME_TYPE_LABELS: Record<string, string> = {\n [FALLBACK_MIME_TYPE]: "Binary",\n "application/json": "JSON",\n "application/msword": "Word document (legacy)",\n "application/pdf": "PDF",\n "application/sql": "SQL",\n "application/vnd.ms-excel": "Excel workbook (legacy)",\n "application/vnd.ms-powerpoint": "PowerPoint (legacy)",\n "application/vnd.openxmlformats-officedocument.presentationml.presentation":\n "PowerPoint",\n "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":\n "Excel workbook",\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document":\n "Word document",\n "application/x-sh": "Shell script",\n "application/zip": "ZIP archive",\n "image/gif": "GIF image",\n "image/jpeg": "JPEG image",\n "image/png": "PNG image",\n "image/svg+xml": "SVG image",\n "image/webp": "WebP image",\n "text/css": "CSS",\n "text/csv": "CSV",\n "text/javascript": "JavaScript",\n "text/jsx": "JSX",\n "text/markdown": "Markdown",\n "text/mdx": "MDX",\n "text/plain": "Plain text",\n "text/tab-separated-values": "TSV",\n "text/x-go": "Go",\n "text/x-python": "Python",\n "text/x-rust": "Rust",\n "text/x-typescript": "TypeScript",\n "text/yaml": "YAML",\n}\n\nfunction mimeTypeForFile(file: FileEntry) {\n return (\n file.contentType ??\n EXTENSION_MIME_TYPES[fileExtension(file.name)] ??\n FALLBACK_MIME_TYPE\n )\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 FileSystemViewerLoading() {\n return (\n <div className="grid h-full min-h-48 flex-1 place-items-center bg-background">\n <Spinner className="size-4 text-muted-foreground" />\n </div>\n )\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\n// Every directory prefix appearing in the given relative file paths.\nfunction directoryPathsOf(paths: readonly string[]) {\n const directoryPaths = new Set<string>()\n\n for (const relativePath of paths) {\n let slashIndex = relativePath.indexOf("/")\n\n while (slashIndex !== -1) {\n directoryPaths.add(relativePath.slice(0, slashIndex))\n slashIndex = relativePath.indexOf("/", slashIndex + 1)\n }\n }\n return directoryPaths\n}\n\nfunction compareEntryNames(left: { name: string }, right: { name: string }) {\n return left.name.localeCompare(right.name, undefined, {\n numeric: true,\n sensitivity: "base",\n })\n}\n\nexport type FileSystemSortKey =\n | "createdAt"\n | "kind"\n | "name"\n | "size"\n | "updatedAt"\n\ntype FileSystemSortState = {\n direction: "asc" | "desc"\n key: FileSystemSortKey\n}\n\nconst SORT_OPTIONS: Array<{\n defaultDirection: "asc" | "desc"\n key: FileSystemSortKey\n label: string\n /** Shorter label so the toolbar trigger stays narrow. */\n triggerLabel: string\n}> = [\n { defaultDirection: "asc", key: "name", label: "Name", triggerLabel: "Name" },\n { defaultDirection: "asc", key: "kind", label: "Kind", triggerLabel: "Kind" },\n {\n defaultDirection: "desc",\n key: "createdAt",\n label: "Date created",\n triggerLabel: "Created",\n },\n {\n defaultDirection: "desc",\n key: "updatedAt",\n label: "Date modified",\n triggerLabel: "Modified",\n },\n {\n defaultDirection: "desc",\n key: "size",\n label: "Size",\n triggerLabel: "Size",\n },\n]\n\nconst DEFAULT_SORT: FileSystemSortState = { direction: "asc", key: "name" }\n\nfunction defaultSortDirection(key: FileSystemSortKey) {\n return (\n SORT_OPTIONS.find((option) => option.key === key)?.defaultDirection ?? "asc"\n )\n}\n\nfunction entrySortTimestamp(\n entry: FileSystemEntry,\n key: "createdAt" | "updatedAt"\n) {\n const value = entry[key]\n const time = value ? Date.parse(value) : Number.NaN\n\n return Number.isNaN(time) ? 0 : time\n}\n\n// Primary key per the active sort; ties (and missing metadata) fall back to\n// the name order so results stay stable. The name tiebreak ignores the\n// direction, like Finder.\nfunction compareEntriesBySort(\n left: FileSystemEntry,\n right: FileSystemEntry,\n sort: FileSystemSortState\n) {\n let result = 0\n\n if (sort.key === "name") {\n result = compareEntryNames(left, right)\n } else if (sort.key === "kind") {\n result = entryKindLabel(left).localeCompare(\n entryKindLabel(right),\n undefined,\n {\n sensitivity: "base",\n }\n )\n } else if (sort.key === "size") {\n // Folders have no byte size; group them at the small end.\n const leftSize = left.kind === "file" ? (left.size ?? 0) : -1\n const rightSize = right.kind === "file" ? (right.size ?? 0) : -1\n\n result = leftSize - rightSize\n } else {\n result =\n entrySortTimestamp(left, sort.key) - entrySortTimestamp(right, sort.key)\n }\n\n if (result === 0) return compareEntryNames(left, right)\n return sort.direction === "asc" ? (result < 0 ? -1 : 1) : result < 0 ? 1 : -1\n}\n\nexport type FileSystemFilterType = "dateCreated" | "dateModified" | "fileType"\n\ntype FileSystemDateFilterType = Exclude<FileSystemFilterType, "fileType">\n\ntype FileSystemFilterOperator =\n | "after"\n | "before"\n | "in-range"\n | "is"\n | "is-any-of"\n | "is-not"\n | "not-in-range"\n\ntype FileSystemFilter = {\n id: string\n operator: FileSystemFilterOperator\n type: FileSystemFilterType\n value: string[]\n}\n\ntype FileTypeFilterOption = {\n /** Sample file name so the option icon reuses the file-type sprite. */\n iconFileName: string\n label: string\n mime: string\n}\n\nconst FILTER_TYPE_LABELS: Record<FileSystemFilterType, string> = {\n dateCreated: "Date created",\n dateModified: "Date modified",\n fileType: "File type",\n}\n\nconst FILTER_OPERATOR_LABELS: Record<FileSystemFilterOperator, string> = {\n after: "after",\n before: "before",\n "in-range": "in range",\n is: "is",\n "is-any-of": "is any of",\n "is-not": "is not",\n "not-in-range": "not in range",\n}\n\n// Relative cutoffs for the date filters, mirroring Extend\'s table filters.\nconst DATE_FILTER_PRESETS = [\n "1 day ago",\n "3 days ago",\n "1 week ago",\n "1 month ago",\n "3 months ago",\n "6 months ago",\n "1 year ago",\n]\n\nfunction dateFilterPresetCutoff(preset: string) {\n const date = new Date()\n\n switch (preset) {\n case "1 day ago":\n date.setDate(date.getDate() - 1)\n break\n case "3 days ago":\n date.setDate(date.getDate() - 3)\n break\n case "1 week ago":\n date.setDate(date.getDate() - 7)\n break\n case "1 month ago":\n date.setMonth(date.getMonth() - 1)\n break\n case "3 months ago":\n date.setMonth(date.getMonth() - 3)\n break\n case "6 months ago":\n date.setMonth(date.getMonth() - 6)\n break\n case "1 year ago":\n date.setFullYear(date.getFullYear() - 1)\n break\n default: {\n const parsed = Date.parse(preset)\n\n if (!Number.isNaN(parsed)) return new Date(parsed)\n }\n }\n return date\n}\n\n// Custom ranges store two ISO timestamps instead of a relative preset.\nfunction isCustomDateRangeValue(value: string[]) {\n return (\n value.length === 2 &&\n value.every(\n (entry) =>\n !DATE_FILTER_PRESETS.includes(entry) && !Number.isNaN(Date.parse(entry))\n )\n )\n}\n\nfunction filterOperatorChoices(\n filter: FileSystemFilter\n): FileSystemFilterOperator[] {\n if (filter.type === "fileType") {\n return filter.value.length > 1 ? ["is-any-of", "is-not"] : ["is", "is-not"]\n }\n if (isCustomDateRangeValue(filter.value)) return ["in-range", "not-in-range"]\n return ["before", "after"]\n}\n\nfunction fileMatchesFilter(file: FileEntry, filter: FileSystemFilter) {\n if (filter.value.length === 0) return true\n if (filter.type === "fileType") {\n const matches = filter.value.includes(mimeTypeForFile(file))\n\n return filter.operator === "is-not" ? !matches : matches\n }\n\n const timestamp =\n filter.type === "dateCreated" ? file.createdAt : file.updatedAt\n const time = timestamp ? Date.parse(timestamp) : Number.NaN\n\n if (Number.isNaN(time)) return false\n if (filter.operator === "in-range" || filter.operator === "not-in-range") {\n const from = Date.parse(filter.value[0])\n const to = Date.parse(filter.value[1] ?? filter.value[0])\n const isInRange = time >= from && time <= to\n\n return filter.operator === "not-in-range" ? !isInRange : isInRange\n }\n\n const cutoff = dateFilterPresetCutoff(filter.value[0]).getTime()\n\n return filter.operator === "before" ? time <= cutoff : time >= cutoff\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(compareEntryNames)\n }\n\n // Folders without an explicit modified date inherit their newest child\'s —\n // object stores carry no folder metadata, yet the list view shows the\n // column and the date sorts compare it. Deepest first (a descendant\'s path\n // is always longer than its ancestor\'s) so dates propagate up the chain.\n const foldersDeepestFirst = [...folders.values()].sort(\n (left, right) => right.path.length - left.path.length\n )\n\n for (const folder of foldersDeepestFirst) {\n if (folder.updatedAt) continue\n\n let newestTime = Number.NEGATIVE_INFINITY\n let newestValue: string | undefined\n\n for (const child of children.get(folder.path) ?? []) {\n const value = child.updatedAt ?? child.createdAt\n const time = value ? Date.parse(value) : Number.NaN\n\n if (!Number.isNaN(time) && time > newestTime) {\n newestTime = time\n newestValue = value\n }\n }\n if (newestValue) folder.updatedAt = newestValue\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("&", "&")\n .replaceAll("<", "<")\n .replaceAll(">", ">")\n .replaceAll(\'"\', """)\n}\n\n// The @pierre/trees "complete" set — the full, colored suite with brand and\n// framework glyphs — ships as an SVG sprite. The list view tree consumes it\n// natively inside its shadow DOM; the icon, column, and gallery views render\n// the same sprite from the light DOM so every view falls back to the same\n// file-type icon when a file has no thumbnail.\nconst FILE_ICON_SPRITE_SHEET = getBuiltInSpriteSheet("complete")\n\nconst { resolveIcon: resolveFileIcon } = createFileTreeIconResolver({\n colored: true,\n set: "complete",\n})\n\n// Per-token light/dark colors mirroring the palette the tree applies inside\n// its shadow DOM. Tokens without an entry (font, nextjs, stylelint) stay\n// muted-foreground there too.\nconst FILE_ICON_COLORS: Record<string, [light: string, dark: string]> = {\n astro: ["#a631be", "#d568ea"],\n babel: ["#d5a910", "#ffd452"],\n bash: ["#199f43", "#5ecc71"],\n biome: ["#1a85d4", "#69b1ff"],\n bootstrap: ["#693acf", "#9d6afb"],\n browserslist: ["#d5a910", "#ffd452"],\n bun: ["#594c5b", "#79697b"],\n c: ["#1a85d4", "#69b1ff"],\n claude: ["#d47628", "#ffa359"],\n cpp: ["#1a85d4", "#69b1ff"],\n css: ["#693acf", "#9d6afb"],\n database: ["#a631be", "#d568ea"],\n default: ["#84848a", "#adadb1"],\n docker: ["#1a85d4", "#69b1ff"],\n eslint: ["#693acf", "#9d6afb"],\n git: ["#ff8c5b", "#d5512f"],\n go: ["#1ca1c7", "#68cdf2"],\n graphql: ["#d32a61", "#ff678d"],\n html: ["#d47628", "#ffa359"],\n image: ["#d32a61", "#ff678d"],\n javascript: ["#d5a910", "#ffd452"],\n json: ["#d47628", "#ffa359"],\n markdown: ["#199f43", "#5ecc71"],\n mcp: ["#17a5af", "#64d1db"],\n npm: ["#d52c36", "#ff6762"],\n oxc: ["#1ca1c7", "#68cdf2"],\n postcss: ["#d52c36", "#ff6762"],\n prettier: ["#17a5af", "#64d1db"],\n python: ["#1a85d4", "#69b1ff"],\n react: ["#1ca1c7", "#68cdf2"],\n ruby: ["#d52c36", "#ff6762"],\n rust: ["#d47628", "#ffa359"],\n sass: ["#d32a61", "#ff678d"],\n svelte: ["#d52c36", "#ff6762"],\n svg: ["#d47628", "#ffa359"],\n svgo: ["#199f43", "#5ecc71"],\n swift: ["#d47628", "#ffa359"],\n table: ["#17a5af", "#64d1db"],\n tailwind: ["#1ca1c7", "#68cdf2"],\n terraform: ["#693acf", "#9d6afb"],\n text: ["#84848a", "#adadb1"],\n typescript: ["#1a85d4", "#69b1ff"],\n vite: ["#a631be", "#d568ea"],\n vscode: ["#1a85d4", "#69b1ff"],\n vue: ["#199f43", "#5ecc71"],\n wasm: ["#693acf", "#9d6afb"],\n webpack: ["#1a85d4", "#69b1ff"],\n yml: ["#d52c36", "#ff6762"],\n zig: ["#d47628", "#ffa359"],\n zip: ["#d47628", "#ffa359"],\n}\n\nfunction fileIconColorVariables(mode: 0 | 1) {\n return Object.entries(FILE_ICON_COLORS)\n .map(([token, colors]) => `--fs-file-icon-${token}: ${colors[mode]};`)\n .join(" ")\n}\n\n// The variables live on :root rather than the component root because the\n// filter menus and dialogs portal outside it; the --fs-file-icon-*\n// namespace keeps them collision-free. Thumbnail tiles keep a light\n// (paper) surface in dark mode, so icons inside them revert to the light\n// palette ([data-file-system-on-light]); selected rows sit on the primary\n// surface — the opposite of the mode\'s background — so icons there swap to\n// the opposite palette ([data-file-system-on-primary] in the light DOM,\n// --fs-selected-color-scheme for the tree\'s light-dark() colors inside its\n// shadow DOM).\nconst FILE_ICON_COLOR_CSS = `\n:root { ${fileIconColorVariables(0)} --fs-selected-color-scheme: dark; }\n.dark { ${fileIconColorVariables(1)} --fs-selected-color-scheme: light; }\n.dark [data-file-system-on-light] { ${fileIconColorVariables(0)} }\n[data-file-system-on-primary] { ${fileIconColorVariables(1)} }\n.dark [data-file-system-on-primary] { ${fileIconColorVariables(0)} }\n`\n\nfunction FileSystemIconSpriteSheet() {\n return (\n <>\n <span\n aria-hidden="true"\n className="hidden"\n dangerouslySetInnerHTML={{ __html: FILE_ICON_SPRITE_SHEET }}\n />\n <style>{FILE_ICON_COLOR_CSS}</style>\n </>\n )\n}\n\nfunction FileTypeIcon({\n fileName,\n className,\n}: {\n fileName: string\n className?: string\n}) {\n const icon = resolveFileIcon("file-tree-icon-file", fileName)\n\n return (\n <svg\n aria-hidden="true"\n viewBox={icon.viewBox ?? "0 0 16 16"}\n className={cn("shrink-0 text-muted-foreground", className)}\n style={\n icon.token\n ? {\n color: `var(--fs-file-icon-${icon.token}, var(--color-muted-foreground))`,\n }\n : undefined\n }\n >\n <use href={`#${icon.name}`} />\n </svg>\n )\n}\n\nfunction FileGenericPreview({ file }: { file: FileEntry }) {\n const extension = fileExtension(file.name)\n\n return (\n <div\n data-file-system-on-light=""\n className="flex size-full flex-col items-center justify-center gap-1.5 bg-white text-neutral-400 dark:bg-neutral-100"\n >\n <FileTypeIcon fileName={file.name} 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// Mirrors @pierre/trees\' query normalization so the toolbar search filters\n// the icon, column, and gallery views exactly like the list view tree:\n// trimmed, backslashes to slashes, lowercased, substring match on the path.\nfunction normalizeSearchQuery(value: string) {\n const trimmed = value.trim()\n\n if (!trimmed) return ""\n return trimmed.replaceAll("\\\\", "/").toLowerCase()\n}\n\n// Windowed rendering, the approach @pierre/trees uses for the list view:\n// with a fixed item stride only the items intersecting the viewport — plus\n// `overscan` on each side — are mounted, so views stay flat-cost at\n// thousands of entries. The window keeps a one-item margin before\n// recomputing (scrolling doesn\'t re-render per item) and that margin also\n// guarantees single-step keyboard moves land on a mounted neighbor.\nfunction useVirtualWindow({\n count,\n horizontal = false,\n itemStride,\n leadingPx = 0,\n overscan = 8,\n viewportRef,\n}: {\n count: number\n horizontal?: boolean\n itemStride: number\n leadingPx?: number\n overscan?: number\n viewportRef: React.RefObject<HTMLDivElement | null>\n}) {\n const [window_, setWindow] = React.useState(() => ({\n end: Math.min(count, overscan * 2),\n start: 0,\n }))\n\n React.useLayoutEffect(() => {\n const viewport = viewportRef.current\n\n if (!viewport || itemStride <= 0) return\n\n const update = () => {\n const scrollStart =\n (horizontal ? viewport.scrollLeft : viewport.scrollTop) - leadingPx\n const viewportSize = horizontal\n ? viewport.clientWidth\n : viewport.clientHeight\n const firstVisible = Math.max(0, Math.floor(scrollStart / itemStride))\n const lastVisible = Math.min(\n count,\n Math.ceil((scrollStart + viewportSize) / itemStride)\n )\n\n setWindow((previous) => {\n if (\n previous.end <= count &&\n previous.start <= Math.max(0, firstVisible - 1) &&\n previous.end >= Math.min(count, lastVisible + 1)\n ) {\n return previous\n }\n return {\n end: Math.min(count, lastVisible + overscan),\n start: Math.max(0, firstVisible - overscan),\n }\n })\n }\n\n update()\n viewport.addEventListener("scroll", update, { passive: true })\n\n const observer =\n typeof ResizeObserver === "undefined" ? null : new ResizeObserver(update)\n\n observer?.observe(viewport)\n return () => {\n viewport.removeEventListener("scroll", update)\n observer?.disconnect()\n }\n }, [count, horizontal, itemStride, leadingPx, overscan, viewportRef])\n\n return window_\n}\n\n// Scrolls the item at `index` into the viewport when it sits outside it —\n// virtualized views need this because off-window items have no DOM node to\n// call scrollIntoView on.\nfunction scrollIndexIntoView({\n horizontal = false,\n index,\n itemSize,\n itemStride,\n leadingPx = 0,\n viewport,\n}: {\n horizontal?: boolean\n index: number\n itemSize: number\n itemStride: number\n leadingPx?: number\n viewport: HTMLDivElement | null\n}) {\n if (!viewport || index < 0) return\n\n const start = leadingPx + index * itemStride\n const end = start + itemSize\n const scrollStart = horizontal ? viewport.scrollLeft : viewport.scrollTop\n const viewportSize = horizontal ? viewport.clientWidth : viewport.clientHeight\n\n let nextScrollStart: number | null = null\n\n if (start < scrollStart) {\n nextScrollStart = start\n } else if (end > scrollStart + viewportSize) {\n nextScrollStart = end - viewportSize\n }\n if (nextScrollStart === null) return\n if (horizontal) {\n viewport.scrollLeft = nextScrollStart\n } else {\n viewport.scrollTop = nextScrollStart\n }\n}\n\nfunction FileVisual({\n file,\n className,\n loadPreviewImageUrl,\n pageable = false,\n pageUrlCache,\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 /**\n * Shared `"path#pageIndex"` → URL cache so pages fetched by one pager\n * (gallery stage, columns preview) are reused by every other instance.\n */\n pageUrlCache?: Map<string, string>\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] ??\n lazyPageUrls[clampedPageIndex] ??\n pageUrlCache?.get(`${file.path}#${clampedPageIndex}`) ??\n 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 // Cache even when stale (page flipped away mid-load): the fetch is\n // done, so let the next visit use it.\n if (url) pageUrlCache?.set(`${file.path}#${clampedPageIndex}`, 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 }, [\n clampedPageIndex,\n file.path,\n isLazyPagePending,\n loadPreviewImageUrl,\n pageUrlCache,\n ])\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 [searchInput, setSearchInput] = React.useState("")\n const searchInputRef = React.useRef<HTMLInputElement | null>(null)\n const [isSearchExpanded, setIsSearchExpanded] = React.useState(false)\n const searchQuery = normalizeSearchQuery(searchInput)\n const isSearching = searchQuery.length > 0\n\n const [sort, setSort] = React.useState(DEFAULT_SORT)\n const [filters, setFilters] = React.useState<FileSystemFilter[]>([])\n const hasActiveFilters = filters.length > 0\n\n // Files must pass every active filter; folders stay visible through\n // matching descendants, so the predicate only ever sees files.\n const fileFilter = React.useMemo(() => {\n if (filters.length === 0) return null\n return (file: FileEntry) =>\n filters.every((filter) => fileMatchesFilter(file, filter))\n }, [filters])\n\n // Paths that stay visible while searching or filtering: every file whose\n // currentPath-relative path contains the query — the list view tree\'s\n // hide-non-matches semantics — and that passes the filters, plus the\n // ancestor folders leading to it. Folder names participate in search\n // matches only when no filters are active; with filters, a folder is only\n // as visible as the files inside it.\n const visiblePaths = React.useMemo(() => {\n if (!isSearching && !fileFilter) return null\n\n const visible = new Set<string>()\n const markVisible = (path: string) => {\n while (path && path !== currentPath && !visible.has(path)) {\n visible.add(path)\n path = pathParent(path)\n }\n }\n const matchesQuery = (path: string) =>\n !isSearching ||\n path.slice(currentPath.length).toLowerCase().includes(searchQuery)\n\n for (const [path, file] of index.files) {\n if (path === currentPath) continue\n if (currentPath && !path.startsWith(currentPath)) continue\n if (!matchesQuery(path)) continue\n if (fileFilter && !fileFilter(file)) continue\n markVisible(path)\n }\n if (!fileFilter) {\n for (const path of index.folders.keys()) {\n if (path === currentPath) continue\n if (currentPath && !path.startsWith(currentPath)) continue\n if (matchesQuery(path)) markVisible(path)\n }\n }\n return visible\n }, [currentPath, fileFilter, index, isSearching, searchQuery])\n\n const visibleIndex = React.useMemo(() => {\n if (!visiblePaths) return index\n\n const children = new Map<string, FileSystemEntry[]>()\n\n for (const [parentPath, parentChildren] of index.children) {\n const visibleChildren = parentChildren.filter((entry) =>\n visiblePaths.has(entry.path)\n )\n\n if (visibleChildren.length) children.set(parentPath, visibleChildren)\n }\n return { ...index, children }\n }, [index, visiblePaths])\n\n // Children re-sorted per the active sort; the default (name ascending)\n // reuses the index\'s pre-sorted arrays untouched.\n const sortedIndex = React.useMemo(() => {\n if (\n sort.key === DEFAULT_SORT.key &&\n sort.direction === DEFAULT_SORT.direction\n ) {\n return visibleIndex\n }\n\n const children = new Map<string, FileSystemEntry[]>()\n\n for (const [parentPath, parentChildren] of visibleIndex.children) {\n children.set(\n parentPath,\n [...parentChildren].sort((left, right) =>\n compareEntriesBySort(left, right, sort)\n )\n )\n }\n return { ...visibleIndex, children }\n }, [sort, visibleIndex])\n\n // The ref mirrors the state so re-selecting the same entry (e.g. the\n // pointerdown + click pair the columns view emits per press) stays a\n // no-op without widening the callback\'s dependencies.\n const selectedPathRef = React.useRef<string | null>(null)\n const selectEntry = React.useCallback(\n (entry: FileSystemEntry | null) => {\n const path = entry?.path ?? null\n\n if (selectedPathRef.current === path) return\n selectedPathRef.current = path\n setSelectedPath(path)\n onSelectionChange?.(entry)\n },\n [onSelectionChange]\n )\n\n // A query or filter change can hide the selected entry out from under the\n // views.\n React.useEffect(() => {\n if (!visiblePaths || !selectedPath) return\n if (!visiblePaths.has(selectedPath)) selectEntry(null)\n }, [selectEntry, selectedPath, visiblePaths])\n\n const applySortKey = React.useCallback((key: FileSystemSortKey) => {\n setSort((previous) =>\n previous.key === key\n ? previous\n : { direction: defaultSortDirection(key), key }\n )\n }, [])\n\n // Column headers toggle the direction when the column is already active,\n // like Finder.\n const toggleSortColumn = React.useCallback((key: FileSystemSortKey) => {\n setSort((previous) =>\n previous.key === key\n ? { direction: previous.direction === "asc" ? "desc" : "asc", key }\n : { direction: defaultSortDirection(key), key }\n )\n }, [])\n\n // Distinct MIME types across the loaded manifest, labeled for the filter\n // menu; the first file seen per type lends its name to the option icon.\n const fileTypeOptions = React.useMemo(() => {\n const byMime = new Map<string, FileTypeFilterOption>()\n\n for (const file of index.files.values()) {\n const mime = mimeTypeForFile(file)\n\n if (!byMime.has(mime)) {\n // The leading-dot check keeps dotfiles (.gitignore) whole.\n const dotIndex = file.name.lastIndexOf(".")\n const extension =\n dotIndex > 0 ? file.name.slice(dotIndex + 1).toLowerCase() : ""\n\n byMime.set(mime, {\n // A synthesized generic name, so files with branded icons\n // (biome.json, next.config.ts, CLAUDE.md, …) don\'t lend them to\n // the whole type; extensionless names keep their own icon\n // (Dockerfile, Makefile).\n iconFileName: extension ? `file.${extension}` : file.name,\n label: MIME_TYPE_LABELS[mime] ?? mime,\n mime,\n })\n }\n }\n return [...byMime.values()].sort((left, right) =>\n left.label.localeCompare(right.label)\n )\n }, [index])\n\n const filterIdRef = React.useRef(0)\n const [dateRangeDialog, setDateRangeDialog] = React.useState<{\n initialRange?: { from: Date; to: Date }\n type: FileSystemDateFilterType\n } | null>(null)\n\n const toggleFileTypeFilterValue = React.useCallback(\n (mime: string, checked: boolean) => {\n const id = `filter-${++filterIdRef.current}`\n\n setFilters((previous) => {\n const existing = previous.find((filter) => filter.type === "fileType")\n\n if (!existing) {\n if (!checked) return previous\n return [\n ...previous,\n {\n id,\n operator: "is" as const,\n type: "fileType" as const,\n value: [mime],\n },\n ]\n }\n\n const value = checked\n ? [...new Set([...existing.value, mime])]\n : existing.value.filter((entry) => entry !== mime)\n\n if (value.length === 0) {\n return previous.filter((filter) => filter !== existing)\n }\n\n // "is" and "is any of" track the value count; "is not" is unaffected.\n const operator =\n existing.operator === "is" || existing.operator === "is-any-of"\n ? value.length > 1\n ? ("is-any-of" as const)\n : ("is" as const)\n : existing.operator\n\n return previous.map((filter) =>\n filter === existing ? { ...filter, operator, value } : filter\n )\n })\n },\n []\n )\n\n const setDatePresetFilter = React.useCallback(\n (type: FileSystemDateFilterType, preset: string) => {\n const id = `filter-${++filterIdRef.current}`\n\n setFilters((previous) => [\n ...previous.filter((filter) => filter.type !== type),\n { id, operator: "after", type, value: [preset] },\n ])\n },\n []\n )\n\n // Editing an existing custom range seeds the dialog with its bounds.\n const openDateRangeDialog = React.useCallback(\n (type: FileSystemDateFilterType) => {\n const existing = filters.find((filter) => filter.type === type)\n\n setDateRangeDialog({\n initialRange:\n existing && isCustomDateRangeValue(existing.value)\n ? {\n from: new Date(existing.value[0]),\n to: new Date(existing.value[1]),\n }\n : undefined,\n type,\n })\n },\n [filters]\n )\n\n const applyCustomDateRange = React.useCallback(\n (type: FileSystemDateFilterType, from: Date, to: Date) => {\n const id = `filter-${++filterIdRef.current}`\n\n setFilters((previous) => {\n const existing = previous.find((filter) => filter.type === type)\n\n return [\n ...previous.filter((filter) => filter.type !== type),\n {\n id,\n operator:\n existing?.operator === "not-in-range"\n ? ("not-in-range" as const)\n : ("in-range" as const),\n type,\n value: [from.toISOString(), to.toISOString()],\n },\n ]\n })\n },\n []\n )\n\n // Below iPad width the view switcher collapses into a select and the sort\n // select drops its label; below 560px the search input collapses into a\n // popover, and below 360px the folder name is dropped too.\n const rootRef = React.useRef<HTMLDivElement | null>(null)\n const [headerLayout, setHeaderLayout] = React.useState<\n "full" | "compact" | "minimal"\n >("full")\n const [isBelowIpadWidth, setIsBelowIpadWidth] = React.useState(false)\n\n React.useEffect(() => {\n const root = rootRef.current\n\n if (!root || typeof ResizeObserver === "undefined") return\n\n const applyWidth = (width: number | undefined) => {\n if (width === undefined) return\n\n setHeaderLayout(\n width < 360 ? "minimal" : width < 560 ? "compact" : "full"\n )\n setIsBelowIpadWidth(width < IPAD_MIN_WIDTH)\n }\n const observer = new ResizeObserver((observerEntries) =>\n applyWidth(observerEntries[0]?.contentRect.width)\n )\n\n // Measure synchronously so the first painted layout is already correct;\n // the observer then tracks resizes.\n applyWidth(root.clientWidth)\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 // Navigation exits search, like Finder.\n setSearchInput("")\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 previousPathRef = React.useRef(currentPath)\n\n React.useEffect(() => {\n if (previousPathRef.current === currentPath) {\n return\n }\n\n previousPathRef.current = currentPath\n const root = rootRef.current\n\n if (root && document.activeElement === document.body) {\n root.focus({ preventScroll: true })\n }\n }, [currentPath])\n\n const [openedFile, setOpenedFile] = React.useState<{\n file: FileEntry\n kind: FileSystemViewerKind\n url: string\n } | null>(null)\n\n // Component-lifetime caches shared by every view and the open dialog:\n // resolved (e.g. presigned) URLs keyed by path, and lazily loaded page\n // thumbnails keyed by `"path#pageIndex"`. Each resolution happens once no\n // matter how often the user revisits a file or switches views; stable\n // URLs also keep the browser\'s HTTP cache valid for fetched content.\n // Lazy state (never set) rather than refs: the Maps are passed down\n // during render, which the rules of React disallow for ref reads.\n const [resolvedUrlCache] = React.useState(() => new Map<string, string>())\n const [pageUrlCache] = React.useState(() => new Map<string, string>())\n\n // The keep-alive preview pool. Recently shown documents stay mounted so\n // returning to one — in the gallery stage or the viewer dialog — skips\n // the download and parse work instead of repeating it behind a spinner.\n // Each pooled path renders through a portal into a stable detached <div>\n // created once per path and never swapped (React remounts a portal\'s\n // children when its container changes); a layout effect reparents that\n // div into whichever host currently shows the file: the gallery\'s stage\n // wrapper or the open dialog. Imperative appendChild keeps the mounted\n // viewer (and its parsed document) alive across every move. Pooled paths\n // without a current host stay mounted but DETACHED from the DOM — a\n // detached subtree costs no layout, paint, or style-recalc work, so idle\n // pool members never slow down interactions in the visible viewer.\n const [stagePool, setStagePool] = React.useState<string[]>([])\n const [stageRecency] = React.useState(() => new Map<string, number>())\n const stageClockRef = React.useRef(0)\n const [stageContainers] = React.useState(\n () => new Map<string, HTMLDivElement>()\n )\n const [stageHosts] = React.useState(() => new Map<string, HTMLElement>())\n const [, bumpStageHosts] = React.useState(0)\n // Bumped on every admission so the attach set recomputes when recency\n // changes without a pool membership change.\n const [stageVersion, setStageVersion] = React.useState(0)\n const [dialogStageHost, setDialogStageHost] =\n React.useState<HTMLElement | null>(null)\n\n const registerStageHost = React.useCallback(\n (path: string, element: HTMLElement | null) => {\n if (element) {\n if (stageHosts.get(path) === element) return\n stageHosts.set(path, element)\n } else {\n if (!stageHosts.has(path)) return\n stageHosts.delete(path)\n }\n bumpStageHosts((version) => version + 1)\n },\n [stageHosts]\n )\n\n const dialogStageHostRef = React.useCallback(\n (element: HTMLDivElement | null) => setDialogStageHost(element),\n []\n )\n\n // Admits a file into the pool (idempotent), evicting the least recently\n // admitted path beyond the cap. The pool array keeps insertion order —\n // reordering would churn the host registrations — so recency lives in a\n // separate map; the version bump re-renders so the attach set below\n // tracks recency even when pool membership is unchanged.\n const poolStagePath = React.useCallback(\n (path: string) => {\n if (!index.files.has(path)) return\n if (!stageContainers.has(path)) {\n const container = document.createElement("div")\n\n // Layout/paint containment keeps work inside one preview from\n // invalidating the rest of the page (and vice versa).\n container.className =\n "flex size-full min-h-0 min-w-0 items-center justify-center contain-layout contain-paint"\n stageContainers.set(path, container)\n }\n\n stageRecency.set(path, ++stageClockRef.current)\n setStageVersion((version) => version + 1)\n setStagePool((previous) => {\n if (previous.includes(path)) return previous\n\n const next = [...previous, path]\n\n if (next.length <= GALLERY_STAGE_POOL_SIZE) return next\n\n let evicted = next[0]\n\n for (const candidate of next) {\n if (candidate === path) continue\n if (\n (stageRecency.get(candidate) ?? 0) <\n (stageRecency.get(evicted) ?? 0)\n ) {\n evicted = candidate\n }\n }\n return next.filter((candidate) => candidate !== evicted)\n })\n },\n [index, stageContainers, stageRecency]\n )\n\n const dialogStagePath =\n openedFile !== null && openedFile.kind !== "image"\n ? openedFile.file.path\n : null\n // Only the most recently shown stages stay attached to the DOM, so\n // rotating among a few files stays instant while older pool members wait\n // detached at zero rendering cost. Memoized so host ref callbacks\n // downstream stay referentially stable — recomputing every render would\n // re-register hosts in a loop.\n const attachedStagePaths = React.useMemo(() => {\n void stageVersion\n\n const attached = [...stagePool]\n .sort((a, b) => (stageRecency.get(b) ?? 0) - (stageRecency.get(a) ?? 0))\n .slice(0, GALLERY_STAGE_ATTACHED_COUNT)\n\n if (\n dialogStagePath &&\n stagePool.includes(dialogStagePath) &&\n !attached.includes(dialogStagePath)\n ) {\n attached.push(dialogStagePath)\n }\n return attached\n }, [dialogStagePath, stagePool, stageRecency, stageVersion])\n\n // Reparent each pooled container to its current host. No dependency\n // array: host registration mutates maps in place, so the cheap loop\n // (pool ≤ GALLERY_STAGE_POOL_SIZE) runs every commit instead of chasing\n // every mutation source.\n React.useLayoutEffect(() => {\n for (const [path, container] of stageContainers) {\n if (!stagePool.includes(path)) {\n // Evicted — React already unmounted the portal\'s children.\n container.remove()\n stageContainers.delete(path)\n continue\n }\n if (dialogStagePath === path) {\n // Leave the container in place until the dialog host mounts.\n if (dialogStageHost && container.parentElement !== dialogStageHost) {\n dialogStageHost.appendChild(container)\n }\n continue\n }\n\n const target = attachedStagePaths.includes(path)\n ? (stageHosts.get(path) ?? null)\n : null\n\n if (!target) {\n if (container.parentElement) container.remove()\n } else if (container.parentElement !== target) {\n target.appendChild(container)\n }\n }\n })\n\n const openFile = React.useCallback(\n (file: FileEntry) => {\n void (async () => {\n let url = file.url ?? resolvedUrlCache.get(file.path) ?? null\n\n if (!url && getFileUrl) {\n try {\n url = await getFileUrl(file)\n if (url) resolvedUrlCache.set(file.path, url)\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 // Pool the file so the dialog reuses an already-mounted preview\n // (and the gallery inherits the live viewer after it closes).\n poolStagePath(file.path)\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, poolStagePath, resolvedUrlCache]\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 setSearchInput("")\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 setSearchInput("")\n selectEntry(null)\n }, [selectEntry])\n\n const currentEntries = sortedIndex.children.get(currentPath) ?? []\n const currentFolderName =\n currentPath === "" ? title : pathName(currentPath) || title\n const isLoadingCurrentFolder = loadingFolders.has(currentPath)\n\n // The list view tree saves its expanded folders here when it unmounts\n // (view switches, navigation) so returning to the list view — or to a\n // previously visited folder — restores the same disclosure state.\n const treeExpansionRef = React.useRef(new Map<string, readonly string[]>())\n\n const viewProps: FileSystemViewProps = {\n attachedStagePaths,\n currentPath,\n entries: currentEntries,\n fileFilter,\n getFileUrl,\n index: sortedIndex,\n loadPreviewImageUrl,\n loadingFolders,\n onOpen: openEntry,\n onSelect: selectAndPrefetchEntry,\n onSortColumnClick: toggleSortColumn,\n pageUrlCache,\n poolStagePath,\n registerStageHost,\n renderFilePreview,\n searchQuery,\n selectedEntry,\n selectedPath,\n sort,\n treeExpansionRef,\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 data-slot="file-system"\n onKeyDown={(event) => {\n // ⌘F focuses the toolbar search while focus is inside the component.\n if ((event.metaKey || event.ctrlKey) && event.key === "f") {\n event.preventDefault()\n setIsSearchExpanded(true)\n searchInputRef.current?.focus()\n }\n }}\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 <FileSystemIconSpriteSheet />\n <div className="relative grid h-12 shrink-0 grid-cols-[minmax(0,1fr)_auto_minmax(0,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" || isBelowIpadWidth ? (\n <Select\n value={view}\n onValueChange={(value) => setView(value as FileSystemView)}\n >\n <SelectTrigger\n size="sm"\n aria-label="View"\n // Icon-only like the sort select: sheds the base min-width to\n // hug icon + chevron at the filter button\'s 28px height.\n className="h-7 min-h-7 w-auto min-w-0 [&_svg]:size-4"\n >\n <SelectValue>\n {activeViewOption ? (\n <HugeiconsIcon\n icon={activeViewOption.icon}\n className="size-4"\n />\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 className="flex min-w-0 items-center justify-end gap-1">\n <FileSystemSortSelect\n layout={headerLayout}\n onKeyChange={applySortKey}\n showLabel={!isBelowIpadWidth}\n sort={sort}\n />\n <FileSystemFilterMenu\n fileTypeOptions={fileTypeOptions}\n filters={filters}\n onOpenCustomRange={openDateRangeDialog}\n onSelectDatePreset={setDatePresetFilter}\n onToggleFileType={toggleFileTypeFilterValue}\n />\n <FileSystemSearchField\n inputRef={searchInputRef}\n isExpanded={isSearchExpanded}\n layout={headerLayout}\n onExpandedChange={setIsSearchExpanded}\n onValueChange={setSearchInput}\n value={searchInput}\n />\n </div>\n </div>\n {hasActiveFilters ? (\n <div className="flex shrink-0 flex-wrap items-center gap-1 border-b bg-muted/20 px-2 py-1.5 text-xs text-muted-foreground">\n {filters.map((filter) => {\n const dateFilterType =\n filter.type === "fileType" ? null : filter.type\n\n return (\n <FileSystemFilterPill\n key={filter.id}\n fileTypeOptions={fileTypeOptions}\n filter={filter}\n onOpenCustomRange={\n dateFilterType\n ? () => openDateRangeDialog(dateFilterType)\n : undefined\n }\n onOperatorChange={(operator) =>\n setFilters((previous) =>\n previous.map((entry) =>\n entry.id === filter.id ? { ...entry, operator } : entry\n )\n )\n }\n onRemove={() =>\n setFilters((previous) =>\n previous.filter((entry) => entry.id !== filter.id)\n )\n }\n onSelectDatePreset={(preset) =>\n setFilters((previous) =>\n previous.map((entry) =>\n entry.id === filter.id\n ? {\n ...entry,\n operator:\n entry.operator === "before" ||\n entry.operator === "after"\n ? entry.operator\n : "after",\n value: [preset],\n }\n : entry\n )\n )\n }\n onToggleFileType={toggleFileTypeFilterValue}\n />\n )\n })}\n <button\n type="button"\n onClick={() => setFilters([])}\n className="rounded-md px-1.5 py-0.5 transition-colors outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"\n >\n Clear\n </button>\n </div>\n ) : null}\n <div className="relative min-h-0 flex-1">\n {isLoadingCurrentFolder && currentEntries.length === 0 ? (\n <FileSystemEmptyState label="Loading…" isLoading />\n ) : currentEntries.length === 0 &&\n (view !== "columns" || isSearching || hasActiveFilters) ? (\n <FileSystemEmptyState\n label={\n isSearching\n ? `No results for “${searchInput.trim()}”`\n : hasActiveFilters\n ? "No items match the active filters"\n : "This folder is empty"\n }\n />\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 {isSearching\n ? currentEntries.length === 1\n ? "result"\n : "results"\n : currentEntries.length === 1\n ? "item"\n : "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 === "image" ? (\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 // The pooled preview reparents into this host (see the layout\n // effect above), so a viewer the gallery already loaded\n // carries over live instead of remounting behind a loading\n // state.\n <div\n ref={dialogStageHostRef}\n className="flex h-full min-h-0 flex-1 flex-col"\n />\n )}\n </DialogContent>\n ) : null}\n {/* The pooled previews. Rendered inside <Dialog> so the dialog\n variant\'s close toolbar button keeps its context; each portal\'s\n container never changes, the container\'s parent does. */}\n {stagePool.map((path) => {\n const file = index.files.get(path)\n const container = stageContainers.get(path)\n\n if (!file || !container) return null\n\n const isOpenedInDialog =\n openedFile !== null &&\n openedFile.kind !== "image" &&\n openedFile.file.path === path\n\n return createPortal(\n <FileSystemGalleryStage\n file={file}\n getFileUrl={getFileUrl}\n loadPreviewImageUrl={loadPreviewImageUrl}\n pageUrlCache={pageUrlCache}\n renderFilePreview={renderFilePreview}\n toolbarActions={\n isOpenedInDialog ? viewerCloseToolbarAction : undefined\n }\n urlCache={resolvedUrlCache}\n variant={isOpenedInDialog ? "dialog" : "stage"}\n />,\n container,\n path\n )\n })}\n </Dialog>\n {dateRangeDialog ? (\n <FileSystemDateRangeDialog\n initialRange={dateRangeDialog.initialRange}\n onApply={(from, to) => {\n applyCustomDateRange(dateRangeDialog.type, from, to)\n setDateRangeDialog(null)\n }}\n onClose={() => setDateRangeDialog(null)}\n />\n ) : null}\n </div>\n )\n}\n\n// Shared style for the ghost icon buttons in the toolbar.\nconst TOOLBAR_ICON_BUTTON_CLASSNAME =\n "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"\n\n// macOS Finder-style toolbar search. At the full layout it sits inline in\n// the header\'s right column; at compact widths it collapses into a ghost\n// icon button that opens the input in a popover (a dot marks the button\n// while a query keeps filtering the views).\nfunction FileSystemSearchField({\n inputRef,\n isExpanded,\n layout,\n onExpandedChange,\n onValueChange,\n value,\n}: {\n inputRef: React.RefObject<HTMLInputElement | null>\n isExpanded: boolean\n layout: "full" | "compact" | "minimal"\n onExpandedChange: (isExpanded: boolean) => void\n onValueChange: (value: string) => void\n value: string\n}) {\n const isInline = layout === "full"\n\n React.useEffect(() => {\n if (!isInline && isExpanded) inputRef.current?.focus()\n }, [inputRef, isExpanded, isInline])\n\n const input = (\n <div\n className={cn(\n "relative flex h-7 min-w-0 flex-1 items-center rounded-lg border border-input bg-popover text-sm text-foreground shadow-xs/5 transition-shadow outline-none not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-focus-within:before:shadow-[0_1px_--theme(--color-black/4%)] focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-1 focus-within:ring-offset-background dark:bg-input/32 dark:not-focus-within:before:shadow-[0_-1px_--theme(--color-white/6%)]",\n isInline && "max-w-56"\n )}\n >\n <HugeiconsIcon\n icon={Search01Icon}\n className="pointer-events-none absolute left-2 size-3.5 text-muted-foreground"\n />\n <input\n ref={inputRef}\n type="text"\n role="searchbox"\n aria-label="Search files"\n placeholder="Search"\n value={value}\n onChange={(event) => onValueChange(event.target.value)}\n onKeyDown={(event) => {\n if (event.key !== "Escape") return\n event.preventDefault()\n event.stopPropagation()\n if (value) {\n onValueChange("")\n } else {\n onExpandedChange(false)\n event.currentTarget.blur()\n }\n }}\n className="h-full w-full min-w-0 rounded-[inherit] bg-transparent pr-6 pl-7 outline-none placeholder:text-muted-foreground"\n />\n {value ? (\n <button\n type="button"\n aria-label="Clear search"\n onClick={() => {\n onValueChange("")\n inputRef.current?.focus()\n }}\n className="absolute right-1 flex size-5 items-center justify-center rounded-sm text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"\n >\n <HugeiconsIcon icon={Cancel01Icon} className="size-3" />\n </button>\n ) : null}\n </div>\n )\n\n if (isInline) {\n // A fixed basis (not flex-1) keeps the whole toolbar cluster packed\n // against the header\'s right edge; the input shrinks first when the\n // header tightens.\n return <div className="flex w-56 min-w-32 items-center">{input}</div>\n }\n\n return (\n <Popover open={isExpanded} onOpenChange={onExpandedChange}>\n <PopoverTrigger\n render={\n <button\n type="button"\n aria-label="Search"\n title="Search"\n className={cn(TOOLBAR_ICON_BUTTON_CLASSNAME, "relative")}\n />\n }\n >\n <HugeiconsIcon icon={Search01Icon} className="size-4" />\n {value ? (\n <span className="absolute top-1 right-1 size-1.5 rounded-full bg-primary" />\n ) : null}\n </PopoverTrigger>\n <PopoverContent align="end" sideOffset={6} className="w-64 p-1">\n {input}\n </PopoverContent>\n </Popover>\n )\n}\n\n// Toolbar "sort by" select. The full layout shows the active key\'s label; at\n// compact widths the trigger collapses to the sort glyph + chevron.\nfunction FileSystemSortSelect({\n layout,\n onKeyChange,\n showLabel,\n sort,\n}: {\n layout: "full" | "compact" | "minimal"\n onKeyChange: (key: FileSystemSortKey) => void\n showLabel: boolean\n sort: FileSystemSortState\n}) {\n const activeOption = SORT_OPTIONS.find((option) => option.key === sort.key)\n\n return (\n <Select\n value={sort.key}\n onValueChange={(value) => onKeyChange(value as FileSystemSortKey)}\n >\n <SelectTrigger\n size="sm"\n aria-label="Sort by"\n title="Sort by"\n className="h-7 min-h-7 w-auto min-w-0 shrink-0 [&_svg]:size-4"\n >\n <SelectValue>\n <span className="flex items-center gap-1.5">\n <HugeiconsIcon icon={ArrowUpDownIcon} className="size-4" />\n {layout === "full" && showLabel ? activeOption?.triggerLabel : null}\n </span>\n </SelectValue>\n </SelectTrigger>\n <SelectContent align="end" alignItemWithTrigger={false}>\n {SORT_OPTIONS.map((option) => (\n <SelectItem key={option.key} value={option.key}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n )\n}\n\n// Searchable file-type list (cmdk) rendered inside a menu popup, so the\n// long MIME list can be filtered by typing. Selection toggles stay open for\n// multi-select; ArrowUp/Down and Enter come from cmdk\'s combobox semantics.\nfunction FileSystemFileTypeCommand({\n checkedMimes,\n onToggle,\n options,\n}: {\n checkedMimes: string[]\n onToggle: (mime: string, checked: boolean) => void\n options: FileTypeFilterOption[]\n}) {\n const inputRef = React.useRef<HTMLInputElement | null>(null)\n\n // The menu focuses its popup when it opens; pull focus into the search\n // field so typing filters immediately.\n React.useEffect(() => {\n const frame = requestAnimationFrame(() => inputRef.current?.focus())\n\n return () => cancelAnimationFrame(frame)\n }, [])\n\n return (\n <Command\n // -m-1 spans the menu viewport\'s built-in padding so the search\n // field\'s bottom border runs edge to edge.\n className="-m-1 w-[calc(100%+--spacing(2))] bg-transparent"\n // cmdk owns the keyboard while focus is in the list; only Escape\n // (close the menu) and Tab continue outward.\n onKeyDown={(event) => {\n if (event.key !== "Escape" && event.key !== "Tab") {\n event.stopPropagation()\n }\n }}\n >\n <CommandInput\n ref={inputRef}\n placeholder="Search file types…"\n className="h-9"\n />\n <CommandList className="max-h-none">\n <CommandEmpty>No file types found.</CommandEmpty>\n <ScrollArea orientation="vertical" className="h-auto max-h-64">\n <CommandGroup>\n {options.map((option) => {\n const isChecked = checkedMimes.includes(option.mime)\n\n return (\n <CommandItem\n key={option.mime}\n value={option.label}\n keywords={[option.mime]}\n onSelect={() => onToggle(option.mime, !isChecked)}\n >\n <HugeiconsIcon\n icon={Tick02Icon}\n className={cn(\n "size-4 text-foreground",\n !isChecked && "opacity-0"\n )}\n />\n <FileTypeIcon\n fileName={option.iconFileName}\n className="size-4"\n />\n {option.label}\n </CommandItem>\n )\n })}\n </CommandGroup>\n </ScrollArea>\n </CommandList>\n </Command>\n )\n}\n\n// Toolbar filter menu: file types as a searchable checklist, dates as\n// single-select presets plus a custom range, mirroring Extend\'s table\n// filters.\nfunction FileSystemFilterMenu({\n fileTypeOptions,\n filters,\n onOpenCustomRange,\n onSelectDatePreset,\n onToggleFileType,\n}: {\n fileTypeOptions: FileTypeFilterOption[]\n filters: FileSystemFilter[]\n onOpenCustomRange: (type: FileSystemDateFilterType) => void\n onSelectDatePreset: (type: FileSystemDateFilterType, preset: string) => void\n onToggleFileType: (mime: string, checked: boolean) => void\n}) {\n const fileTypeFilter = filters.find((filter) => filter.type === "fileType")\n\n return (\n <DropdownMenu>\n <DropdownMenuTrigger\n render={\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Filter"\n title="Filter"\n className="relative size-7 sm:size-7"\n />\n }\n >\n <HugeiconsIcon icon={FilterIcon} className="size-4" />\n {filters.length > 0 ? (\n <span className="absolute top-1 right-1 size-1.5 rounded-full bg-primary" />\n ) : null}\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="min-w-44">\n <DropdownMenuSub>\n <DropdownMenuSubTrigger>\n <HugeiconsIcon\n icon={File01Icon}\n className="size-4 text-muted-foreground"\n />\n File type\n </DropdownMenuSubTrigger>\n <DropdownMenuSubContent className="w-60">\n <FileSystemFileTypeCommand\n checkedMimes={fileTypeFilter?.value ?? []}\n onToggle={onToggleFileType}\n options={fileTypeOptions}\n />\n </DropdownMenuSubContent>\n </DropdownMenuSub>\n {(["dateModified", "dateCreated"] as const).map((type) => (\n <DropdownMenuSub key={type}>\n <DropdownMenuSubTrigger>\n <HugeiconsIcon\n icon={Calendar03Icon}\n className="size-4 text-muted-foreground"\n />\n {FILTER_TYPE_LABELS[type]}\n </DropdownMenuSubTrigger>\n <DropdownMenuSubContent>\n <ScrollArea orientation="vertical" className="h-auto max-h-72">\n {DATE_FILTER_PRESETS.map((preset) => (\n <DropdownMenuItem\n key={preset}\n onClick={() => onSelectDatePreset(type, preset)}\n >\n {preset}\n </DropdownMenuItem>\n ))}\n <DropdownMenuItem onClick={() => onOpenCustomRange(type)}>\n Custom date range…\n </DropdownMenuItem>\n </ScrollArea>\n </DropdownMenuSubContent>\n </DropdownMenuSub>\n ))}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nconst FILTER_PILL_SEGMENT_CLASSNAME =\n "flex h-5 items-center gap-1 border border-l-0 bg-background px-1.5 whitespace-nowrap text-foreground"\n\nconst FILTER_PILL_BUTTON_CLASSNAME = cn(\n FILTER_PILL_SEGMENT_CLASSNAME,\n "transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"\n)\n\n// One applied filter, rendered as a segmented pill in the status bar:\n// type · operator · value · remove, each segment interactive like Extend\'s\n// table filter pills.\nfunction FileSystemFilterPill({\n fileTypeOptions,\n filter,\n onOpenCustomRange,\n onOperatorChange,\n onRemove,\n onSelectDatePreset,\n onToggleFileType,\n}: {\n fileTypeOptions: FileTypeFilterOption[]\n filter: FileSystemFilter\n onOpenCustomRange?: () => void\n onOperatorChange: (operator: FileSystemFilterOperator) => void\n onRemove: () => void\n onSelectDatePreset: (preset: string) => void\n onToggleFileType: (mime: string, checked: boolean) => void\n}) {\n const isCustomRange =\n filter.type !== "fileType" && isCustomDateRangeValue(filter.value)\n const selectedTypeLabels =\n filter.type === "fileType"\n ? filter.value.map(\n (mime) =>\n fileTypeOptions.find((option) => option.mime === mime)?.label ??\n mime\n )\n : []\n\n return (\n <div className="flex items-center text-xs">\n <span\n className={cn(\n FILTER_PILL_SEGMENT_CLASSNAME,\n "rounded-l-md border-l text-primary"\n )}\n >\n <HugeiconsIcon\n icon={filter.type === "fileType" ? File01Icon : Calendar03Icon}\n className="size-3"\n />\n {FILTER_TYPE_LABELS[filter.type]}\n </span>\n <DropdownMenu>\n <DropdownMenuTrigger\n render={\n <button\n type="button"\n className={cn(FILTER_PILL_BUTTON_CLASSNAME, "text-primary")}\n />\n }\n >\n {FILTER_OPERATOR_LABELS[filter.operator]}\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="min-w-28">\n {filterOperatorChoices(filter).map((operator) => (\n <DropdownMenuItem\n key={operator}\n onClick={() => onOperatorChange(operator)}\n >\n {FILTER_OPERATOR_LABELS[operator]}\n </DropdownMenuItem>\n ))}\n </DropdownMenuContent>\n </DropdownMenu>\n {filter.type === "fileType" ? (\n <DropdownMenu>\n <DropdownMenuTrigger\n render={\n <button\n type="button"\n title={selectedTypeLabels.join(", ")}\n className={FILTER_PILL_BUTTON_CLASSNAME}\n />\n }\n >\n {filter.value.length === 1\n ? selectedTypeLabels[0]\n : `${filter.value.length} selected`}\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="w-60">\n <FileSystemFileTypeCommand\n checkedMimes={filter.value}\n onToggle={onToggleFileType}\n options={fileTypeOptions}\n />\n </DropdownMenuContent>\n </DropdownMenu>\n ) : isCustomRange ? (\n <button\n type="button"\n onClick={onOpenCustomRange}\n className={FILTER_PILL_BUTTON_CLASSNAME}\n >\n {filter.value\n .map((value) => new Date(value).toLocaleDateString("en-US"))\n .join(" – ")}\n </button>\n ) : (\n <DropdownMenu>\n <DropdownMenuTrigger\n render={\n <button type="button" className={FILTER_PILL_BUTTON_CLASSNAME} />\n }\n >\n {filter.value[0]}\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start">\n <ScrollArea orientation="vertical" className="h-auto max-h-72">\n {DATE_FILTER_PRESETS.map((preset) => (\n <DropdownMenuItem\n key={preset}\n onClick={() => onSelectDatePreset(preset)}\n >\n {preset}\n </DropdownMenuItem>\n ))}\n <DropdownMenuItem onClick={onOpenCustomRange}>\n Custom date range…\n </DropdownMenuItem>\n </ScrollArea>\n </DropdownMenuContent>\n </DropdownMenu>\n )}\n <button\n type="button"\n aria-label={`Remove ${FILTER_TYPE_LABELS[filter.type]} filter`}\n onClick={onRemove}\n className={cn(\n FILTER_PILL_BUTTON_CLASSNAME,\n "rounded-r-md px-1 text-muted-foreground hover:text-foreground"\n )}\n >\n <HugeiconsIcon icon={Cancel01Icon} className="size-3" />\n </button>\n </div>\n )\n}\n\nfunction formatDateInputValue(date: Date | undefined) {\n if (!date) return ""\n\n const pad = (value: number) => String(value).padStart(2, "0")\n\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`\n}\n\nfunction parseDateInputValue(value: string) {\n const trimmed = value.trim()\n\n if (!trimmed) return undefined\n\n const isoMatch = /^(\\d{4})-(\\d{1,2})-(\\d{1,2})$/.exec(trimmed)\n\n if (isoMatch) {\n const date = new Date(\n Number(isoMatch[1]),\n Number(isoMatch[2]) - 1,\n Number(isoMatch[3])\n )\n\n return Number.isNaN(date.getTime()) ? undefined : date\n }\n\n const parsed = Date.parse(trimmed)\n\n return Number.isNaN(parsed) ? undefined : new Date(parsed)\n}\n\nconst DATE_RANGE_DIALOG_PRESETS = [\n "Last 7 days",\n "This month",\n "Last 1 month",\n "Last 3 months",\n "This year",\n "Last 12 months",\n]\n\nfunction dateRangePresetRange(preset: string) {\n const from = new Date()\n const to = new Date()\n\n from.setHours(0, 0, 0, 0)\n to.setHours(23, 59, 59, 999)\n\n switch (preset) {\n case "Last 7 days":\n from.setDate(from.getDate() - 6)\n break\n case "This month":\n from.setDate(1)\n break\n case "Last 1 month":\n from.setMonth(from.getMonth() - 1)\n break\n case "Last 3 months":\n from.setMonth(from.getMonth() - 3)\n break\n case "This year":\n from.setMonth(0, 1)\n break\n case "Last 12 months":\n from.setFullYear(from.getFullYear() - 1)\n break\n }\n return { from, to }\n}\n\nconst WEEKDAY_LABELS = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]\n\nfunction calendarDayKey(date: Date) {\n return date.getFullYear() * 10_000 + date.getMonth() * 100 + date.getDate()\n}\n\n// Two-month range calendar for the custom date range dialog (one month at\n// phone widths). Clicking sets the start, then the end; clicking before the\n// start swaps the ends, and a third click restarts the range.\nfunction FileSystemRangeCalendar({\n onSelect,\n range,\n}: {\n onSelect: (range: { from?: Date; to?: Date }) => void\n range: { from?: Date; to?: Date }\n}) {\n const [viewMonth, setViewMonth] = React.useState(() => {\n const base = range.from ?? new Date()\n\n return new Date(base.getFullYear(), base.getMonth(), 1)\n })\n const months = [\n viewMonth,\n new Date(viewMonth.getFullYear(), viewMonth.getMonth() + 1, 1),\n ]\n const fromKey = range.from ? calendarDayKey(range.from) : null\n const toKey = range.to ? calendarDayKey(range.to) : null\n const todayKey = calendarDayKey(new Date())\n\n const handleDayClick = (day: Date) => {\n if (!range.from || range.to) {\n onSelect({ from: day })\n } else if (calendarDayKey(day) < calendarDayKey(range.from)) {\n onSelect({ from: day, to: range.from })\n } else {\n onSelect({ from: range.from, to: day })\n }\n }\n\n return (\n <div className="relative">\n <button\n type="button"\n aria-label="Previous month"\n onClick={() =>\n setViewMonth(\n (previous) =>\n new Date(previous.getFullYear(), previous.getMonth() - 1, 1)\n )\n }\n className="absolute top-0 left-0 flex size-6 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"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4" />\n </button>\n <button\n type="button"\n aria-label="Next month"\n onClick={() =>\n setViewMonth(\n (previous) =>\n new Date(previous.getFullYear(), previous.getMonth() + 1, 1)\n )\n }\n className="absolute top-0 right-0 flex size-6 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"\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-4" />\n </button>\n <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">\n {months.map((month, monthIndex) => {\n const firstWeekday = month.getDay()\n const dayCount = new Date(\n month.getFullYear(),\n month.getMonth() + 1,\n 0\n ).getDate()\n const cells = [\n ...Array.from({ length: firstWeekday }, () => null),\n ...Array.from(\n { length: dayCount },\n (_, index) =>\n new Date(month.getFullYear(), month.getMonth(), index + 1)\n ),\n ]\n\n return (\n <div\n key={`${month.getFullYear()}-${month.getMonth()}`}\n className={cn(monthIndex === 1 && "max-sm:hidden")}\n >\n <div className="text-center text-sm leading-6 font-medium">\n {month.toLocaleDateString("en-US", {\n month: "long",\n year: "numeric",\n })}\n </div>\n <div className="mt-1 grid grid-cols-7 text-center text-xs text-muted-foreground">\n {WEEKDAY_LABELS.map((weekday) => (\n <span key={weekday} className="h-6 leading-6">\n {weekday}\n </span>\n ))}\n </div>\n <div className="grid grid-cols-7 gap-y-px">\n {cells.map((day, cellIndex) => {\n if (!day) return <span key={cellIndex} />\n\n const dayKey = calendarDayKey(day)\n const isFrom = dayKey === fromKey\n const isTo = dayKey === toKey\n const isWithinRange =\n fromKey !== null &&\n toKey !== null &&\n dayKey > fromKey &&\n dayKey < toKey\n\n return (\n <button\n key={cellIndex}\n type="button"\n onClick={() => handleDayClick(day)}\n className={cn(\n "flex h-7 items-center justify-center rounded-md text-xs tabular-nums transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",\n isWithinRange && "rounded-none bg-accent",\n (isFrom || isTo) &&\n "bg-primary text-primary-foreground hover:bg-primary",\n isFrom &&\n toKey !== null &&\n fromKey !== toKey &&\n "rounded-r-none",\n isTo && fromKey !== toKey && "rounded-l-none",\n dayKey === todayKey &&\n !isFrom &&\n !isTo &&\n "font-semibold text-primary"\n )}\n >\n {day.getDate()}\n </button>\n )\n })}\n </div>\n </div>\n )\n })}\n </div>\n </div>\n )\n}\n\n// Custom date range dialog mirroring Extend\'s table filters: From/To inputs,\n// a two-month range calendar, and quick presets. Applied ranges span from\n// the start of the first day to the end of the last.\nfunction FileSystemDateRangeDialog({\n initialRange,\n onApply,\n onClose,\n}: {\n initialRange?: { from: Date; to: Date }\n onApply: (from: Date, to: Date) => void\n onClose: () => void\n}) {\n const [range, setRange] = React.useState<{ from?: Date; to?: Date }>(\n () => initialRange ?? {}\n )\n const [fromInput, setFromInput] = React.useState(() =>\n formatDateInputValue(initialRange?.from)\n )\n const [toInput, setToInput] = React.useState(() =>\n formatDateInputValue(initialRange?.to)\n )\n\n const selectRange = (next: { from?: Date; to?: Date }) => {\n setRange(next)\n if (next.from) setFromInput(formatDateInputValue(next.from))\n if (next.to) setToInput(formatDateInputValue(next.to))\n }\n\n const dateField = (\n label: string,\n value: string,\n onChange: (value: string) => void\n ) => (\n <div className="flex flex-1 flex-col gap-1.5">\n <span className="text-xs font-medium">{label}</span>\n <div className="relative flex items-center">\n <HugeiconsIcon\n icon={Calendar03Icon}\n className="pointer-events-none absolute left-2.5 size-3.5 text-muted-foreground"\n />\n <Input\n type="text"\n value={value}\n placeholder="YYYY-MM-DD"\n aria-label={`${label} date`}\n onChange={(event) => onChange(event.target.value)}\n className="h-8 pl-8 sm:h-8"\n />\n </div>\n </div>\n )\n\n return (\n <Dialog\n open\n onOpenChange={(open) => {\n if (!open) onClose()\n }}\n >\n <DialogContent className="w-[30rem] max-w-[calc(100vw-2rem)]">\n <DialogHeader>\n <DialogTitle>Custom date range</DialogTitle>\n </DialogHeader>\n <DialogPanel className="flex flex-col gap-4">\n <div className="flex gap-3">\n {dateField("From", fromInput, (value) => {\n setFromInput(value)\n\n const parsed = parseDateInputValue(value)\n\n if (parsed)\n setRange((previous) => ({ ...previous, from: parsed }))\n })}\n {dateField("To", toInput, (value) => {\n setToInput(value)\n\n const parsed = parseDateInputValue(value)\n\n if (parsed) setRange((previous) => ({ ...previous, to: parsed }))\n })}\n </div>\n <FileSystemRangeCalendar range={range} onSelect={selectRange} />\n <div className="grid grid-cols-3 gap-2">\n {DATE_RANGE_DIALOG_PRESETS.map((preset) => (\n <Button\n key={preset}\n type="button"\n variant="outline"\n size="sm"\n onClick={() => selectRange(dateRangePresetRange(preset))}\n >\n {preset}\n </Button>\n ))}\n </div>\n </DialogPanel>\n <DialogFooter>\n <Button type="button" variant="outline" onClick={onClose}>\n Cancel\n </Button>\n <Button\n type="button"\n disabled={!range.from || !range.to}\n onClick={() => {\n if (!range.from || !range.to) return\n\n const from = new Date(range.from)\n const to = new Date(range.to)\n\n from.setHours(0, 0, 0, 0)\n to.setHours(23, 59, 59, 999)\n onApply(from, to)\n }}\n >\n Apply\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\ntype FileSystemViewProps = {\n currentPath: string\n entries: FileSystemEntry[]\n fileFilter: ((file: FileEntry) => boolean) | null\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 onSortColumnClick: (key: FileSystemSortKey) => void\n /** Pooled paths currently attached to the DOM (reveal instantly). */\n attachedStagePaths: string[]\n /** `"path#pageIndex"` → thumbnail URL, shared by every pager. */\n pageUrlCache: Map<string, string>\n /** Admits a file into the root-owned keep-alive preview pool. */\n poolStagePath: (path: string) => void\n /** Mounts/unmounts the gallery host element for a pooled path. */\n registerStageHost: (path: string, element: HTMLElement | null) => void\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n searchQuery: string\n selectedEntry: FileSystemEntry | null\n selectedPath: string | null\n sort: FileSystemSortState\n /** Expanded tree folders per folder path, surviving view switches. */\n treeExpansionRef: React.RefObject<Map<string, readonly string[]>>\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. An\n// optional `cache` shared across mounts serves revisited files synchronously:\n// no repeat presign round-trip (and no loading flash), and the stable URL\n// keeps the browser\'s HTTP cache valid for already-fetched content.\nfunction useResolvedFileUrl(\n file: FileEntry | null,\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>,\n cache?: Map<string, string>\n) {\n const [state, setState] = React.useState<{\n isResolving: boolean\n url: string | null\n }>(() => ({\n isResolving: false,\n url: file ? (file.url ?? cache?.get(file.path) ?? null) : 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 const knownUrl =\n fileUrl ?? (filePath ? (cache?.get(filePath) ?? null) : null)\n\n if (!currentFile || knownUrl || !getFileUrl) {\n setState({ isResolving: false, url: knownUrl })\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 (url) cache?.set(currentFile.path, 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 }, [cache, 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// Type-ahead buffers reset after this idle period, like Finder.\nconst TYPE_AHEAD_RESET_MS = 700\n\n// Letters and digits only — the same key test the tree uses — so shortcuts\n// and whitespace scrolling stay untouched.\nfunction isTypeAheadKey(event: React.KeyboardEvent) {\n return (\n event.key.length === 1 &&\n /^[\\p{L}\\p{N}]$/u.test(event.key) &&\n !event.altKey &&\n !event.ctrlKey &&\n !event.metaKey\n )\n}\n\n// Shared Finder-style type-ahead used by every view: printable keys\n// accumulate a buffer that jumps to the next entry whose name starts with\n// it, and repeating a single letter cycles through entries with that\n// prefix. Each view passes its own display-ordered candidate list, so the\n// same keystrokes land on the same file everywhere.\nfunction useEntryTypeAhead() {\n const stateRef = React.useRef({ buffer: "", timeout: 0 })\n\n React.useEffect(() => {\n const state = stateRef.current\n\n return () => window.clearTimeout(state.timeout)\n }, [])\n\n return React.useCallback(\n (\n event: React.KeyboardEvent,\n entries: readonly FileSystemEntry[],\n currentIndex: number\n ) => {\n if (!isTypeAheadKey(event) || entries.length === 0) return null\n\n // Embedded viewers (and any future inputs) keep their keystrokes.\n const target = event.target\n\n if (\n target instanceof HTMLElement &&\n (target.isContentEditable ||\n target.tagName === "INPUT" ||\n target.tagName === "TEXTAREA" ||\n target.tagName === "SELECT")\n ) {\n return null\n }\n\n const state = stateRef.current\n\n window.clearTimeout(state.timeout)\n state.timeout = window.setTimeout(() => {\n state.buffer = ""\n }, TYPE_AHEAD_RESET_MS)\n state.buffer += event.key.toLowerCase()\n\n // A repeated single letter advances past the current entry; a longer\n // buffer refines the match in place.\n const startIndex =\n currentIndex < 0\n ? 0\n : currentIndex + (state.buffer.length === 1 ? 1 : 0)\n\n for (let step = 0; step < entries.length; step += 1) {\n const entry = entries[(startIndex + step) % entries.length]\n\n if (entry.name.toLowerCase().startsWith(state.buffer)) {\n event.preventDefault()\n return entry\n }\n }\n event.preventDefault()\n return null\n },\n []\n )\n}\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\n// Icon grid geometry (px at the default 16px root font size). Tiles have a\n// fixed height — a 4rem glyph box plus a reserved two-line label — so rows\n// share one stride and the grid can window cleanly.\nconst ICON_GRID_PADDING = 12 // p-3\nconst ICON_MIN_TILE_WIDTH = 104 // 6.5rem\nconst ICON_TILE_GAP_X = 4 // gap-x-1\nconst ICON_TILE_HEIGHT = 102 // h-16 glyph box + gap-1.5 + two text-xs lines\nconst ICON_ROW_GAP = 12 // gap-y-3\nconst ICON_ROW_STRIDE = ICON_TILE_HEIGHT + ICON_ROW_GAP\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 const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const typeAhead = useEntryTypeAhead()\n // The column count mirrors what `repeat(auto-fill, minmax(6.5rem, 1fr))`\n // produces (the CSS owns the actual layout) so item indices map to grid\n // rows — the windowing below depends on that mapping. It stays null until\n // the first client measure; server markup must not guess.\n const [columnCount, setColumnCount] = React.useState<number | null>(null)\n\n React.useLayoutEffect(() => {\n const viewport = viewportRef.current\n\n if (!viewport || typeof ResizeObserver === "undefined") return\n\n const update = () => {\n const available = viewport.clientWidth - ICON_GRID_PADDING * 2\n\n setColumnCount(\n Math.max(\n 1,\n Math.floor(\n (available + ICON_TILE_GAP_X) /\n (ICON_MIN_TILE_WIDTH + ICON_TILE_GAP_X)\n )\n )\n )\n }\n const observer = new ResizeObserver(update)\n\n update()\n observer.observe(viewport)\n return () => observer.disconnect()\n }, [])\n\n const resolvedColumnCount = columnCount ?? 1\n const rowCount = Math.ceil(entries.length / resolvedColumnCount)\n const { end, start } = useVirtualWindow({\n count: rowCount,\n itemStride: ICON_ROW_STRIDE,\n leadingPx: ICON_GRID_PADDING,\n overscan: 4,\n viewportRef,\n })\n const visibleEntries = entries.slice(\n start * resolvedColumnCount,\n end * resolvedColumnCount\n )\n\n // Selection can land outside the window (view switches, shrinking results);\n // bring its row back into the viewport so the tile mounts and is focusable.\n React.useLayoutEffect(() => {\n if (!selectedPath) return\n\n const entryIndex = entries.findIndex((entry) => entry.path === selectedPath)\n\n if (entryIndex === -1) return\n\n scrollIndexIntoView({\n index: Math.floor(entryIndex / resolvedColumnCount),\n itemSize: ICON_TILE_HEIGHT,\n itemStride: ICON_ROW_STRIDE,\n leadingPx: ICON_GRID_PADDING,\n viewport: viewportRef.current,\n })\n }, [entries, resolvedColumnCount, selectedPath])\n\n // Roving tabindex: the grid is a single tab stop (the selected tile when\n // rendered, else the first rendered one), so Shift+Tab returns to the\n // toolbar like in the list view.\n const tabStopPath = visibleEntries.some(\n (entry) => entry.path === selectedPath\n )\n ? selectedPath\n : (visibleEntries[0]?.path ?? null)\n\n return (\n <ScrollArea\n orientation="vertical"\n viewportRef={viewportRef}\n viewportClassName="p-3"\n viewportProps={{\n onClick: (event) => {\n if (event.target === event.currentTarget) onSelect(null)\n },\n }}\n >\n <div\n className="relative"\n // The scroll-height spacer needs the measured column count; until\n // then the absolutely positioned grid alone defines the scrollable\n // overflow, so the server-rendered frame doesn\'t flash an\n // oversized scroll range.\n style={{\n height:\n columnCount !== null && rowCount\n ? rowCount * ICON_ROW_STRIDE - ICON_ROW_GAP\n : undefined,\n }}\n >\n <div\n role="listbox"\n aria-label="Files"\n className="absolute inset-x-0 grid gap-x-1 gap-y-3"\n // The auto-fill expression produces the same column count the\n // ResizeObserver measures (the measurement exists only for the\n // windowing math), so the server-rendered first paint is already\n // a grid instead of flashing a single stacked column until the\n // first client measure.\n style={{\n gridTemplateColumns: "repeat(auto-fill, minmax(6.5rem, 1fr))",\n top: start * ICON_ROW_STRIDE,\n }}\n onKeyDown={(event) => {\n if (!ARROW_KEYS.has(event.key)) {\n const match = typeAhead(\n event,\n entries,\n entries.findIndex((entry) => entry.path === selectedPath)\n )\n\n if (match) {\n onSelect(match)\n // The matched tile may be outside the virtual window; the\n // selection effect scrolls it in, and focus follows once it\n // has mounted.\n requestAnimationFrame(() =>\n itemRefs.current.get(match.path)?.focus()\n )\n }\n return\n }\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 {visibleEntries.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 h-[6.375rem] flex-col items-center gap-1.5 outline-none"\n >\n <span\n className={cn(\n "flex h-16 w-20 shrink-0 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 </div>\n </ScrollArea>\n )\n}\n\n// One sortable column header for the list view; the active column shows the\n// direction chevron on its right.\nfunction FileSystemListColumnHeader({\n className,\n label,\n onClick,\n sort,\n sortKey,\n}: {\n className?: string\n label: string\n onClick: (key: FileSystemSortKey) => void\n sort: FileSystemSortState\n sortKey: FileSystemSortKey\n}) {\n const isActive = sort.key === sortKey\n\n return (\n <button\n type="button"\n onClick={() => onClick(sortKey)}\n className={cn(\n "flex items-center gap-0.5 rounded-sm py-0.5 transition-colors outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",\n isActive && "text-foreground",\n className\n )}\n >\n {label}\n {isActive ? (\n <HugeiconsIcon\n icon={sort.direction === "asc" ? ArrowUp01Icon : ArrowDown01Icon}\n className="size-3 shrink-0"\n />\n ) : null}\n </button>\n )\n}\n\nfunction FileSystemListView({\n currentPath,\n fileFilter,\n index,\n onOpen,\n onSelect,\n onSortColumnClick,\n searchQuery,\n selectedPath,\n sort,\n treeExpansionRef,\n}: FileSystemViewProps) {\n // Filters narrow the path list handed to the tree; the search query stays\n // out of it so the tree\'s own search session (with match highlighting)\n // keeps handling it without remounts per keystroke.\n const relativePaths = React.useMemo(() => {\n const paths: string[] = []\n\n for (const [path, file] of index.files) {\n if (currentPath === "" || path.startsWith(currentPath)) {\n const relativePath = path.slice(currentPath.length)\n\n if (!relativePath) continue\n if (fileFilter && !fileFilter(file)) continue\n paths.push(relativePath)\n }\n }\n return paths.sort()\n }, [currentPath, fileFilter, index])\n\n if (relativePaths.length === 0) {\n return (\n <FileSystemEmptyState\n label={\n fileFilter\n ? "No items match the active filters"\n : "This folder is empty"\n }\n />\n )\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 pr-6 pl-[46px] text-xs font-medium text-muted-foreground">\n <FileSystemListColumnHeader\n className="flex-1 justify-start"\n label="Name"\n onClick={onSortColumnClick}\n sort={sort}\n sortKey="name"\n />\n <FileSystemListColumnHeader\n className="w-44 justify-start"\n label="Date Modified"\n onClick={onSortColumnClick}\n sort={sort}\n sortKey="updatedAt"\n />\n <FileSystemListColumnHeader\n className="w-20 justify-start"\n label="Size"\n onClick={onSortColumnClick}\n sort={sort}\n sortKey="size"\n />\n </div>\n {/* Keyed by folder only: navigation remounts the tree, while filter,\n sort, and manifest changes update the mounted model in place so\n folder disclosure state survives them. */}\n <FileSystemPierreTree\n key={currentPath}\n currentPath={currentPath}\n hasActiveFilters={fileFilter !== null}\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 searchQuery={searchQuery}\n sort={sort}\n treeExpansionRef={treeExpansionRef}\n />\n </div>\n )\n}\n\n// Embedded thumbnail symbols grow the sprite injected into the tree\'s shadow\n// DOM (data-URL covers can run hundreds of KB each); past this many the\n// remaining files fall back to the built-in file-type icons alone.\nconst TREE_THUMBNAIL_SPRITE_LIMIT = 400\n\nfunction FileSystemPierreTree({\n currentPath,\n hasActiveFilters,\n index,\n initialSelectedPath,\n onOpen,\n onSelect,\n relativePaths,\n searchQuery,\n sort,\n treeExpansionRef,\n}: {\n currentPath: string\n hasActiveFilters: boolean\n index: FileSystemIndex\n initialSelectedPath: string | null\n onOpen: (entry: FileSystemEntry) => void\n onSelect: (entry: FileSystemEntry | null) => void\n relativePaths: string[]\n searchQuery: string\n sort: FileSystemSortState\n treeExpansionRef: React.RefObject<Map<string, readonly string[]>>\n}) {\n // The tree\'s comparator receives whole paths, not siblings, so it walks\n // the shared segments and applies the active sort at the first level the\n // two paths diverge — keeping directories first per level, the tree\'s\n // default convention. Lookups go through the index maps, which are stable\n // across search keystrokes.\n const indexFiles = index.files\n const indexFolders = index.folders\n const sortComparator = React.useMemo<\n "default" | FileTreeSortComparator\n >(() => {\n if (\n sort.key === DEFAULT_SORT.key &&\n sort.direction === DEFAULT_SORT.direction\n ) {\n return "default"\n }\n\n const entryAtDepth = (sortEntry: FileTreeSortEntry, depth: number) => {\n const isDirectory =\n depth < sortEntry.segments.length - 1 || sortEntry.isDirectory\n const absolutePath = `${currentPath}${sortEntry.segments\n .slice(0, depth + 1)\n .join("/")}${isDirectory ? "/" : ""}`\n\n return isDirectory\n ? indexFolders.get(absolutePath)\n : indexFiles.get(absolutePath)\n }\n\n return (left, right) => {\n const sharedDepth = Math.min(left.segments.length, right.segments.length)\n\n for (let depth = 0; depth < sharedDepth; depth += 1) {\n if (left.segments[depth] === right.segments[depth]) continue\n\n const leftIsDirectory =\n depth < left.segments.length - 1 || left.isDirectory\n const rightIsDirectory =\n depth < right.segments.length - 1 || right.isDirectory\n\n if (leftIsDirectory !== rightIsDirectory) {\n return leftIsDirectory ? -1 : 1\n }\n\n const leftEntry = entryAtDepth(left, depth)\n const rightEntry = entryAtDepth(right, depth)\n\n if (leftEntry && rightEntry) {\n return compareEntriesBySort(leftEntry, rightEntry, sort)\n }\n return left.segments[depth] < right.segments[depth] ? -1 : 1\n }\n return left.segments.length - right.segments.length\n }\n }, [currentPath, indexFiles, indexFolders, sort])\n const preparedInput = React.useMemo(\n () => prepareFileTreeInput(relativePaths, { sort: sortComparator }),\n [relativePaths, sortComparator]\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. Files without\n // a thumbnail resolve through the built-in complete icon set instead — the\n // same colored file-type icons the other views use. 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 let thumbnailCount = 0\n\n for (const relativePath of relativePaths) {\n if (thumbnailCount >= TREE_THUMBNAIL_SPRITE_LIMIT) break\n\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 thumbnailCount += 1\n }\n\n return {\n byFileName,\n colored: true,\n remap: {\n "file-tree-icon-chevron": {\n name: "file-system-chevron",\n viewBox: "0 0 24 24",\n },\n },\n set: "complete" as const,\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 // Remounts (folder changes, manifest updates) keep the active filter.\n initialSearchQuery: searchQuery || null,\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 /* The primary surface is the opposite of the mode\'s background, so\n the row\'s light-dark() icon colors resolve against the opposite\n scheme — light-palette icons on the light pill in dark mode and\n vice versa. */\n color-scheme: var(--fs-selected-color-scheme, normal);\n }\n button[data-type=\'item\'][data-item-selected] *:not([data-icon-token]):not([data-icon-token] *),\n button[data-type=\'item\'][data-item-selected] [data-item-section]::before {\n color: var(--color-primary-foreground) !important;\n }\n [data-item-section=\'decoration\'] > span {\n display: grid;\n grid-template-columns: 11rem 5rem;\n white-space: nowrap;\n /* The size cell is the span\'s anonymous text item, so alignment\n rides on text-align: the span\'s right applies to it while the\n date cell (::before) overrides back to left. */\n text-align: right;\n }\n [data-item-section=\'decoration\'] > span::before {\n content: attr(title);\n text-align: left;\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 folders currently expanded in the mounted model, derived from the\n // given path list (the model knows the rows; the paths name the\n // directories to ask about).\n const collectExpandedDirectories = React.useCallback(\n (paths: readonly string[]) => {\n const expandedPaths: string[] = []\n\n for (const directoryPath of directoryPathsOf(paths)) {\n const item =\n model.getItem(directoryPath) ?? model.getItem(`${directoryPath}/`)\n\n if (item && "isExpanded" in item && item.isExpanded()) {\n expandedPaths.push(directoryPath)\n }\n }\n return expandedPaths\n },\n [model]\n )\n\n // Opens every given folder on the mounted model (no-ops on the already\n // open ones).\n const expandDirectories = React.useCallback(\n (directoryPaths: Iterable<string>) => {\n for (const directoryPath of directoryPaths) {\n const item =\n model.getItem(directoryPath) ?? model.getItem(`${directoryPath}/`)\n\n if (item && "isExpanded" in item && !item.isExpanded()) {\n item.toggle()\n }\n }\n },\n [model]\n )\n\n // Sort and filter changes swap the prepared input in place — remounting\n // would reset every folder\'s disclosure. The folders expanded in the\n // outgoing path list, the selection, and the active search query are\n // captured first and handed back to the reset.\n const appliedPreparedInputRef = React.useRef(preparedInput)\n // Filter bookkeeping: the latest prop (for unmount-time decisions), the\n // state at the last applied reset (for transition detection), and the\n // disclosure to restore once the filters clear.\n const hasActiveFiltersRef = React.useRef(hasActiveFilters)\n const filteredAtLastResetRef = React.useRef(hasActiveFilters)\n const preFilterExpansionRef = React.useRef<readonly string[] | null>(null)\n\n React.useEffect(() => {\n hasActiveFiltersRef.current = hasActiveFilters\n })\n\n React.useEffect(() => {\n const previousPreparedInput = appliedPreparedInputRef.current\n\n if (previousPreparedInput === preparedInput) return\n appliedPreparedInputRef.current = preparedInput\n\n const wasFiltered = filteredAtLastResetRef.current\n\n filteredAtLastResetRef.current = hasActiveFilters\n\n // Filters reveal their matches the way the search session does: every\n // folder on the way to a match opens. The disclosure from just before\n // filtering is kept aside and comes back when the filters clear.\n let expandedPaths: readonly string[]\n\n if (hasActiveFilters) {\n if (!wasFiltered) {\n preFilterExpansionRef.current = collectExpandedDirectories(\n previousPreparedInput.paths\n )\n }\n expandedPaths = [...directoryPathsOf(preparedInput.paths)]\n } else if (wasFiltered) {\n expandedPaths = preFilterExpansionRef.current ?? []\n preFilterExpansionRef.current = null\n } else {\n expandedPaths = collectExpandedDirectories(previousPreparedInput.paths)\n }\n\n const searchValue = model.getSearchValue()\n\n // The `paths` argument must stay unset: when both are given, resetPaths\n // re-prepares the paths with the comparator the model was CREATED with\n // and rejects the differently-ordered prepared input. Passing only the\n // prepared input makes the reset adopt its path list as-is, and the\n // reset itself carries the selection over.\n model.resetPaths(undefined as unknown as readonly string[], {\n initialExpandedPaths: expandedPaths,\n preparedInput,\n })\n if (searchValue) model.setSearch(searchValue)\n }, [collectExpandedDirectories, hasActiveFilters, model, preparedInput])\n\n // View switches and navigation unmount the tree; remember which folders\n // were left expanded and reopen them on the next mount of this folder\n // (before paint, so the restored disclosure never flashes closed). While\n // filters are active their matches are revealed instead, and the\n // remembered disclosure is the pre-filter one.\n React.useLayoutEffect(() => {\n const expansionStore = treeExpansionRef.current\n const savedExpansion = expansionStore.get(currentPath) ?? []\n\n if (hasActiveFiltersRef.current) {\n preFilterExpansionRef.current = savedExpansion\n expandDirectories(directoryPathsOf(appliedPreparedInputRef.current.paths))\n } else {\n expandDirectories(savedExpansion)\n }\n\n return () => {\n expansionStore.set(\n currentPath,\n hasActiveFiltersRef.current\n ? (preFilterExpansionRef.current ?? [])\n : collectExpandedDirectories(appliedPreparedInputRef.current.paths)\n )\n }\n }, [\n collectExpandedDirectories,\n currentPath,\n expandDirectories,\n treeExpansionRef,\n ])\n\n // The toolbar search drives the tree\'s own search session, which filters\n // rows with hide-non-matches semantics and highlights the matched text.\n React.useEffect(() => {\n model.setSearch(searchQuery || null)\n }, [model, searchQuery])\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 // Rows live in the tree\'s shadow DOM; composedPath surfaces the row\n // element behind a pointer or keyboard event so it can resolve to a\n // manifest entry.\n const entryFromEvent = (event: React.SyntheticEvent) => {\n for (const target of event.nativeEvent.composedPath()) {\n if (!(target instanceof HTMLElement)) continue\n\n const relativePath = target.dataset?.itemPath\n\n if (!relativePath) continue\n\n const absolutePath = `${currentPath}${relativePath}`\n\n return (\n index.files.get(absolutePath) ??\n index.folders.get(normalizeFolderPath(absolutePath)) ??\n null\n )\n }\n return null\n }\n\n // The tree exposes rows by relative path; directory ids may or may not\n // carry the trailing slash depending on the call site.\n const resolveTreeItem = (relativePath: string) =>\n model.getItem(relativePath) ??\n model.getItem(\n relativePath.endsWith("/")\n ? relativePath.slice(0, -1)\n : `${relativePath}/`\n )\n\n // The tree\'s rows in display order — folders first per level, recursing\n // only into expanded folders — so type-ahead cycles exactly what\'s on\n // screen. Virtualization keeps this off the DOM; the index and the item\n // handles carry the same information.\n const collectVisibleEntries = () => {\n const visibleEntries: FileSystemEntry[] = []\n const walk = (folderPath: string) => {\n const children = index.children.get(folderPath) ?? []\n\n for (const child of children) {\n if (child.kind !== "folder") continue\n\n const item = resolveTreeItem(child.path.slice(currentPath.length))\n\n if (!item) continue\n visibleEntries.push(child)\n if ("isExpanded" in item && item.isExpanded()) walk(child.path)\n }\n for (const child of children) {\n if (child.kind === "file") visibleEntries.push(child)\n }\n }\n\n walk(currentPath)\n return visibleEntries\n }\n\n const typeAhead = useEntryTypeAhead()\n\n return (\n <PierreFileTree\n model={model}\n className="block min-h-0 flex-1"\n // Finder semantics: double-clicking a folder navigates into it and\n // double-clicking a file opens it; a single click still only toggles\n // the folder\'s disclosure.\n onDoubleClick={(event) => {\n const entry = entryFromEvent(event)\n\n if (entry) onOpen(entry)\n }}\n // Enter mirrors the other views: navigate into the focused folder or\n // open the focused file. Printable keys run the shared type-ahead\n // over the visible rows.\n onKeyDown={(event) => {\n if (event.key === "Enter") {\n const entry = entryFromEvent(event)\n\n if (entry) {\n event.preventDefault()\n onOpen(entry)\n }\n return\n }\n\n if (!isTypeAheadKey(event)) return\n\n const visibleEntries = collectVisibleEntries()\n const focusedPath = model.getFocusedPath()?.replace(/\\/$/, "") ?? null\n const focusedIndex = visibleEntries.findIndex(\n (entry) =>\n entry.path.slice(currentPath.length).replace(/\\/$/, "") ===\n focusedPath\n )\n const match = typeAhead(event, visibleEntries, focusedIndex)\n\n if (!match) return\n\n const item = resolveTreeItem(match.path.slice(currentPath.length))\n\n if (item) {\n model.scrollToPath(item.getPath())\n item.focus()\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 pageUrlCache,\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 const typeAhead = useEntryTypeAhead()\n\n const handleKeyDown = (event: React.KeyboardEvent) => {\n if (!ARROW_KEYS.has(event.key)) {\n // Type-ahead moves within the active column\'s rows, like Finder.\n const siblings =\n selectedEntry && selectedPath?.startsWith(currentPath)\n ? (index.children.get(selectedEntry.parentPath) ?? [])\n : (index.children.get(currentPath) ?? [])\n const match = typeAhead(\n event,\n siblings,\n siblings.findIndex((sibling) => sibling.path === selectedPath)\n )\n\n if (match) {\n onSelect(match)\n\n const row = rowRefs.current.get(match.path)\n\n if (row) {\n row.focus()\n } else {\n pendingFocusPathRef.current = match.path\n }\n }\n return\n }\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 // 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 {/* The Content part\'s ResizeObserver tells the scroll area when the\n trail shrinks (deselect, shallower selection) so the horizontal\n scrollbar hides; the viewport alone only observes its own box. Its\n built-in inline min-width (fit-content) would beat a min-w-full\n class, so the full-width floor is inline too. */}\n <ScrollAreaPrimitive.Content\n className="flex h-full w-max"\n style={{ minWidth: "100%" }}\n onKeyDown={handleKeyDown}\n >\n {columnPaths.map((columnPath, columnIndex) => (\n <FileSystemColumn\n key={columnPath || "(root)"}\n entries={index.children.get(columnPath) ?? []}\n index={index}\n isLoading={loadingFolders.has(columnPath)}\n onOpen={onOpen}\n onSelect={onSelect}\n rowRefs={rowRefs}\n // Scalar per-column props so the memoized column only\n // re-renders when its own rows change — a selection deeper in\n // the trail leaves ancestor columns untouched.\n selectedChildPath={\n selectedPath && pathParent(selectedPath) === columnPath\n ? selectedPath\n : null\n }\n tabStopChildPath={\n tabStopPath && pathParent(tabStopPath) === columnPath\n ? tabStopPath\n : null\n }\n trailChildPath={columnPaths[columnIndex + 1] ?? null}\n />\n ))}\n {selectedFile ? (\n // contain-inline-size zeroes the pane\'s intrinsic width so its\n // max-content contribution is exactly the min-w-60 floor — matching\n // a column\'s w-60. Otherwise long filenames or wide thumbnails\n // would nudge the overflowing trail\'s scroll width as the arrow-key\n // selection alternates between files and folders.\n <ScrollArea\n orientation="vertical"\n className="min-w-60 flex-1 contain-inline-size"\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 pageUrlCache={pageUrlCache}\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 </ScrollAreaPrimitive.Content>\n </ScrollArea>\n )\n}\n\n// Column row geometry (px at the default 16px root font size).\nconst COLUMN_PADDING = 6 // p-1.5\nconst COLUMN_ROW_HEIGHT = 28 // h-7\nconst COLUMN_ROW_GAP = 1 // gap-px\nconst COLUMN_ROW_STRIDE = COLUMN_ROW_HEIGHT + COLUMN_ROW_GAP\n\n// Memoized with scalar selection props: pressing into a deep trail only\n// re-renders the columns whose rows actually change.\nconst FileSystemColumn = React.memo(function FileSystemColumn({\n entries,\n index,\n isLoading,\n onOpen,\n onSelect,\n rowRefs,\n selectedChildPath,\n tabStopChildPath,\n trailChildPath,\n}: {\n entries: FileSystemEntry[]\n index: FileSystemIndex\n isLoading: boolean\n onOpen: (entry: FileSystemEntry) => void\n onSelect: (entry: FileSystemEntry | null) => void\n rowRefs: React.RefObject<Map<string, HTMLButtonElement>>\n selectedChildPath: string | null\n tabStopChildPath: string | null\n trailChildPath: string | null\n}) {\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const { end, start } = useVirtualWindow({\n count: entries.length,\n itemStride: COLUMN_ROW_STRIDE,\n leadingPx: COLUMN_PADDING,\n overscan: 10,\n viewportRef,\n })\n\n // Keyboard navigation can select a row this column hasn\'t mounted; scroll\n // it into the viewport so it mounts and the pending-focus effect can land.\n React.useLayoutEffect(() => {\n if (!selectedChildPath) return\n\n scrollIndexIntoView({\n index: entries.findIndex((entry) => entry.path === selectedChildPath),\n itemSize: COLUMN_ROW_HEIGHT,\n itemStride: COLUMN_ROW_STRIDE,\n leadingPx: COLUMN_PADDING,\n viewport: viewportRef.current,\n })\n }, [entries, selectedChildPath])\n\n return (\n <ScrollArea\n orientation="vertical"\n className="w-60 shrink-0 border-r"\n viewportRef={viewportRef}\n viewportClassName="p-1.5"\n viewportProps={{ "aria-label": "Files", role: "listbox" }}\n >\n {isLoading && entries.length === 0 ? (\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 <div\n className="relative"\n style={{\n height: entries.length\n ? entries.length * COLUMN_ROW_STRIDE - COLUMN_ROW_GAP\n : undefined,\n }}\n >\n <div\n className="absolute inset-x-0 flex flex-col gap-px"\n style={{ top: start * COLUMN_ROW_STRIDE }}\n >\n {entries.slice(start, end).map((entry) => {\n const isSelected = entry.path === selectedChildPath\n const isOnTrail =\n entry.kind === "folder" && entry.path === trailChildPath\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 // Selected rows sit on the primary surface — the opposite\n // of the mode\'s background — so the file-type icon swaps\n // to the opposite palette.\n data-file-system-on-primary={isSelected ? "" : undefined}\n tabIndex={entry.path === tabStopChildPath ? 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 // Selecting on press (mouse only) starts mounting the\n // child column a beat before mouseup — the immediacy\n // @pierre/trees rows have. Touch keeps selection on the\n // click so scroll gestures don\'t select.\n onPointerDown={(event) => {\n if (event.pointerType === "mouse" && event.button === 0) {\n onSelect(entry)\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 h-7 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 <FileTypeIcon\n fileName={entry.name}\n className="size-4 shrink-0"\n />\n )}\n <span className="min-w-0 flex-1 truncate">{entry.name}</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 </div>\n </div>\n )}\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\n// Filmstrip geometry (px at the default 16px root font size).\nconst GALLERY_STRIP_PADDING = 8 // p-2\nconst GALLERY_TILE_SIZE = 56 // size-14\nconst GALLERY_TILE_GAP = 6 // gap-1.5\nconst GALLERY_TILE_STRIDE = GALLERY_TILE_SIZE + GALLERY_TILE_GAP\n// How many visited stages stay mounted so stepping back to a recent file\n// restores its already-loaded preview without refetching or re-parsing;\n// also bounds the memory the keep-alive pool can hold onto.\nconst GALLERY_STAGE_POOL_SIZE = 4\n// Of those, how many stay attached to the DOM (the active stage plus the\n// two before it, keeping the usual two-or-three-file rotation instant).\n// The rest wait detached, costing no layout or style-recalc work until\n// they return — their page canvases remount on the way back, so returning\n// to a detached stage briefly rebuilds the page content.\nconst GALLERY_STAGE_ATTACHED_COUNT = 3\n\n// The preview for one pooled file. Each stage owns its URL resolution and\n// viewer state, so a mounted stage is self-contained: the root keeps\n// recently shown stages alive (reparented between hosts rather than\n// remounted, because the document viewers load in effects and would\n// refetch and re-parse on remount) and revisiting one — in the gallery or\n// the dialog — skips the presign, download, and parse work instead of\n// re-running it behind a spinner. The two variants share one element\n// structure, differing only in props and classes, so flipping a mounted\n// stage between them keeps the viewer instance.\nfunction FileSystemGalleryStage({\n file,\n getFileUrl,\n loadPreviewImageUrl,\n pageUrlCache,\n renderFilePreview,\n toolbarActions,\n urlCache,\n variant = "stage",\n}: {\n file: FileEntry\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n pageUrlCache?: Map<string, string>\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n /** Rendered in the viewer toolbar in the `"dialog"` variant. */\n toolbarActions?: React.ReactNode\n urlCache: Map<string, string>\n /** `"stage"` is toolbar-less in a bordered tile; `"dialog"` shows the full viewer chrome. */\n variant?: "dialog" | "stage"\n}) {\n const viewerKind = viewerKindForFile(file)\n // Only viewer-backed stages need a URL; thumbnail stages render from the\n // manifest\'s preview images, so selecting them never triggers a presign.\n const { isResolving, url } = useResolvedFileUrl(\n viewerKind ? file : null,\n getFileUrl,\n urlCache\n )\n const isDialog = variant === "dialog"\n const [isDark, setIsDark] = React.useState(false)\n const viewerFrameClassName = cn(\n "size-full",\n !isDialog && "overflow-hidden rounded-lg border"\n )\n\n if (viewerKind && isResolving) {\n return <Spinner className="size-6 text-muted-foreground" />\n }\n if (viewerKind === "image" && url) {\n return (\n <img\n src={url}\n alt={file.name}\n className="max-h-full max-w-full rounded-lg object-contain"\n />\n )\n }\n if (viewerKind === "pdf" && url) {\n return (\n <div className={viewerFrameClassName}>\n <React.Suspense fallback={<FileSystemViewerLoading />}>\n <LazyPDFViewer\n src={url}\n className={cn(\n "h-full",\n isDialog && "min-h-0 overflow-hidden rounded-2xl"\n )}\n fileName={file.name}\n showToolbar={isDialog}\n showUpload={false}\n toolbarActions={toolbarActions}\n />\n </React.Suspense>\n </div>\n )\n }\n if (viewerKind === "docx" && url) {\n return (\n <div className={viewerFrameClassName}>\n <React.Suspense fallback={<FileSystemViewerLoading />}>\n <LazyDocxViewerPreview\n src={url}\n fileName={file.name}\n isDark={isDark}\n className={cn(\n "h-full min-h-0",\n isDialog && "overflow-hidden rounded-2xl"\n )}\n onIsDarkChange={setIsDark}\n showToolbar={isDialog}\n showUpload={false}\n toolbarActions={toolbarActions}\n />\n </React.Suspense>\n </div>\n )\n }\n if (viewerKind === "xlsx" && url) {\n return (\n <div className={viewerFrameClassName}>\n <React.Suspense fallback={<FileSystemViewerLoading />}>\n <LazyXlsxViewerPreview\n src={url}\n fileName={file.name}\n isDark={isDark}\n className={cn(\n "h-full min-h-0",\n isDialog && "overflow-hidden rounded-2xl"\n )}\n onIsDarkChange={setIsDark}\n showToolbar={isDialog}\n showUpload={false}\n toolbarActions={toolbarActions}\n />\n </React.Suspense>\n </div>\n )\n }\n return (\n <FileVisual\n file={file}\n className="w-56 max-w-full"\n loadPreviewImageUrl={loadPreviewImageUrl}\n pageable\n pageUrlCache={pageUrlCache}\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )\n}\n\nfunction FileSystemGalleryView(props: FileSystemViewProps) {\n const {\n attachedStagePaths,\n entries,\n index,\n onOpen,\n onSelect,\n poolStagePath,\n registerStageHost,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n } = props\n const stripRefs = React.useRef(new Map<string, HTMLButtonElement>())\n const stripViewportRef = React.useRef<HTMLDivElement | null>(null)\n const typeAhead = useEntryTypeAhead()\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 // While arrow keys are scrubbing the strip, the center pane shows a\n // spinner; a file is only admitted to the preview pool (mounting its\n // viewer and resolving its URL) once the selection settles so each\n // keystroke stays cheap.\n const settledPath = useSettledValue(activeEntry?.path ?? null, 200)\n\n React.useEffect(() => {\n if (settledPath) poolStagePath(settledPath)\n }, [poolStagePath, settledPath])\n\n // Hosts for the root-owned preview pool: one positioned wrapper per\n // pooled path; the root reparents each live preview into its wrapper.\n // Stable callbacks per path keep React from re-running the host refs on\n // unrelated renders.\n const stageHostRefs = React.useMemo(\n () =>\n new Map(\n attachedStagePaths.map(\n (path) =>\n [\n path,\n (element: HTMLElement | null) => registerStageHost(path, element),\n ] as const\n )\n ),\n [attachedStagePaths, registerStageHost]\n )\n\n const activeFileSize = activeFile ? formatByteSize(activeFile.size) : null\n\n const handleKeyDown = (event: React.KeyboardEvent) => {\n if (entries.length === 0) return\n\n const currentIndex = activeEntry\n ? entries.findIndex((entry) => entry.path === activeEntry.path)\n : -1\n\n if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") {\n const match = typeAhead(event, entries, currentIndex)\n\n if (match) {\n onSelect(match)\n // The matched tile may be outside the strip\'s virtual window; the\n // active-tile effect scrolls it in, and focus follows once mounted.\n requestAnimationFrame(() => stripRefs.current.get(match.path)?.focus())\n }\n return\n }\n\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 const { end: stripEnd, start: stripStart } = useVirtualWindow({\n count: entries.length,\n horizontal: true,\n itemStride: GALLERY_TILE_STRIDE,\n leadingPx: GALLERY_STRIP_PADDING,\n overscan: 8,\n viewportRef: stripViewportRef,\n })\n\n // Keep the active tile mounted and visible while scrubbing or when the\n // selection arrives from another view.\n const activePath = activeEntry?.path ?? null\n\n React.useLayoutEffect(() => {\n if (!activePath) return\n\n scrollIndexIntoView({\n horizontal: true,\n index: entries.findIndex((entry) => entry.path === activePath),\n itemSize: GALLERY_TILE_SIZE,\n itemStride: GALLERY_TILE_STRIDE,\n leadingPx: GALLERY_STRIP_PADDING,\n viewport: stripViewportRef.current,\n })\n }, [activePath, entries])\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 viewportRef={stripViewportRef}\n viewportClassName="p-2"\n >\n <div\n className="relative h-14 min-w-full"\n style={{\n width: entries.length\n ? entries.length * GALLERY_TILE_STRIDE - GALLERY_TILE_GAP\n : undefined,\n }}\n >\n <div\n role="listbox"\n aria-label="Files"\n className="absolute inset-y-0 flex items-center gap-1.5"\n style={{ left: stripStart * GALLERY_TILE_STRIDE }}\n >\n {entries.slice(stripStart, stripEnd).map((entry) => {\n const isActive =\n 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 </div>\n </ScrollArea>\n <div className="flex min-h-0 flex-1">\n <div className="relative flex min-h-0 min-w-0 flex-1 items-center justify-center p-3">\n {activeEntry?.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-40 max-h-full w-auto drop-shadow-md" />\n ) : activeFile && !attachedStagePaths.includes(activeFile.path) ? (\n <Spinner className="size-6 text-muted-foreground" />\n ) : null}\n {/* Inactive hosts hide via `visibility` + `opacity`, never\n `display`: the document viewers size pages off ResizeObserver\n measurements, and display:none would collapse them to zero\n width — every reveal would re-lay-out and re-rasterize behind\n a blank pane. Stacking absolutely keeps each hidden stage at\n its real size so revealing one is pure paint. `opacity-0`\n matters: descendants can override an inherited\n visibility:hidden with their own visibility:visible (the\n spreadsheet grid\'s cell-selection overlay does), but nothing\n can opt out of an ancestor\'s zero opacity. `inert` keeps the\n hidden viewer\'s focusables out of reach. */}\n {attachedStagePaths.map((path) => {\n const isActiveStage = path === activeFile?.path\n\n return (\n <div\n key={path}\n ref={stageHostRefs.get(path)}\n inert={!isActiveStage || undefined}\n className={cn(\n "absolute inset-0 flex items-center justify-center p-3",\n !isActiveStage && "invisible opacity-0"\n )}\n />\n )\n })}\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'+ '"use client"\n\nimport * as React from "react"\nimport {\n ArrowDown01Icon,\n ArrowLeft01Icon,\n ArrowRight01Icon,\n ArrowUp01Icon,\n ArrowUpDownIcon,\n Calendar03Icon,\n Cancel01Icon,\n File01Icon,\n FilterIcon,\n GalleryThumbnailsIcon,\n GridViewIcon,\n LayoutThreeColumnIcon,\n LeftToRightListBulletIcon,\n Search01Icon,\n Tick02Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport {\n createFileTreeIconResolver,\n getBuiltInSpriteSheet,\n prepareFileTreeInput,\n type FileTreeSortComparator,\n type FileTreeSortEntry,\n} from "@pierre/trees"\nimport { FileTree as PierreFileTree, useFileTree } from "@pierre/trees/react"\nimport { createPortal } from "react-dom"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n Command,\n CommandEmpty,\n CommandGroup,\n CommandInput,\n CommandItem,\n CommandList,\n} from "@/components/ui/command"\nimport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogFooter,\n DialogHeader,\n DialogPanel,\n DialogTitle,\n} from "@/components/ui/dialog"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuSub,\n DropdownMenuSubContent,\n DropdownMenuSubTrigger,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { Input } from "@/components/ui/input"\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from "@/components/ui/popover"\nimport { ScrollArea, ScrollAreaPrimitive } 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"\n\nconst LazyPDFViewer = React.lazy(() =>\n import("@/components/ui/pdf-viewer").then((mod) => ({\n default: mod.PDFViewer,\n }))\n)\nconst LazyDocxViewerPreview = React.lazy(() =>\n import("@/components/ui/docx-viewer").then((mod) => ({\n default: mod.DocxViewerPreview,\n }))\n)\nconst LazyXlsxViewerPreview = React.lazy(() =>\n import("@/components/ui/xlsx-viewer").then((mod) => ({\n default: mod.XlsxViewerPreview,\n }))\n)\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 css: "CSS Stylesheet",\n csv: "CSV Document",\n doc: "Word Document",\n docx: "Word Document",\n gif: "GIF Image",\n go: "Go Source",\n jpeg: "JPEG Image",\n jpg: "JPEG Image",\n js: "JavaScript Source",\n json: "JSON Document",\n jsx: "JavaScript Source",\n md: "Markdown Document",\n mdx: "MDX Document",\n pdf: "PDF Document",\n png: "PNG Image",\n ppt: "PowerPoint Presentation",\n pptx: "PowerPoint Presentation",\n py: "Python Script",\n rs: "Rust Source",\n sh: "Shell Script",\n sql: "SQL Script",\n svg: "SVG Image",\n ts: "TypeScript Source",\n tsv: "TSV Document",\n tsx: "TypeScript Source",\n txt: "Plain Text",\n webp: "WebP Image",\n xls: "Excel Workbook",\n xlsx: "Excel Workbook",\n yaml: "YAML Document",\n yml: "YAML Document",\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\n// Folders sort under the "Folder" kind alphabetically among the file kinds,\n// like Finder\'s Kind sort.\nfunction entryKindLabel(entry: FileSystemEntry) {\n return entry.kind === "folder" ? "Folder" : fileKindLabel(entry)\n}\n\n// MIME types inferred from the extension when a file carries no\n// `contentType`, so the file-type filter can classify every manifest entry.\nconst EXTENSION_MIME_TYPES: Record<string, string> = {\n css: "text/css",\n csv: "text/csv",\n doc: "application/msword",\n docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",\n gif: "image/gif",\n go: "text/x-go",\n jpeg: "image/jpeg",\n jpg: "image/jpeg",\n js: "text/javascript",\n json: "application/json",\n jsx: "text/jsx",\n md: "text/markdown",\n mdx: "text/mdx",\n pdf: "application/pdf",\n png: "image/png",\n ppt: "application/vnd.ms-powerpoint",\n pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",\n py: "text/x-python",\n rs: "text/x-rust",\n sh: "application/x-sh",\n sql: "application/sql",\n svg: "image/svg+xml",\n ts: "text/x-typescript",\n tsv: "text/tab-separated-values",\n tsx: "text/x-typescript",\n txt: "text/plain",\n webp: "image/webp",\n xls: "application/vnd.ms-excel",\n xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",\n yaml: "text/yaml",\n yml: "text/yaml",\n zip: "application/zip",\n}\n\nconst FALLBACK_MIME_TYPE = "application/octet-stream"\nconst IPAD_MIN_WIDTH = 768\n\nconst MIME_TYPE_LABELS: Record<string, string> = {\n [FALLBACK_MIME_TYPE]: "Binary",\n "application/json": "JSON",\n "application/msword": "Word document (legacy)",\n "application/pdf": "PDF",\n "application/sql": "SQL",\n "application/vnd.ms-excel": "Excel workbook (legacy)",\n "application/vnd.ms-powerpoint": "PowerPoint (legacy)",\n "application/vnd.openxmlformats-officedocument.presentationml.presentation":\n "PowerPoint",\n "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":\n "Excel workbook",\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document":\n "Word document",\n "application/x-sh": "Shell script",\n "application/zip": "ZIP archive",\n "image/gif": "GIF image",\n "image/jpeg": "JPEG image",\n "image/png": "PNG image",\n "image/svg+xml": "SVG image",\n "image/webp": "WebP image",\n "text/css": "CSS",\n "text/csv": "CSV",\n "text/javascript": "JavaScript",\n "text/jsx": "JSX",\n "text/markdown": "Markdown",\n "text/mdx": "MDX",\n "text/plain": "Plain text",\n "text/tab-separated-values": "TSV",\n "text/x-go": "Go",\n "text/x-python": "Python",\n "text/x-rust": "Rust",\n "text/x-typescript": "TypeScript",\n "text/yaml": "YAML",\n}\n\nfunction mimeTypeForFile(file: FileEntry) {\n return (\n file.contentType ??\n EXTENSION_MIME_TYPES[fileExtension(file.name)] ??\n FALLBACK_MIME_TYPE\n )\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 FileSystemViewerLoading() {\n return (\n <div className="grid h-full min-h-48 flex-1 place-items-center bg-background">\n <Spinner className="size-4 text-muted-foreground" />\n </div>\n )\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\n// Every directory prefix appearing in the given relative file paths.\nfunction directoryPathsOf(paths: readonly string[]) {\n const directoryPaths = new Set<string>()\n\n for (const relativePath of paths) {\n let slashIndex = relativePath.indexOf("/")\n\n while (slashIndex !== -1) {\n directoryPaths.add(relativePath.slice(0, slashIndex))\n slashIndex = relativePath.indexOf("/", slashIndex + 1)\n }\n }\n return directoryPaths\n}\n\nfunction compareEntryNames(left: { name: string }, right: { name: string }) {\n return left.name.localeCompare(right.name, undefined, {\n numeric: true,\n sensitivity: "base",\n })\n}\n\nexport type FileSystemSortKey =\n | "createdAt"\n | "kind"\n | "name"\n | "size"\n | "updatedAt"\n\ntype FileSystemSortState = {\n direction: "asc" | "desc"\n key: FileSystemSortKey\n}\n\nconst SORT_OPTIONS: Array<{\n defaultDirection: "asc" | "desc"\n key: FileSystemSortKey\n label: string\n /** Shorter label so the toolbar trigger stays narrow. */\n triggerLabel: string\n}> = [\n { defaultDirection: "asc", key: "name", label: "Name", triggerLabel: "Name" },\n { defaultDirection: "asc", key: "kind", label: "Kind", triggerLabel: "Kind" },\n {\n defaultDirection: "desc",\n key: "createdAt",\n label: "Date created",\n triggerLabel: "Created",\n },\n {\n defaultDirection: "desc",\n key: "updatedAt",\n label: "Date modified",\n triggerLabel: "Modified",\n },\n {\n defaultDirection: "desc",\n key: "size",\n label: "Size",\n triggerLabel: "Size",\n },\n]\n\nconst DEFAULT_SORT: FileSystemSortState = { direction: "asc", key: "name" }\n\nfunction defaultSortDirection(key: FileSystemSortKey) {\n return (\n SORT_OPTIONS.find((option) => option.key === key)?.defaultDirection ?? "asc"\n )\n}\n\nfunction entrySortTimestamp(\n entry: FileSystemEntry,\n key: "createdAt" | "updatedAt"\n) {\n const value = entry[key]\n const time = value ? Date.parse(value) : Number.NaN\n\n return Number.isNaN(time) ? 0 : time\n}\n\n// Primary key per the active sort; ties (and missing metadata) fall back to\n// the name order so results stay stable. The name tiebreak ignores the\n// direction, like Finder.\nfunction compareEntriesBySort(\n left: FileSystemEntry,\n right: FileSystemEntry,\n sort: FileSystemSortState\n) {\n let result = 0\n\n if (sort.key === "name") {\n result = compareEntryNames(left, right)\n } else if (sort.key === "kind") {\n result = entryKindLabel(left).localeCompare(\n entryKindLabel(right),\n undefined,\n {\n sensitivity: "base",\n }\n )\n } else if (sort.key === "size") {\n // Folders have no byte size; group them at the small end.\n const leftSize = left.kind === "file" ? (left.size ?? 0) : -1\n const rightSize = right.kind === "file" ? (right.size ?? 0) : -1\n\n result = leftSize - rightSize\n } else {\n result =\n entrySortTimestamp(left, sort.key) - entrySortTimestamp(right, sort.key)\n }\n\n if (result === 0) return compareEntryNames(left, right)\n return sort.direction === "asc" ? (result < 0 ? -1 : 1) : result < 0 ? 1 : -1\n}\n\nexport type FileSystemFilterType = "dateCreated" | "dateModified" | "fileType"\n\ntype FileSystemDateFilterType = Exclude<FileSystemFilterType, "fileType">\n\ntype FileSystemFilterOperator =\n | "after"\n | "before"\n | "in-range"\n | "is"\n | "is-any-of"\n | "is-not"\n | "not-in-range"\n\ntype FileSystemFilter = {\n id: string\n operator: FileSystemFilterOperator\n type: FileSystemFilterType\n value: string[]\n}\n\ntype FileTypeFilterOption = {\n /** Sample file name so the option icon reuses the file-type sprite. */\n iconFileName: string\n label: string\n mime: string\n}\n\nconst FILTER_TYPE_LABELS: Record<FileSystemFilterType, string> = {\n dateCreated: "Date created",\n dateModified: "Date modified",\n fileType: "File type",\n}\n\nconst FILTER_OPERATOR_LABELS: Record<FileSystemFilterOperator, string> = {\n after: "after",\n before: "before",\n "in-range": "in range",\n is: "is",\n "is-any-of": "is any of",\n "is-not": "is not",\n "not-in-range": "not in range",\n}\n\n// Relative cutoffs for the date filters, mirroring Extend\'s table filters.\nconst DATE_FILTER_PRESETS = [\n "1 day ago",\n "3 days ago",\n "1 week ago",\n "1 month ago",\n "3 months ago",\n "6 months ago",\n "1 year ago",\n]\n\nfunction dateFilterPresetCutoff(preset: string) {\n const date = new Date()\n\n switch (preset) {\n case "1 day ago":\n date.setDate(date.getDate() - 1)\n break\n case "3 days ago":\n date.setDate(date.getDate() - 3)\n break\n case "1 week ago":\n date.setDate(date.getDate() - 7)\n break\n case "1 month ago":\n date.setMonth(date.getMonth() - 1)\n break\n case "3 months ago":\n date.setMonth(date.getMonth() - 3)\n break\n case "6 months ago":\n date.setMonth(date.getMonth() - 6)\n break\n case "1 year ago":\n date.setFullYear(date.getFullYear() - 1)\n break\n default: {\n const parsed = Date.parse(preset)\n\n if (!Number.isNaN(parsed)) return new Date(parsed)\n }\n }\n return date\n}\n\n// Custom ranges store two ISO timestamps instead of a relative preset.\nfunction isCustomDateRangeValue(value: string[]) {\n return (\n value.length === 2 &&\n value.every(\n (entry) =>\n !DATE_FILTER_PRESETS.includes(entry) && !Number.isNaN(Date.parse(entry))\n )\n )\n}\n\nfunction filterOperatorChoices(\n filter: FileSystemFilter\n): FileSystemFilterOperator[] {\n if (filter.type === "fileType") {\n return filter.value.length > 1 ? ["is-any-of", "is-not"] : ["is", "is-not"]\n }\n if (isCustomDateRangeValue(filter.value)) return ["in-range", "not-in-range"]\n return ["before", "after"]\n}\n\nfunction fileMatchesFilter(file: FileEntry, filter: FileSystemFilter) {\n if (filter.value.length === 0) return true\n if (filter.type === "fileType") {\n const matches = filter.value.includes(mimeTypeForFile(file))\n\n return filter.operator === "is-not" ? !matches : matches\n }\n\n const timestamp =\n filter.type === "dateCreated" ? file.createdAt : file.updatedAt\n const time = timestamp ? Date.parse(timestamp) : Number.NaN\n\n if (Number.isNaN(time)) return false\n if (filter.operator === "in-range" || filter.operator === "not-in-range") {\n const from = Date.parse(filter.value[0])\n const to = Date.parse(filter.value[1] ?? filter.value[0])\n const isInRange = time >= from && time <= to\n\n return filter.operator === "not-in-range" ? !isInRange : isInRange\n }\n\n const cutoff = dateFilterPresetCutoff(filter.value[0]).getTime()\n\n return filter.operator === "before" ? time <= cutoff : time >= cutoff\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(compareEntryNames)\n }\n\n // Folders without an explicit modified date inherit their newest child\'s —\n // object stores carry no folder metadata, yet the list view shows the\n // column and the date sorts compare it. Deepest first (a descendant\'s path\n // is always longer than its ancestor\'s) so dates propagate up the chain.\n const foldersDeepestFirst = [...folders.values()].sort(\n (left, right) => right.path.length - left.path.length\n )\n\n for (const folder of foldersDeepestFirst) {\n if (folder.updatedAt) continue\n\n let newestTime = Number.NEGATIVE_INFINITY\n let newestValue: string | undefined\n\n for (const child of children.get(folder.path) ?? []) {\n const value = child.updatedAt ?? child.createdAt\n const time = value ? Date.parse(value) : Number.NaN\n\n if (!Number.isNaN(time) && time > newestTime) {\n newestTime = time\n newestValue = value\n }\n }\n if (newestValue) folder.updatedAt = newestValue\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 // eslint-disable-next-line @next/next/no-img-element -- The folder glyph is an inline SVG data URL shared with the tree sprite.\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("&", "&")\n .replaceAll("<", "<")\n .replaceAll(">", ">")\n .replaceAll(\'"\', """)\n}\n\n// The @pierre/trees "complete" set — the full, colored suite with brand and\n// framework glyphs — ships as an SVG sprite. The list view tree consumes it\n// natively inside its shadow DOM; the icon, column, and gallery views render\n// the same sprite from the light DOM so every view falls back to the same\n// file-type icon when a file has no thumbnail.\nconst FILE_ICON_SPRITE_SHEET = getBuiltInSpriteSheet("complete")\n\nconst { resolveIcon: resolveFileIcon } = createFileTreeIconResolver({\n colored: true,\n set: "complete",\n})\n\n// Per-token light/dark colors mirroring the palette the tree applies inside\n// its shadow DOM. Tokens without an entry (font, nextjs, stylelint) stay\n// muted-foreground there too.\nconst FILE_ICON_COLORS: Record<string, [light: string, dark: string]> = {\n astro: ["#a631be", "#d568ea"],\n babel: ["#d5a910", "#ffd452"],\n bash: ["#199f43", "#5ecc71"],\n biome: ["#1a85d4", "#69b1ff"],\n bootstrap: ["#693acf", "#9d6afb"],\n browserslist: ["#d5a910", "#ffd452"],\n bun: ["#594c5b", "#79697b"],\n c: ["#1a85d4", "#69b1ff"],\n claude: ["#d47628", "#ffa359"],\n cpp: ["#1a85d4", "#69b1ff"],\n css: ["#693acf", "#9d6afb"],\n database: ["#a631be", "#d568ea"],\n default: ["#84848a", "#adadb1"],\n docker: ["#1a85d4", "#69b1ff"],\n eslint: ["#693acf", "#9d6afb"],\n git: ["#ff8c5b", "#d5512f"],\n go: ["#1ca1c7", "#68cdf2"],\n graphql: ["#d32a61", "#ff678d"],\n html: ["#d47628", "#ffa359"],\n image: ["#d32a61", "#ff678d"],\n javascript: ["#d5a910", "#ffd452"],\n json: ["#d47628", "#ffa359"],\n markdown: ["#199f43", "#5ecc71"],\n mcp: ["#17a5af", "#64d1db"],\n npm: ["#d52c36", "#ff6762"],\n oxc: ["#1ca1c7", "#68cdf2"],\n postcss: ["#d52c36", "#ff6762"],\n prettier: ["#17a5af", "#64d1db"],\n python: ["#1a85d4", "#69b1ff"],\n react: ["#1ca1c7", "#68cdf2"],\n ruby: ["#d52c36", "#ff6762"],\n rust: ["#d47628", "#ffa359"],\n sass: ["#d32a61", "#ff678d"],\n svelte: ["#d52c36", "#ff6762"],\n svg: ["#d47628", "#ffa359"],\n svgo: ["#199f43", "#5ecc71"],\n swift: ["#d47628", "#ffa359"],\n table: ["#17a5af", "#64d1db"],\n tailwind: ["#1ca1c7", "#68cdf2"],\n terraform: ["#693acf", "#9d6afb"],\n text: ["#84848a", "#adadb1"],\n typescript: ["#1a85d4", "#69b1ff"],\n vite: ["#a631be", "#d568ea"],\n vscode: ["#1a85d4", "#69b1ff"],\n vue: ["#199f43", "#5ecc71"],\n wasm: ["#693acf", "#9d6afb"],\n webpack: ["#1a85d4", "#69b1ff"],\n yml: ["#d52c36", "#ff6762"],\n zig: ["#d47628", "#ffa359"],\n zip: ["#d47628", "#ffa359"],\n}\n\nfunction fileIconColorVariables(mode: 0 | 1) {\n return Object.entries(FILE_ICON_COLORS)\n .map(([token, colors]) => `--fs-file-icon-${token}: ${colors[mode]};`)\n .join(" ")\n}\n\n// The variables live on :root rather than the component root because the\n// filter menus and dialogs portal outside it; the --fs-file-icon-*\n// namespace keeps them collision-free. Thumbnail tiles keep a light\n// (paper) surface in dark mode, so icons inside them revert to the light\n// palette ([data-file-system-on-light]); selected rows sit on the primary\n// surface — the opposite of the mode\'s background — so icons there swap to\n// the opposite palette ([data-file-system-on-primary] in the light DOM,\n// --fs-selected-color-scheme for the tree\'s light-dark() colors inside its\n// shadow DOM).\nconst FILE_ICON_COLOR_CSS = `\n:root { ${fileIconColorVariables(0)} --fs-selected-color-scheme: dark; }\n.dark { ${fileIconColorVariables(1)} --fs-selected-color-scheme: light; }\n.dark [data-file-system-on-light] { ${fileIconColorVariables(0)} }\n[data-file-system-on-primary] { ${fileIconColorVariables(1)} }\n.dark [data-file-system-on-primary] { ${fileIconColorVariables(0)} }\n`\n\nfunction FileSystemIconSpriteSheet() {\n return (\n <>\n <span\n aria-hidden="true"\n className="hidden"\n dangerouslySetInnerHTML={{ __html: FILE_ICON_SPRITE_SHEET }}\n />\n <style>{FILE_ICON_COLOR_CSS}</style>\n </>\n )\n}\n\nfunction FileTypeIcon({\n fileName,\n className,\n}: {\n fileName: string\n className?: string\n}) {\n const icon = resolveFileIcon("file-tree-icon-file", fileName)\n\n return (\n <svg\n aria-hidden="true"\n viewBox={icon.viewBox ?? "0 0 16 16"}\n className={cn("shrink-0 text-muted-foreground", className)}\n style={\n icon.token\n ? {\n color: `var(--fs-file-icon-${icon.token}, var(--color-muted-foreground))`,\n }\n : undefined\n }\n >\n <use href={`#${icon.name}`} />\n </svg>\n )\n}\n\nfunction FileGenericPreview({ file }: { file: FileEntry }) {\n const extension = fileExtension(file.name)\n\n return (\n <div\n data-file-system-on-light=""\n className="flex size-full flex-col items-center justify-center gap-1.5 bg-white text-neutral-400 dark:bg-neutral-100"\n >\n <FileTypeIcon fileName={file.name} 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// Mirrors @pierre/trees\' query normalization so the toolbar search filters\n// the icon, column, and gallery views exactly like the list view tree:\n// trimmed, backslashes to slashes, lowercased, substring match on the path.\nfunction normalizeSearchQuery(value: string) {\n const trimmed = value.trim()\n\n if (!trimmed) return ""\n return trimmed.replaceAll("\\\\", "/").toLowerCase()\n}\n\n// Windowed rendering, the approach @pierre/trees uses for the list view:\n// with a fixed item stride only the items intersecting the viewport — plus\n// `overscan` on each side — are mounted, so views stay flat-cost at\n// thousands of entries. The window keeps a one-item margin before\n// recomputing (scrolling doesn\'t re-render per item) and that margin also\n// guarantees single-step keyboard moves land on a mounted neighbor.\nfunction useVirtualWindow({\n count,\n horizontal = false,\n itemStride,\n leadingPx = 0,\n overscan = 8,\n viewportRef,\n}: {\n count: number\n horizontal?: boolean\n itemStride: number\n leadingPx?: number\n overscan?: number\n viewportRef: React.RefObject<HTMLDivElement | null>\n}) {\n const [window_, setWindow] = React.useState(() => ({\n end: Math.min(count, overscan * 2),\n start: 0,\n }))\n\n React.useLayoutEffect(() => {\n const viewport = viewportRef.current\n\n if (!viewport || itemStride <= 0) return\n\n const update = () => {\n const scrollStart =\n (horizontal ? viewport.scrollLeft : viewport.scrollTop) - leadingPx\n const viewportSize = horizontal\n ? viewport.clientWidth\n : viewport.clientHeight\n const firstVisible = Math.max(0, Math.floor(scrollStart / itemStride))\n const lastVisible = Math.min(\n count,\n Math.ceil((scrollStart + viewportSize) / itemStride)\n )\n\n setWindow((previous) => {\n if (\n previous.end <= count &&\n previous.start <= Math.max(0, firstVisible - 1) &&\n previous.end >= Math.min(count, lastVisible + 1)\n ) {\n return previous\n }\n return {\n end: Math.min(count, lastVisible + overscan),\n start: Math.max(0, firstVisible - overscan),\n }\n })\n }\n\n update()\n viewport.addEventListener("scroll", update, { passive: true })\n\n const observer =\n typeof ResizeObserver === "undefined" ? null : new ResizeObserver(update)\n\n observer?.observe(viewport)\n return () => {\n viewport.removeEventListener("scroll", update)\n observer?.disconnect()\n }\n }, [count, horizontal, itemStride, leadingPx, overscan, viewportRef])\n\n return window_\n}\n\n// Scrolls the item at `index` into the viewport when it sits outside it —\n// virtualized views need this because off-window items have no DOM node to\n// call scrollIntoView on.\nfunction scrollIndexIntoView({\n horizontal = false,\n index,\n itemSize,\n itemStride,\n leadingPx = 0,\n viewport,\n}: {\n horizontal?: boolean\n index: number\n itemSize: number\n itemStride: number\n leadingPx?: number\n viewport: HTMLDivElement | null\n}) {\n if (!viewport || index < 0) return\n\n const start = leadingPx + index * itemStride\n const end = start + itemSize\n const scrollStart = horizontal ? viewport.scrollLeft : viewport.scrollTop\n const viewportSize = horizontal ? viewport.clientWidth : viewport.clientHeight\n\n let nextScrollStart: number | null = null\n\n if (start < scrollStart) {\n nextScrollStart = start\n } else if (end > scrollStart + viewportSize) {\n nextScrollStart = end - viewportSize\n }\n if (nextScrollStart === null) return\n if (horizontal) {\n viewport.scrollLeft = nextScrollStart\n } else {\n viewport.scrollTop = nextScrollStart\n }\n}\n\nfunction FileVisual({\n file,\n className,\n loadPreviewImageUrl,\n pageable = false,\n pageUrlCache,\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 /**\n * Shared `"path#pageIndex"` → URL cache so pages fetched by one pager\n * (gallery stage, columns preview) are reused by every other instance.\n */\n pageUrlCache?: Map<string, string>\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] ??\n lazyPageUrls[clampedPageIndex] ??\n pageUrlCache?.get(`${file.path}#${clampedPageIndex}`) ??\n 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 // Cache even when stale (page flipped away mid-load): the fetch is\n // done, so let the next visit use it.\n if (url) pageUrlCache?.set(`${file.path}#${clampedPageIndex}`, 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 }, [\n clampedPageIndex,\n file.path,\n isLazyPagePending,\n loadPreviewImageUrl,\n pageUrlCache,\n ])\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 [searchInput, setSearchInput] = React.useState("")\n const searchInputRef = React.useRef<HTMLInputElement | null>(null)\n const [isSearchExpanded, setIsSearchExpanded] = React.useState(false)\n const searchQuery = normalizeSearchQuery(searchInput)\n const isSearching = searchQuery.length > 0\n\n const [sort, setSort] = React.useState(DEFAULT_SORT)\n const [filters, setFilters] = React.useState<FileSystemFilter[]>([])\n const hasActiveFilters = filters.length > 0\n\n // Files must pass every active filter; folders stay visible through\n // matching descendants, so the predicate only ever sees files.\n const fileFilter = React.useMemo(() => {\n if (filters.length === 0) return null\n return (file: FileEntry) =>\n filters.every((filter) => fileMatchesFilter(file, filter))\n }, [filters])\n\n // Paths that stay visible while searching or filtering: every file whose\n // currentPath-relative path contains the query — the list view tree\'s\n // hide-non-matches semantics — and that passes the filters, plus the\n // ancestor folders leading to it. Folder names participate in search\n // matches only when no filters are active; with filters, a folder is only\n // as visible as the files inside it.\n const visiblePaths = React.useMemo(() => {\n if (!isSearching && !fileFilter) return null\n\n const visible = new Set<string>()\n const markVisible = (path: string) => {\n while (path && path !== currentPath && !visible.has(path)) {\n visible.add(path)\n path = pathParent(path)\n }\n }\n const matchesQuery = (path: string) =>\n !isSearching ||\n path.slice(currentPath.length).toLowerCase().includes(searchQuery)\n\n for (const [path, file] of index.files) {\n if (path === currentPath) continue\n if (currentPath && !path.startsWith(currentPath)) continue\n if (!matchesQuery(path)) continue\n if (fileFilter && !fileFilter(file)) continue\n markVisible(path)\n }\n if (!fileFilter) {\n for (const path of index.folders.keys()) {\n if (path === currentPath) continue\n if (currentPath && !path.startsWith(currentPath)) continue\n if (matchesQuery(path)) markVisible(path)\n }\n }\n return visible\n }, [currentPath, fileFilter, index, isSearching, searchQuery])\n\n const visibleIndex = React.useMemo(() => {\n if (!visiblePaths) return index\n\n const children = new Map<string, FileSystemEntry[]>()\n\n for (const [parentPath, parentChildren] of index.children) {\n const visibleChildren = parentChildren.filter((entry) =>\n visiblePaths.has(entry.path)\n )\n\n if (visibleChildren.length) children.set(parentPath, visibleChildren)\n }\n return { ...index, children }\n }, [index, visiblePaths])\n\n // Children re-sorted per the active sort; the default (name ascending)\n // reuses the index\'s pre-sorted arrays untouched.\n const sortedIndex = React.useMemo(() => {\n if (\n sort.key === DEFAULT_SORT.key &&\n sort.direction === DEFAULT_SORT.direction\n ) {\n return visibleIndex\n }\n\n const children = new Map<string, FileSystemEntry[]>()\n\n for (const [parentPath, parentChildren] of visibleIndex.children) {\n children.set(\n parentPath,\n [...parentChildren].sort((left, right) =>\n compareEntriesBySort(left, right, sort)\n )\n )\n }\n return { ...visibleIndex, children }\n }, [sort, visibleIndex])\n\n // The ref mirrors the state so re-selecting the same entry (e.g. the\n // pointerdown + click pair the columns view emits per press) stays a\n // no-op without widening the callback\'s dependencies.\n const selectedPathRef = React.useRef<string | null>(null)\n const selectEntry = React.useCallback(\n (entry: FileSystemEntry | null) => {\n const path = entry?.path ?? null\n\n if (selectedPathRef.current === path) return\n selectedPathRef.current = path\n setSelectedPath(path)\n onSelectionChange?.(entry)\n },\n [onSelectionChange]\n )\n\n // A query or filter change can hide the selected entry out from under the\n // views.\n React.useEffect(() => {\n if (!visiblePaths || !selectedPath) return\n if (!visiblePaths.has(selectedPath)) selectEntry(null)\n }, [selectEntry, selectedPath, visiblePaths])\n\n const applySortKey = React.useCallback((key: FileSystemSortKey) => {\n setSort((previous) =>\n previous.key === key\n ? previous\n : { direction: defaultSortDirection(key), key }\n )\n }, [])\n\n // Column headers toggle the direction when the column is already active,\n // like Finder.\n const toggleSortColumn = React.useCallback((key: FileSystemSortKey) => {\n setSort((previous) =>\n previous.key === key\n ? { direction: previous.direction === "asc" ? "desc" : "asc", key }\n : { direction: defaultSortDirection(key), key }\n )\n }, [])\n\n // Distinct MIME types across the loaded manifest, labeled for the filter\n // menu; the first file seen per type lends its name to the option icon.\n const fileTypeOptions = React.useMemo(() => {\n const byMime = new Map<string, FileTypeFilterOption>()\n\n for (const file of index.files.values()) {\n const mime = mimeTypeForFile(file)\n\n if (!byMime.has(mime)) {\n // The leading-dot check keeps dotfiles (.gitignore) whole.\n const dotIndex = file.name.lastIndexOf(".")\n const extension =\n dotIndex > 0 ? file.name.slice(dotIndex + 1).toLowerCase() : ""\n\n byMime.set(mime, {\n // A synthesized generic name, so files with branded icons\n // (biome.json, next.config.ts, CLAUDE.md, …) don\'t lend them to\n // the whole type; extensionless names keep their own icon\n // (Dockerfile, Makefile).\n iconFileName: extension ? `file.${extension}` : file.name,\n label: MIME_TYPE_LABELS[mime] ?? mime,\n mime,\n })\n }\n }\n return [...byMime.values()].sort((left, right) =>\n left.label.localeCompare(right.label)\n )\n }, [index])\n\n const filterIdRef = React.useRef(0)\n const [dateRangeDialog, setDateRangeDialog] = React.useState<{\n initialRange?: { from: Date; to: Date }\n type: FileSystemDateFilterType\n } | null>(null)\n\n const toggleFileTypeFilterValue = React.useCallback(\n (mime: string, checked: boolean) => {\n const id = `filter-${++filterIdRef.current}`\n\n setFilters((previous) => {\n const existing = previous.find((filter) => filter.type === "fileType")\n\n if (!existing) {\n if (!checked) return previous\n return [\n ...previous,\n {\n id,\n operator: "is" as const,\n type: "fileType" as const,\n value: [mime],\n },\n ]\n }\n\n const value = checked\n ? [...new Set([...existing.value, mime])]\n : existing.value.filter((entry) => entry !== mime)\n\n if (value.length === 0) {\n return previous.filter((filter) => filter !== existing)\n }\n\n // "is" and "is any of" track the value count; "is not" is unaffected.\n const operator =\n existing.operator === "is" || existing.operator === "is-any-of"\n ? value.length > 1\n ? ("is-any-of" as const)\n : ("is" as const)\n : existing.operator\n\n return previous.map((filter) =>\n filter === existing ? { ...filter, operator, value } : filter\n )\n })\n },\n []\n )\n\n const setDatePresetFilter = React.useCallback(\n (type: FileSystemDateFilterType, preset: string) => {\n const id = `filter-${++filterIdRef.current}`\n\n setFilters((previous) => [\n ...previous.filter((filter) => filter.type !== type),\n { id, operator: "after", type, value: [preset] },\n ])\n },\n []\n )\n\n // Editing an existing custom range seeds the dialog with its bounds.\n const openDateRangeDialog = React.useCallback(\n (type: FileSystemDateFilterType) => {\n const existing = filters.find((filter) => filter.type === type)\n\n setDateRangeDialog({\n initialRange:\n existing && isCustomDateRangeValue(existing.value)\n ? {\n from: new Date(existing.value[0]),\n to: new Date(existing.value[1]),\n }\n : undefined,\n type,\n })\n },\n [filters]\n )\n\n const applyCustomDateRange = React.useCallback(\n (type: FileSystemDateFilterType, from: Date, to: Date) => {\n const id = `filter-${++filterIdRef.current}`\n\n setFilters((previous) => {\n const existing = previous.find((filter) => filter.type === type)\n\n return [\n ...previous.filter((filter) => filter.type !== type),\n {\n id,\n operator:\n existing?.operator === "not-in-range"\n ? ("not-in-range" as const)\n : ("in-range" as const),\n type,\n value: [from.toISOString(), to.toISOString()],\n },\n ]\n })\n },\n []\n )\n\n // Below iPad width the view switcher collapses into a select and the sort\n // select drops its label; below 560px the search input collapses into a\n // popover, and below 360px the folder name is dropped too.\n const rootRef = React.useRef<HTMLDivElement | null>(null)\n const [headerLayout, setHeaderLayout] = React.useState<\n "full" | "compact" | "minimal"\n >("full")\n const [isBelowIpadWidth, setIsBelowIpadWidth] = React.useState(false)\n\n React.useEffect(() => {\n const root = rootRef.current\n\n if (!root || typeof ResizeObserver === "undefined") return\n\n const applyWidth = (width: number | undefined) => {\n if (width === undefined) return\n\n setHeaderLayout(\n width < 360 ? "minimal" : width < 560 ? "compact" : "full"\n )\n setIsBelowIpadWidth(width < IPAD_MIN_WIDTH)\n }\n const observer = new ResizeObserver((observerEntries) =>\n applyWidth(observerEntries[0]?.contentRect.width)\n )\n\n // Measure synchronously so the first painted layout is already correct;\n // the observer then tracks resizes.\n applyWidth(root.clientWidth)\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 // Navigation exits search, like Finder.\n setSearchInput("")\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 previousPathRef = React.useRef(currentPath)\n\n React.useEffect(() => {\n if (previousPathRef.current === currentPath) {\n return\n }\n\n previousPathRef.current = currentPath\n const root = rootRef.current\n\n if (root && document.activeElement === document.body) {\n root.focus({ preventScroll: true })\n }\n }, [currentPath])\n\n const [openedFile, setOpenedFile] = React.useState<{\n file: FileEntry\n kind: FileSystemViewerKind\n url: string\n } | null>(null)\n\n // Component-lifetime caches shared by every view and the open dialog:\n // resolved (e.g. presigned) URLs keyed by path, and lazily loaded page\n // thumbnails keyed by `"path#pageIndex"`. Each resolution happens once no\n // matter how often the user revisits a file or switches views; stable\n // URLs also keep the browser\'s HTTP cache valid for fetched content.\n // Lazy state (never set) rather than refs: the Maps are passed down\n // during render, which the rules of React disallow for ref reads.\n const [resolvedUrlCache] = React.useState(() => new Map<string, string>())\n const [pageUrlCache] = React.useState(() => new Map<string, string>())\n\n // The keep-alive preview pool. Recently shown documents stay mounted so\n // returning to one — in the gallery stage or the viewer dialog — skips\n // the download and parse work instead of repeating it behind a spinner.\n // Each pooled path renders through a portal into a stable detached <div>\n // created once per path and never swapped (React remounts a portal\'s\n // children when its container changes); a layout effect reparents that\n // div into whichever host currently shows the file: the gallery\'s stage\n // wrapper or the open dialog. Imperative appendChild keeps the mounted\n // viewer (and its parsed document) alive across every move. Pooled paths\n // without a current host stay mounted but DETACHED from the DOM — a\n // detached subtree costs no layout, paint, or style-recalc work, so idle\n // pool members never slow down interactions in the visible viewer.\n const [stagePool, setStagePool] = React.useState<string[]>([])\n const [stageRecency] = React.useState(() => new Map<string, number>())\n const stageClockRef = React.useRef(0)\n const [stageContainers] = React.useState(\n () => new Map<string, HTMLDivElement>()\n )\n const [stageHosts] = React.useState(() => new Map<string, HTMLElement>())\n const [, bumpStageHosts] = React.useState(0)\n // Bumped on every admission so the attach set recomputes when recency\n // changes without a pool membership change.\n const [stageVersion, setStageVersion] = React.useState(0)\n const [dialogStageHost, setDialogStageHost] =\n React.useState<HTMLElement | null>(null)\n\n const registerStageHost = React.useCallback(\n (path: string, element: HTMLElement | null) => {\n if (element) {\n if (stageHosts.get(path) === element) return\n stageHosts.set(path, element)\n } else {\n if (!stageHosts.has(path)) return\n stageHosts.delete(path)\n }\n bumpStageHosts((version) => version + 1)\n },\n [stageHosts]\n )\n\n const dialogStageHostRef = React.useCallback(\n (element: HTMLDivElement | null) => setDialogStageHost(element),\n []\n )\n\n // Admits a file into the pool (idempotent), evicting the least recently\n // admitted path beyond the cap. The pool array keeps insertion order —\n // reordering would churn the host registrations — so recency lives in a\n // separate map; the version bump re-renders so the attach set below\n // tracks recency even when pool membership is unchanged.\n const poolStagePath = React.useCallback(\n (path: string) => {\n if (!index.files.has(path)) return\n if (!stageContainers.has(path)) {\n const container = document.createElement("div")\n\n // Layout/paint containment keeps work inside one preview from\n // invalidating the rest of the page (and vice versa).\n container.className =\n "flex size-full min-h-0 min-w-0 items-center justify-center contain-layout contain-paint"\n stageContainers.set(path, container)\n }\n\n stageRecency.set(path, ++stageClockRef.current)\n setStageVersion((version) => version + 1)\n setStagePool((previous) => {\n if (previous.includes(path)) return previous\n\n const next = [...previous, path]\n\n if (next.length <= GALLERY_STAGE_POOL_SIZE) return next\n\n let evicted = next[0]\n\n for (const candidate of next) {\n if (candidate === path) continue\n if (\n (stageRecency.get(candidate) ?? 0) <\n (stageRecency.get(evicted) ?? 0)\n ) {\n evicted = candidate\n }\n }\n return next.filter((candidate) => candidate !== evicted)\n })\n },\n [index, stageContainers, stageRecency]\n )\n\n const dialogStagePath =\n openedFile !== null && openedFile.kind !== "image"\n ? openedFile.file.path\n : null\n // Only the most recently shown stages stay attached to the DOM, so\n // rotating among a few files stays instant while older pool members wait\n // detached at zero rendering cost. Memoized so host ref callbacks\n // downstream stay referentially stable — recomputing every render would\n // re-register hosts in a loop.\n const attachedStagePaths = React.useMemo(() => {\n void stageVersion\n\n const attached = [...stagePool]\n .sort((a, b) => (stageRecency.get(b) ?? 0) - (stageRecency.get(a) ?? 0))\n .slice(0, GALLERY_STAGE_ATTACHED_COUNT)\n\n if (\n dialogStagePath &&\n stagePool.includes(dialogStagePath) &&\n !attached.includes(dialogStagePath)\n ) {\n attached.push(dialogStagePath)\n }\n return attached\n }, [dialogStagePath, stagePool, stageRecency, stageVersion])\n\n // Reparent each pooled container to its current host. No dependency\n // array: host registration mutates maps in place, so the cheap loop\n // (pool ≤ GALLERY_STAGE_POOL_SIZE) runs every commit instead of chasing\n // every mutation source.\n React.useLayoutEffect(() => {\n for (const [path, container] of stageContainers) {\n if (!stagePool.includes(path)) {\n // Evicted — React already unmounted the portal\'s children.\n container.remove()\n stageContainers.delete(path)\n continue\n }\n if (dialogStagePath === path) {\n // Leave the container in place until the dialog host mounts.\n if (dialogStageHost && container.parentElement !== dialogStageHost) {\n dialogStageHost.appendChild(container)\n }\n continue\n }\n\n const target = attachedStagePaths.includes(path)\n ? (stageHosts.get(path) ?? null)\n : null\n\n if (!target) {\n if (container.parentElement) container.remove()\n } else if (container.parentElement !== target) {\n target.appendChild(container)\n }\n }\n })\n\n const openFile = React.useCallback(\n (file: FileEntry) => {\n void (async () => {\n let url = file.url ?? resolvedUrlCache.get(file.path) ?? null\n\n if (!url && getFileUrl) {\n try {\n url = await getFileUrl(file)\n if (url) resolvedUrlCache.set(file.path, url)\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 // Pool the file so the dialog reuses an already-mounted preview\n // (and the gallery inherits the live viewer after it closes).\n poolStagePath(file.path)\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, poolStagePath, resolvedUrlCache]\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 setSearchInput("")\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 setSearchInput("")\n selectEntry(null)\n }, [selectEntry])\n\n const currentEntries = sortedIndex.children.get(currentPath) ?? []\n const currentFolderName =\n currentPath === "" ? title : pathName(currentPath) || title\n const isLoadingCurrentFolder = loadingFolders.has(currentPath)\n\n // The list view tree saves its expanded folders here when it unmounts\n // (view switches, navigation) so returning to the list view — or to a\n // previously visited folder — restores the same disclosure state.\n const treeExpansionRef = React.useRef(new Map<string, readonly string[]>())\n\n const viewProps: FileSystemViewProps = {\n attachedStagePaths,\n currentPath,\n entries: currentEntries,\n fileFilter,\n getFileUrl,\n index: sortedIndex,\n loadPreviewImageUrl,\n loadingFolders,\n onOpen: openEntry,\n onSelect: selectAndPrefetchEntry,\n onSortColumnClick: toggleSortColumn,\n pageUrlCache,\n poolStagePath,\n registerStageHost,\n renderFilePreview,\n searchQuery,\n selectedEntry,\n selectedPath,\n sort,\n treeExpansionRef,\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 data-slot="file-system"\n onKeyDown={(event) => {\n // ⌘F focuses the toolbar search while focus is inside the component.\n if ((event.metaKey || event.ctrlKey) && event.key === "f") {\n event.preventDefault()\n setIsSearchExpanded(true)\n searchInputRef.current?.focus()\n }\n }}\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 <FileSystemIconSpriteSheet />\n <div className="relative grid h-12 shrink-0 grid-cols-[minmax(0,1fr)_auto_minmax(0,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" || isBelowIpadWidth ? (\n <Select\n value={view}\n onValueChange={(value) => setView(value as FileSystemView)}\n >\n <SelectTrigger\n size="sm"\n aria-label="View"\n // Icon-only like the sort select: sheds the base min-width to\n // hug icon + chevron at the filter button\'s 28px height.\n className="h-7 min-h-7 w-auto min-w-0 [&_svg]:size-4"\n >\n <SelectValue>\n {activeViewOption ? (\n <HugeiconsIcon\n icon={activeViewOption.icon}\n className="size-4"\n />\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 className="flex min-w-0 items-center justify-end gap-1">\n <FileSystemSortSelect\n layout={headerLayout}\n onKeyChange={applySortKey}\n showLabel={!isBelowIpadWidth}\n sort={sort}\n />\n <FileSystemFilterMenu\n fileTypeOptions={fileTypeOptions}\n filters={filters}\n onOpenCustomRange={openDateRangeDialog}\n onSelectDatePreset={setDatePresetFilter}\n onToggleFileType={toggleFileTypeFilterValue}\n />\n <FileSystemSearchField\n inputRef={searchInputRef}\n isExpanded={isSearchExpanded}\n layout={headerLayout}\n onExpandedChange={setIsSearchExpanded}\n onValueChange={setSearchInput}\n value={searchInput}\n />\n </div>\n </div>\n {hasActiveFilters ? (\n <div className="flex shrink-0 flex-wrap items-center gap-1 border-b bg-muted/20 px-2 py-1.5 text-xs text-muted-foreground">\n {filters.map((filter) => {\n const dateFilterType =\n filter.type === "fileType" ? null : filter.type\n\n return (\n <FileSystemFilterPill\n key={filter.id}\n fileTypeOptions={fileTypeOptions}\n filter={filter}\n onOpenCustomRange={\n dateFilterType\n ? () => openDateRangeDialog(dateFilterType)\n : undefined\n }\n onOperatorChange={(operator) =>\n setFilters((previous) =>\n previous.map((entry) =>\n entry.id === filter.id ? { ...entry, operator } : entry\n )\n )\n }\n onRemove={() =>\n setFilters((previous) =>\n previous.filter((entry) => entry.id !== filter.id)\n )\n }\n onSelectDatePreset={(preset) =>\n setFilters((previous) =>\n previous.map((entry) =>\n entry.id === filter.id\n ? {\n ...entry,\n operator:\n entry.operator === "before" ||\n entry.operator === "after"\n ? entry.operator\n : "after",\n value: [preset],\n }\n : entry\n )\n )\n }\n onToggleFileType={toggleFileTypeFilterValue}\n />\n )\n })}\n <button\n type="button"\n onClick={() => setFilters([])}\n className="rounded-md px-1.5 py-0.5 transition-colors outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"\n >\n Clear\n </button>\n </div>\n ) : null}\n <div className="relative min-h-0 flex-1">\n {isLoadingCurrentFolder && currentEntries.length === 0 ? (\n <FileSystemEmptyState label="Loading…" isLoading />\n ) : currentEntries.length === 0 &&\n (view !== "columns" || isSearching || hasActiveFilters) ? (\n <FileSystemEmptyState\n label={\n isSearching\n ? `No results for “${searchInput.trim()}”`\n : hasActiveFilters\n ? "No items match the active filters"\n : "This folder is empty"\n }\n />\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 {isSearching\n ? currentEntries.length === 1\n ? "result"\n : "results"\n : currentEntries.length === 1\n ? "item"\n : "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 === "image" ? (\n // eslint-disable-next-line @next/next/no-img-element -- File previews render caller-provided URLs that may be object or presigned URLs.\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 // The pooled preview reparents into this host (see the layout\n // effect above), so a viewer the gallery already loaded\n // carries over live instead of remounting behind a loading\n // state.\n <div\n ref={dialogStageHostRef}\n className="flex h-full min-h-0 flex-1 flex-col"\n />\n )}\n </DialogContent>\n ) : null}\n {/* The pooled previews. Rendered inside <Dialog> so the dialog\n variant\'s close toolbar button keeps its context; each portal\'s\n container never changes, the container\'s parent does. */}\n {stagePool.map((path) => {\n const file = index.files.get(path)\n const container = stageContainers.get(path)\n\n if (!file || !container) return null\n\n const isOpenedInDialog =\n openedFile !== null &&\n openedFile.kind !== "image" &&\n openedFile.file.path === path\n\n return createPortal(\n <FileSystemGalleryStage\n file={file}\n getFileUrl={getFileUrl}\n loadPreviewImageUrl={loadPreviewImageUrl}\n pageUrlCache={pageUrlCache}\n renderFilePreview={renderFilePreview}\n toolbarActions={\n isOpenedInDialog ? viewerCloseToolbarAction : undefined\n }\n urlCache={resolvedUrlCache}\n variant={isOpenedInDialog ? "dialog" : "stage"}\n />,\n container,\n path\n )\n })}\n </Dialog>\n {dateRangeDialog ? (\n <FileSystemDateRangeDialog\n initialRange={dateRangeDialog.initialRange}\n onApply={(from, to) => {\n applyCustomDateRange(dateRangeDialog.type, from, to)\n setDateRangeDialog(null)\n }}\n onClose={() => setDateRangeDialog(null)}\n />\n ) : null}\n </div>\n )\n}\n\n// Shared style for the ghost icon buttons in the toolbar.\nconst TOOLBAR_ICON_BUTTON_CLASSNAME =\n "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"\n\n// macOS Finder-style toolbar search. At the full layout it sits inline in\n// the header\'s right column; at compact widths it collapses into a ghost\n// icon button that opens the input in a popover (a dot marks the button\n// while a query keeps filtering the views).\nfunction FileSystemSearchField({\n inputRef,\n isExpanded,\n layout,\n onExpandedChange,\n onValueChange,\n value,\n}: {\n inputRef: React.RefObject<HTMLInputElement | null>\n isExpanded: boolean\n layout: "full" | "compact" | "minimal"\n onExpandedChange: (isExpanded: boolean) => void\n onValueChange: (value: string) => void\n value: string\n}) {\n const isInline = layout === "full"\n\n React.useEffect(() => {\n if (!isInline && isExpanded) inputRef.current?.focus()\n }, [inputRef, isExpanded, isInline])\n\n const input = (\n <div\n className={cn(\n "relative flex h-7 min-w-0 flex-1 items-center rounded-lg border border-input bg-popover text-sm text-foreground shadow-xs/5 transition-shadow outline-none not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-focus-within:before:shadow-[0_1px_--theme(--color-black/4%)] focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-1 focus-within:ring-offset-background dark:bg-input/32 dark:not-focus-within:before:shadow-[0_-1px_--theme(--color-white/6%)]",\n isInline && "max-w-56"\n )}\n >\n <HugeiconsIcon\n icon={Search01Icon}\n className="pointer-events-none absolute left-2 size-3.5 text-muted-foreground"\n />\n <input\n ref={inputRef}\n type="text"\n role="searchbox"\n aria-label="Search files"\n placeholder="Search"\n value={value}\n onChange={(event) => onValueChange(event.target.value)}\n onKeyDown={(event) => {\n if (event.key !== "Escape") return\n event.preventDefault()\n event.stopPropagation()\n if (value) {\n onValueChange("")\n } else {\n onExpandedChange(false)\n event.currentTarget.blur()\n }\n }}\n className="h-full w-full min-w-0 rounded-[inherit] bg-transparent pr-6 pl-7 outline-none placeholder:text-muted-foreground"\n />\n {value ? (\n <button\n type="button"\n aria-label="Clear search"\n onClick={() => {\n onValueChange("")\n inputRef.current?.focus()\n }}\n className="absolute right-1 flex size-5 items-center justify-center rounded-sm text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"\n >\n <HugeiconsIcon icon={Cancel01Icon} className="size-3" />\n </button>\n ) : null}\n </div>\n )\n\n if (isInline) {\n // A fixed basis (not flex-1) keeps the whole toolbar cluster packed\n // against the header\'s right edge; the input shrinks first when the\n // header tightens.\n return <div className="flex w-56 min-w-32 items-center">{input}</div>\n }\n\n return (\n <Popover open={isExpanded} onOpenChange={onExpandedChange}>\n <PopoverTrigger\n render={\n <button\n type="button"\n aria-label="Search"\n title="Search"\n className={cn(TOOLBAR_ICON_BUTTON_CLASSNAME, "relative")}\n />\n }\n >\n <HugeiconsIcon icon={Search01Icon} className="size-4" />\n {value ? (\n <span className="absolute top-1 right-1 size-1.5 rounded-full bg-primary" />\n ) : null}\n </PopoverTrigger>\n <PopoverContent align="end" sideOffset={6} className="w-64 p-1">\n {input}\n </PopoverContent>\n </Popover>\n )\n}\n\n// Toolbar "sort by" select. The full layout shows the active key\'s label; at\n// compact widths the trigger collapses to the sort glyph + chevron.\nfunction FileSystemSortSelect({\n layout,\n onKeyChange,\n showLabel,\n sort,\n}: {\n layout: "full" | "compact" | "minimal"\n onKeyChange: (key: FileSystemSortKey) => void\n showLabel: boolean\n sort: FileSystemSortState\n}) {\n const activeOption = SORT_OPTIONS.find((option) => option.key === sort.key)\n\n return (\n <Select\n value={sort.key}\n onValueChange={(value) => onKeyChange(value as FileSystemSortKey)}\n >\n <SelectTrigger\n size="sm"\n aria-label="Sort by"\n title="Sort by"\n className="h-7 min-h-7 w-auto min-w-0 shrink-0 [&_svg]:size-4"\n >\n <SelectValue>\n <span className="flex items-center gap-1.5">\n <HugeiconsIcon icon={ArrowUpDownIcon} className="size-4" />\n {layout === "full" && showLabel ? activeOption?.triggerLabel : null}\n </span>\n </SelectValue>\n </SelectTrigger>\n <SelectContent align="end" alignItemWithTrigger={false}>\n {SORT_OPTIONS.map((option) => (\n <SelectItem key={option.key} value={option.key}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n )\n}\n\n// Searchable file-type list (cmdk) rendered inside a menu popup, so the\n// long MIME list can be filtered by typing. Selection toggles stay open for\n// multi-select; ArrowUp/Down and Enter come from cmdk\'s combobox semantics.\nfunction FileSystemFileTypeCommand({\n checkedMimes,\n onToggle,\n options,\n}: {\n checkedMimes: string[]\n onToggle: (mime: string, checked: boolean) => void\n options: FileTypeFilterOption[]\n}) {\n const inputRef = React.useRef<HTMLInputElement | null>(null)\n\n // The menu focuses its popup when it opens; pull focus into the search\n // field so typing filters immediately.\n React.useEffect(() => {\n const frame = requestAnimationFrame(() => inputRef.current?.focus())\n\n return () => cancelAnimationFrame(frame)\n }, [])\n\n return (\n <Command\n // -m-1 spans the menu viewport\'s built-in padding so the search\n // field\'s bottom border runs edge to edge.\n className="-m-1 w-[calc(100%+--spacing(2))] bg-transparent"\n // cmdk owns the keyboard while focus is in the list; only Escape\n // (close the menu) and Tab continue outward.\n onKeyDown={(event) => {\n if (event.key !== "Escape" && event.key !== "Tab") {\n event.stopPropagation()\n }\n }}\n >\n <CommandInput\n ref={inputRef}\n placeholder="Search file types…"\n className="h-9"\n />\n <CommandList className="max-h-none">\n <CommandEmpty>No file types found.</CommandEmpty>\n <ScrollArea orientation="vertical" className="h-auto max-h-64">\n <CommandGroup>\n {options.map((option) => {\n const isChecked = checkedMimes.includes(option.mime)\n\n return (\n <CommandItem\n key={option.mime}\n value={option.label}\n keywords={[option.mime]}\n onSelect={() => onToggle(option.mime, !isChecked)}\n >\n <HugeiconsIcon\n icon={Tick02Icon}\n className={cn(\n "size-4 text-foreground",\n !isChecked && "opacity-0"\n )}\n />\n <FileTypeIcon\n fileName={option.iconFileName}\n className="size-4"\n />\n {option.label}\n </CommandItem>\n )\n })}\n </CommandGroup>\n </ScrollArea>\n </CommandList>\n </Command>\n )\n}\n\n// Toolbar filter menu: file types as a searchable checklist, dates as\n// single-select presets plus a custom range, mirroring Extend\'s table\n// filters.\nfunction FileSystemFilterMenu({\n fileTypeOptions,\n filters,\n onOpenCustomRange,\n onSelectDatePreset,\n onToggleFileType,\n}: {\n fileTypeOptions: FileTypeFilterOption[]\n filters: FileSystemFilter[]\n onOpenCustomRange: (type: FileSystemDateFilterType) => void\n onSelectDatePreset: (type: FileSystemDateFilterType, preset: string) => void\n onToggleFileType: (mime: string, checked: boolean) => void\n}) {\n const fileTypeFilter = filters.find((filter) => filter.type === "fileType")\n\n return (\n <DropdownMenu>\n <DropdownMenuTrigger\n render={\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Filter"\n title="Filter"\n className="relative size-7 sm:size-7"\n />\n }\n >\n <HugeiconsIcon icon={FilterIcon} className="size-4" />\n {filters.length > 0 ? (\n <span className="absolute top-1 right-1 size-1.5 rounded-full bg-primary" />\n ) : null}\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="min-w-44">\n <DropdownMenuSub>\n <DropdownMenuSubTrigger>\n <HugeiconsIcon\n icon={File01Icon}\n className="size-4 text-muted-foreground"\n />\n File type\n </DropdownMenuSubTrigger>\n <DropdownMenuSubContent className="w-60">\n <FileSystemFileTypeCommand\n checkedMimes={fileTypeFilter?.value ?? []}\n onToggle={onToggleFileType}\n options={fileTypeOptions}\n />\n </DropdownMenuSubContent>\n </DropdownMenuSub>\n {(["dateModified", "dateCreated"] as const).map((type) => (\n <DropdownMenuSub key={type}>\n <DropdownMenuSubTrigger>\n <HugeiconsIcon\n icon={Calendar03Icon}\n className="size-4 text-muted-foreground"\n />\n {FILTER_TYPE_LABELS[type]}\n </DropdownMenuSubTrigger>\n <DropdownMenuSubContent>\n <ScrollArea orientation="vertical" className="h-auto max-h-72">\n {DATE_FILTER_PRESETS.map((preset) => (\n <DropdownMenuItem\n key={preset}\n onClick={() => onSelectDatePreset(type, preset)}\n >\n {preset}\n </DropdownMenuItem>\n ))}\n <DropdownMenuItem onClick={() => onOpenCustomRange(type)}>\n Custom date range…\n </DropdownMenuItem>\n </ScrollArea>\n </DropdownMenuSubContent>\n </DropdownMenuSub>\n ))}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nconst FILTER_PILL_SEGMENT_CLASSNAME =\n "flex h-5 items-center gap-1 border border-l-0 bg-background px-1.5 whitespace-nowrap text-foreground"\n\nconst FILTER_PILL_BUTTON_CLASSNAME = cn(\n FILTER_PILL_SEGMENT_CLASSNAME,\n "transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"\n)\n\n// One applied filter, rendered as a segmented pill in the status bar:\n// type · operator · value · remove, each segment interactive like Extend\'s\n// table filter pills.\nfunction FileSystemFilterPill({\n fileTypeOptions,\n filter,\n onOpenCustomRange,\n onOperatorChange,\n onRemove,\n onSelectDatePreset,\n onToggleFileType,\n}: {\n fileTypeOptions: FileTypeFilterOption[]\n filter: FileSystemFilter\n onOpenCustomRange?: () => void\n onOperatorChange: (operator: FileSystemFilterOperator) => void\n onRemove: () => void\n onSelectDatePreset: (preset: string) => void\n onToggleFileType: (mime: string, checked: boolean) => void\n}) {\n const isCustomRange =\n filter.type !== "fileType" && isCustomDateRangeValue(filter.value)\n const selectedTypeLabels =\n filter.type === "fileType"\n ? filter.value.map(\n (mime) =>\n fileTypeOptions.find((option) => option.mime === mime)?.label ??\n mime\n )\n : []\n\n return (\n <div className="flex items-center text-xs">\n <span\n className={cn(\n FILTER_PILL_SEGMENT_CLASSNAME,\n "rounded-l-md border-l text-primary"\n )}\n >\n <HugeiconsIcon\n icon={filter.type === "fileType" ? File01Icon : Calendar03Icon}\n className="size-3"\n />\n {FILTER_TYPE_LABELS[filter.type]}\n </span>\n <DropdownMenu>\n <DropdownMenuTrigger\n render={\n <button\n type="button"\n className={cn(FILTER_PILL_BUTTON_CLASSNAME, "text-primary")}\n />\n }\n >\n {FILTER_OPERATOR_LABELS[filter.operator]}\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="min-w-28">\n {filterOperatorChoices(filter).map((operator) => (\n <DropdownMenuItem\n key={operator}\n onClick={() => onOperatorChange(operator)}\n >\n {FILTER_OPERATOR_LABELS[operator]}\n </DropdownMenuItem>\n ))}\n </DropdownMenuContent>\n </DropdownMenu>\n {filter.type === "fileType" ? (\n <DropdownMenu>\n <DropdownMenuTrigger\n render={\n <button\n type="button"\n title={selectedTypeLabels.join(", ")}\n className={FILTER_PILL_BUTTON_CLASSNAME}\n />\n }\n >\n {filter.value.length === 1\n ? selectedTypeLabels[0]\n : `${filter.value.length} selected`}\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="w-60">\n <FileSystemFileTypeCommand\n checkedMimes={filter.value}\n onToggle={onToggleFileType}\n options={fileTypeOptions}\n />\n </DropdownMenuContent>\n </DropdownMenu>\n ) : isCustomRange ? (\n <button\n type="button"\n onClick={onOpenCustomRange}\n className={FILTER_PILL_BUTTON_CLASSNAME}\n >\n {filter.value\n .map((value) => new Date(value).toLocaleDateString("en-US"))\n .join(" – ")}\n </button>\n ) : (\n <DropdownMenu>\n <DropdownMenuTrigger\n render={\n <button type="button" className={FILTER_PILL_BUTTON_CLASSNAME} />\n }\n >\n {filter.value[0]}\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start">\n <ScrollArea orientation="vertical" className="h-auto max-h-72">\n {DATE_FILTER_PRESETS.map((preset) => (\n <DropdownMenuItem\n key={preset}\n onClick={() => onSelectDatePreset(preset)}\n >\n {preset}\n </DropdownMenuItem>\n ))}\n <DropdownMenuItem onClick={onOpenCustomRange}>\n Custom date range…\n </DropdownMenuItem>\n </ScrollArea>\n </DropdownMenuContent>\n </DropdownMenu>\n )}\n <button\n type="button"\n aria-label={`Remove ${FILTER_TYPE_LABELS[filter.type]} filter`}\n onClick={onRemove}\n className={cn(\n FILTER_PILL_BUTTON_CLASSNAME,\n "rounded-r-md px-1 text-muted-foreground hover:text-foreground"\n )}\n >\n <HugeiconsIcon icon={Cancel01Icon} className="size-3" />\n </button>\n </div>\n )\n}\n\nfunction formatDateInputValue(date: Date | undefined) {\n if (!date) return ""\n\n const pad = (value: number) => String(value).padStart(2, "0")\n\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`\n}\n\nfunction parseDateInputValue(value: string) {\n const trimmed = value.trim()\n\n if (!trimmed) return undefined\n\n const isoMatch = /^(\\d{4})-(\\d{1,2})-(\\d{1,2})$/.exec(trimmed)\n\n if (isoMatch) {\n const date = new Date(\n Number(isoMatch[1]),\n Number(isoMatch[2]) - 1,\n Number(isoMatch[3])\n )\n\n return Number.isNaN(date.getTime()) ? undefined : date\n }\n\n const parsed = Date.parse(trimmed)\n\n return Number.isNaN(parsed) ? undefined : new Date(parsed)\n}\n\nconst DATE_RANGE_DIALOG_PRESETS = [\n "Last 7 days",\n "This month",\n "Last 1 month",\n "Last 3 months",\n "This year",\n "Last 12 months",\n]\n\nfunction dateRangePresetRange(preset: string) {\n const from = new Date()\n const to = new Date()\n\n from.setHours(0, 0, 0, 0)\n to.setHours(23, 59, 59, 999)\n\n switch (preset) {\n case "Last 7 days":\n from.setDate(from.getDate() - 6)\n break\n case "This month":\n from.setDate(1)\n break\n case "Last 1 month":\n from.setMonth(from.getMonth() - 1)\n break\n case "Last 3 months":\n from.setMonth(from.getMonth() - 3)\n break\n case "This year":\n from.setMonth(0, 1)\n break\n case "Last 12 months":\n from.setFullYear(from.getFullYear() - 1)\n break\n }\n return { from, to }\n}\n\nconst WEEKDAY_LABELS = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]\n\nfunction calendarDayKey(date: Date) {\n return date.getFullYear() * 10_000 + date.getMonth() * 100 + date.getDate()\n}\n\n// Two-month range calendar for the custom date range dialog (one month at\n// phone widths). Clicking sets the start, then the end; clicking before the\n// start swaps the ends, and a third click restarts the range.\nfunction FileSystemRangeCalendar({\n onSelect,\n range,\n}: {\n onSelect: (range: { from?: Date; to?: Date }) => void\n range: { from?: Date; to?: Date }\n}) {\n const [viewMonth, setViewMonth] = React.useState(() => {\n const base = range.from ?? new Date()\n\n return new Date(base.getFullYear(), base.getMonth(), 1)\n })\n const months = [\n viewMonth,\n new Date(viewMonth.getFullYear(), viewMonth.getMonth() + 1, 1),\n ]\n const fromKey = range.from ? calendarDayKey(range.from) : null\n const toKey = range.to ? calendarDayKey(range.to) : null\n const todayKey = calendarDayKey(new Date())\n\n const handleDayClick = (day: Date) => {\n if (!range.from || range.to) {\n onSelect({ from: day })\n } else if (calendarDayKey(day) < calendarDayKey(range.from)) {\n onSelect({ from: day, to: range.from })\n } else {\n onSelect({ from: range.from, to: day })\n }\n }\n\n return (\n <div className="relative">\n <button\n type="button"\n aria-label="Previous month"\n onClick={() =>\n setViewMonth(\n (previous) =>\n new Date(previous.getFullYear(), previous.getMonth() - 1, 1)\n )\n }\n className="absolute top-0 left-0 flex size-6 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"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4" />\n </button>\n <button\n type="button"\n aria-label="Next month"\n onClick={() =>\n setViewMonth(\n (previous) =>\n new Date(previous.getFullYear(), previous.getMonth() + 1, 1)\n )\n }\n className="absolute top-0 right-0 flex size-6 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"\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-4" />\n </button>\n <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">\n {months.map((month, monthIndex) => {\n const firstWeekday = month.getDay()\n const dayCount = new Date(\n month.getFullYear(),\n month.getMonth() + 1,\n 0\n ).getDate()\n const cells = [\n ...Array.from({ length: firstWeekday }, () => null),\n ...Array.from(\n { length: dayCount },\n (_, index) =>\n new Date(month.getFullYear(), month.getMonth(), index + 1)\n ),\n ]\n\n return (\n <div\n key={`${month.getFullYear()}-${month.getMonth()}`}\n className={cn(monthIndex === 1 && "max-sm:hidden")}\n >\n <div className="text-center text-sm leading-6 font-medium">\n {month.toLocaleDateString("en-US", {\n month: "long",\n year: "numeric",\n })}\n </div>\n <div className="mt-1 grid grid-cols-7 text-center text-xs text-muted-foreground">\n {WEEKDAY_LABELS.map((weekday) => (\n <span key={weekday} className="h-6 leading-6">\n {weekday}\n </span>\n ))}\n </div>\n <div className="grid grid-cols-7 gap-y-px">\n {cells.map((day, cellIndex) => {\n if (!day) return <span key={cellIndex} />\n\n const dayKey = calendarDayKey(day)\n const isFrom = dayKey === fromKey\n const isTo = dayKey === toKey\n const isWithinRange =\n fromKey !== null &&\n toKey !== null &&\n dayKey > fromKey &&\n dayKey < toKey\n\n return (\n <button\n key={cellIndex}\n type="button"\n onClick={() => handleDayClick(day)}\n className={cn(\n "flex h-7 items-center justify-center rounded-md text-xs tabular-nums transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",\n isWithinRange && "rounded-none bg-accent",\n (isFrom || isTo) &&\n "bg-primary text-primary-foreground hover:bg-primary",\n isFrom &&\n toKey !== null &&\n fromKey !== toKey &&\n "rounded-r-none",\n isTo && fromKey !== toKey && "rounded-l-none",\n dayKey === todayKey &&\n !isFrom &&\n !isTo &&\n "font-semibold text-primary"\n )}\n >\n {day.getDate()}\n </button>\n )\n })}\n </div>\n </div>\n )\n })}\n </div>\n </div>\n )\n}\n\n// Custom date range dialog mirroring Extend\'s table filters: From/To inputs,\n// a two-month range calendar, and quick presets. Applied ranges span from\n// the start of the first day to the end of the last.\nfunction FileSystemDateRangeDialog({\n initialRange,\n onApply,\n onClose,\n}: {\n initialRange?: { from: Date; to: Date }\n onApply: (from: Date, to: Date) => void\n onClose: () => void\n}) {\n const [range, setRange] = React.useState<{ from?: Date; to?: Date }>(\n () => initialRange ?? {}\n )\n const [fromInput, setFromInput] = React.useState(() =>\n formatDateInputValue(initialRange?.from)\n )\n const [toInput, setToInput] = React.useState(() =>\n formatDateInputValue(initialRange?.to)\n )\n\n const selectRange = (next: { from?: Date; to?: Date }) => {\n setRange(next)\n if (next.from) setFromInput(formatDateInputValue(next.from))\n if (next.to) setToInput(formatDateInputValue(next.to))\n }\n\n const dateField = (\n label: string,\n value: string,\n onChange: (value: string) => void\n ) => (\n <div className="flex flex-1 flex-col gap-1.5">\n <span className="text-xs font-medium">{label}</span>\n <div className="relative flex items-center">\n <HugeiconsIcon\n icon={Calendar03Icon}\n className="pointer-events-none absolute left-2.5 size-3.5 text-muted-foreground"\n />\n <Input\n type="text"\n value={value}\n placeholder="YYYY-MM-DD"\n aria-label={`${label} date`}\n onChange={(event) => onChange(event.target.value)}\n className="h-8 pl-8 sm:h-8"\n />\n </div>\n </div>\n )\n\n return (\n <Dialog\n open\n onOpenChange={(open) => {\n if (!open) onClose()\n }}\n >\n <DialogContent className="w-[30rem] max-w-[calc(100vw-2rem)]">\n <DialogHeader>\n <DialogTitle>Custom date range</DialogTitle>\n </DialogHeader>\n <DialogPanel className="flex flex-col gap-4">\n <div className="flex gap-3">\n {dateField("From", fromInput, (value) => {\n setFromInput(value)\n\n const parsed = parseDateInputValue(value)\n\n if (parsed)\n setRange((previous) => ({ ...previous, from: parsed }))\n })}\n {dateField("To", toInput, (value) => {\n setToInput(value)\n\n const parsed = parseDateInputValue(value)\n\n if (parsed) setRange((previous) => ({ ...previous, to: parsed }))\n })}\n </div>\n <FileSystemRangeCalendar range={range} onSelect={selectRange} />\n <div className="grid grid-cols-3 gap-2">\n {DATE_RANGE_DIALOG_PRESETS.map((preset) => (\n <Button\n key={preset}\n type="button"\n variant="outline"\n size="sm"\n onClick={() => selectRange(dateRangePresetRange(preset))}\n >\n {preset}\n </Button>\n ))}\n </div>\n </DialogPanel>\n <DialogFooter>\n <Button type="button" variant="outline" onClick={onClose}>\n Cancel\n </Button>\n <Button\n type="button"\n disabled={!range.from || !range.to}\n onClick={() => {\n if (!range.from || !range.to) return\n\n const from = new Date(range.from)\n const to = new Date(range.to)\n\n from.setHours(0, 0, 0, 0)\n to.setHours(23, 59, 59, 999)\n onApply(from, to)\n }}\n >\n Apply\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\ntype FileSystemViewProps = {\n currentPath: string\n entries: FileSystemEntry[]\n fileFilter: ((file: FileEntry) => boolean) | null\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 onSortColumnClick: (key: FileSystemSortKey) => void\n /** Pooled paths currently attached to the DOM (reveal instantly). */\n attachedStagePaths: string[]\n /** `"path#pageIndex"` → thumbnail URL, shared by every pager. */\n pageUrlCache: Map<string, string>\n /** Admits a file into the root-owned keep-alive preview pool. */\n poolStagePath: (path: string) => void\n /** Mounts/unmounts the gallery host element for a pooled path. */\n registerStageHost: (path: string, element: HTMLElement | null) => void\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n searchQuery: string\n selectedEntry: FileSystemEntry | null\n selectedPath: string | null\n sort: FileSystemSortState\n /** Expanded tree folders per folder path, surviving view switches. */\n treeExpansionRef: React.RefObject<Map<string, readonly string[]>>\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. An\n// optional `cache` shared across mounts serves revisited files synchronously:\n// no repeat presign round-trip (and no loading flash), and the stable URL\n// keeps the browser\'s HTTP cache valid for already-fetched content.\nfunction useResolvedFileUrl(\n file: FileEntry | null,\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>,\n cache?: Map<string, string>\n) {\n const [state, setState] = React.useState<{\n isResolving: boolean\n url: string | null\n }>(() => ({\n isResolving: false,\n url: file ? (file.url ?? cache?.get(file.path) ?? null) : 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 const knownUrl =\n fileUrl ?? (filePath ? (cache?.get(filePath) ?? null) : null)\n\n if (!currentFile || knownUrl || !getFileUrl) {\n setState({ isResolving: false, url: knownUrl })\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 (url) cache?.set(currentFile.path, 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 }, [cache, 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// Type-ahead buffers reset after this idle period, like Finder.\nconst TYPE_AHEAD_RESET_MS = 700\n\n// Letters and digits only — the same key test the tree uses — so shortcuts\n// and whitespace scrolling stay untouched.\nfunction isTypeAheadKey(event: React.KeyboardEvent) {\n return (\n event.key.length === 1 &&\n /^[\\p{L}\\p{N}]$/u.test(event.key) &&\n !event.altKey &&\n !event.ctrlKey &&\n !event.metaKey\n )\n}\n\n// Shared Finder-style type-ahead used by every view: printable keys\n// accumulate a buffer that jumps to the next entry whose name starts with\n// it, and repeating a single letter cycles through entries with that\n// prefix. Each view passes its own display-ordered candidate list, so the\n// same keystrokes land on the same file everywhere.\nfunction useEntryTypeAhead() {\n const stateRef = React.useRef({ buffer: "", timeout: 0 })\n\n React.useEffect(() => {\n const state = stateRef.current\n\n return () => window.clearTimeout(state.timeout)\n }, [])\n\n return React.useCallback(\n (\n event: React.KeyboardEvent,\n entries: readonly FileSystemEntry[],\n currentIndex: number\n ) => {\n if (!isTypeAheadKey(event) || entries.length === 0) return null\n\n // Embedded viewers (and any future inputs) keep their keystrokes.\n const target = event.target\n\n if (\n target instanceof HTMLElement &&\n (target.isContentEditable ||\n target.tagName === "INPUT" ||\n target.tagName === "TEXTAREA" ||\n target.tagName === "SELECT")\n ) {\n return null\n }\n\n const state = stateRef.current\n\n window.clearTimeout(state.timeout)\n state.timeout = window.setTimeout(() => {\n state.buffer = ""\n }, TYPE_AHEAD_RESET_MS)\n state.buffer += event.key.toLowerCase()\n\n // A repeated single letter advances past the current entry; a longer\n // buffer refines the match in place.\n const startIndex =\n currentIndex < 0\n ? 0\n : currentIndex + (state.buffer.length === 1 ? 1 : 0)\n\n for (let step = 0; step < entries.length; step += 1) {\n const entry = entries[(startIndex + step) % entries.length]\n\n if (entry.name.toLowerCase().startsWith(state.buffer)) {\n event.preventDefault()\n return entry\n }\n }\n event.preventDefault()\n return null\n },\n []\n )\n}\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\n// Icon grid geometry (px at the default 16px root font size). Tiles have a\n// fixed height — a 4rem glyph box plus a reserved two-line label — so rows\n// share one stride and the grid can window cleanly.\nconst ICON_GRID_PADDING = 12 // p-3\nconst ICON_MIN_TILE_WIDTH = 104 // 6.5rem\nconst ICON_TILE_GAP_X = 4 // gap-x-1\nconst ICON_TILE_HEIGHT = 102 // h-16 glyph box + gap-1.5 + two text-xs lines\nconst ICON_ROW_GAP = 12 // gap-y-3\nconst ICON_ROW_STRIDE = ICON_TILE_HEIGHT + ICON_ROW_GAP\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 const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const typeAhead = useEntryTypeAhead()\n // The column count mirrors what `repeat(auto-fill, minmax(6.5rem, 1fr))`\n // produces (the CSS owns the actual layout) so item indices map to grid\n // rows — the windowing below depends on that mapping. It stays null until\n // the first client measure; server markup must not guess.\n const [columnCount, setColumnCount] = React.useState<number | null>(null)\n\n React.useLayoutEffect(() => {\n const viewport = viewportRef.current\n\n if (!viewport || typeof ResizeObserver === "undefined") return\n\n const update = () => {\n const available = viewport.clientWidth - ICON_GRID_PADDING * 2\n\n setColumnCount(\n Math.max(\n 1,\n Math.floor(\n (available + ICON_TILE_GAP_X) /\n (ICON_MIN_TILE_WIDTH + ICON_TILE_GAP_X)\n )\n )\n )\n }\n const observer = new ResizeObserver(update)\n\n update()\n observer.observe(viewport)\n return () => observer.disconnect()\n }, [])\n\n const resolvedColumnCount = columnCount ?? 1\n const rowCount = Math.ceil(entries.length / resolvedColumnCount)\n const { end, start } = useVirtualWindow({\n count: rowCount,\n itemStride: ICON_ROW_STRIDE,\n leadingPx: ICON_GRID_PADDING,\n overscan: 4,\n viewportRef,\n })\n const visibleEntries = entries.slice(\n start * resolvedColumnCount,\n end * resolvedColumnCount\n )\n\n // Selection can land outside the window (view switches, shrinking results);\n // bring its row back into the viewport so the tile mounts and is focusable.\n React.useLayoutEffect(() => {\n if (!selectedPath) return\n\n const entryIndex = entries.findIndex((entry) => entry.path === selectedPath)\n\n if (entryIndex === -1) return\n\n scrollIndexIntoView({\n index: Math.floor(entryIndex / resolvedColumnCount),\n itemSize: ICON_TILE_HEIGHT,\n itemStride: ICON_ROW_STRIDE,\n leadingPx: ICON_GRID_PADDING,\n viewport: viewportRef.current,\n })\n }, [entries, resolvedColumnCount, selectedPath])\n\n // Roving tabindex: the grid is a single tab stop (the selected tile when\n // rendered, else the first rendered one), so Shift+Tab returns to the\n // toolbar like in the list view.\n const tabStopPath = visibleEntries.some(\n (entry) => entry.path === selectedPath\n )\n ? selectedPath\n : (visibleEntries[0]?.path ?? null)\n\n return (\n <ScrollArea\n orientation="vertical"\n viewportRef={viewportRef}\n viewportClassName="p-3"\n viewportProps={{\n onClick: (event) => {\n if (event.target === event.currentTarget) onSelect(null)\n },\n }}\n >\n <div\n className="relative"\n // The scroll-height spacer needs the measured column count; until\n // then the absolutely positioned grid alone defines the scrollable\n // overflow, so the server-rendered frame doesn\'t flash an\n // oversized scroll range.\n style={{\n height:\n columnCount !== null && rowCount\n ? rowCount * ICON_ROW_STRIDE - ICON_ROW_GAP\n : undefined,\n }}\n >\n <div\n role="listbox"\n aria-label="Files"\n className="absolute inset-x-0 grid gap-x-1 gap-y-3"\n // The auto-fill expression produces the same column count the\n // ResizeObserver measures (the measurement exists only for the\n // windowing math), so the server-rendered first paint is already\n // a grid instead of flashing a single stacked column until the\n // first client measure.\n style={{\n gridTemplateColumns: "repeat(auto-fill, minmax(6.5rem, 1fr))",\n top: start * ICON_ROW_STRIDE,\n }}\n onKeyDown={(event) => {\n if (!ARROW_KEYS.has(event.key)) {\n const match = typeAhead(\n event,\n entries,\n entries.findIndex((entry) => entry.path === selectedPath)\n )\n\n if (match) {\n onSelect(match)\n // The matched tile may be outside the virtual window; the\n // selection effect scrolls it in, and focus follows once it\n // has mounted.\n requestAnimationFrame(() =>\n itemRefs.current.get(match.path)?.focus()\n )\n }\n return\n }\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 {visibleEntries.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 h-[6.375rem] flex-col items-center gap-1.5 outline-none"\n >\n <span\n className={cn(\n "flex h-16 w-20 shrink-0 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 </div>\n </ScrollArea>\n )\n}\n\n// One sortable column header for the list view; the active column shows the\n// direction chevron on its right.\nfunction FileSystemListColumnHeader({\n className,\n label,\n onClick,\n sort,\n sortKey,\n}: {\n className?: string\n label: string\n onClick: (key: FileSystemSortKey) => void\n sort: FileSystemSortState\n sortKey: FileSystemSortKey\n}) {\n const isActive = sort.key === sortKey\n\n return (\n <button\n type="button"\n onClick={() => onClick(sortKey)}\n className={cn(\n "flex items-center gap-0.5 rounded-sm py-0.5 transition-colors outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",\n isActive && "text-foreground",\n className\n )}\n >\n {label}\n {isActive ? (\n <HugeiconsIcon\n icon={sort.direction === "asc" ? ArrowUp01Icon : ArrowDown01Icon}\n className="size-3 shrink-0"\n />\n ) : null}\n </button>\n )\n}\n\nfunction FileSystemListView({\n currentPath,\n fileFilter,\n index,\n onOpen,\n onSelect,\n onSortColumnClick,\n searchQuery,\n selectedPath,\n sort,\n treeExpansionRef,\n}: FileSystemViewProps) {\n // Filters narrow the path list handed to the tree; the search query stays\n // out of it so the tree\'s own search session (with match highlighting)\n // keeps handling it without remounts per keystroke.\n const relativePaths = React.useMemo(() => {\n const paths: string[] = []\n\n for (const [path, file] of index.files) {\n if (currentPath === "" || path.startsWith(currentPath)) {\n const relativePath = path.slice(currentPath.length)\n\n if (!relativePath) continue\n if (fileFilter && !fileFilter(file)) continue\n paths.push(relativePath)\n }\n }\n return paths.sort()\n }, [currentPath, fileFilter, index])\n\n if (relativePaths.length === 0) {\n return (\n <FileSystemEmptyState\n label={\n fileFilter\n ? "No items match the active filters"\n : "This folder is empty"\n }\n />\n )\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 pr-6 pl-[46px] text-xs font-medium text-muted-foreground">\n <FileSystemListColumnHeader\n className="flex-1 justify-start"\n label="Name"\n onClick={onSortColumnClick}\n sort={sort}\n sortKey="name"\n />\n <FileSystemListColumnHeader\n className="w-44 justify-start"\n label="Date Modified"\n onClick={onSortColumnClick}\n sort={sort}\n sortKey="updatedAt"\n />\n <FileSystemListColumnHeader\n className="w-20 justify-start"\n label="Size"\n onClick={onSortColumnClick}\n sort={sort}\n sortKey="size"\n />\n </div>\n {/* Keyed by folder only: navigation remounts the tree, while filter,\n sort, and manifest changes update the mounted model in place so\n folder disclosure state survives them. */}\n <FileSystemPierreTree\n key={currentPath}\n currentPath={currentPath}\n hasActiveFilters={fileFilter !== null}\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 searchQuery={searchQuery}\n sort={sort}\n treeExpansionRef={treeExpansionRef}\n />\n </div>\n )\n}\n\n// Embedded thumbnail symbols grow the sprite injected into the tree\'s shadow\n// DOM (data-URL covers can run hundreds of KB each); past this many the\n// remaining files fall back to the built-in file-type icons alone.\nconst TREE_THUMBNAIL_SPRITE_LIMIT = 400\n\nfunction FileSystemPierreTree({\n currentPath,\n hasActiveFilters,\n index,\n initialSelectedPath,\n onOpen,\n onSelect,\n relativePaths,\n searchQuery,\n sort,\n treeExpansionRef,\n}: {\n currentPath: string\n hasActiveFilters: boolean\n index: FileSystemIndex\n initialSelectedPath: string | null\n onOpen: (entry: FileSystemEntry) => void\n onSelect: (entry: FileSystemEntry | null) => void\n relativePaths: string[]\n searchQuery: string\n sort: FileSystemSortState\n treeExpansionRef: React.RefObject<Map<string, readonly string[]>>\n}) {\n // The tree\'s comparator receives whole paths, not siblings, so it walks\n // the shared segments and applies the active sort at the first level the\n // two paths diverge — keeping directories first per level, the tree\'s\n // default convention. Lookups go through the index maps, which are stable\n // across search keystrokes.\n const indexFiles = index.files\n const indexFolders = index.folders\n const sortComparator = React.useMemo<\n "default" | FileTreeSortComparator\n >(() => {\n if (\n sort.key === DEFAULT_SORT.key &&\n sort.direction === DEFAULT_SORT.direction\n ) {\n return "default"\n }\n\n const entryAtDepth = (sortEntry: FileTreeSortEntry, depth: number) => {\n const isDirectory =\n depth < sortEntry.segments.length - 1 || sortEntry.isDirectory\n const absolutePath = `${currentPath}${sortEntry.segments\n .slice(0, depth + 1)\n .join("/")}${isDirectory ? "/" : ""}`\n\n return isDirectory\n ? indexFolders.get(absolutePath)\n : indexFiles.get(absolutePath)\n }\n\n return (left, right) => {\n const sharedDepth = Math.min(left.segments.length, right.segments.length)\n\n for (let depth = 0; depth < sharedDepth; depth += 1) {\n if (left.segments[depth] === right.segments[depth]) continue\n\n const leftIsDirectory =\n depth < left.segments.length - 1 || left.isDirectory\n const rightIsDirectory =\n depth < right.segments.length - 1 || right.isDirectory\n\n if (leftIsDirectory !== rightIsDirectory) {\n return leftIsDirectory ? -1 : 1\n }\n\n const leftEntry = entryAtDepth(left, depth)\n const rightEntry = entryAtDepth(right, depth)\n\n if (leftEntry && rightEntry) {\n return compareEntriesBySort(leftEntry, rightEntry, sort)\n }\n return left.segments[depth] < right.segments[depth] ? -1 : 1\n }\n return left.segments.length - right.segments.length\n }\n }, [currentPath, indexFiles, indexFolders, sort])\n const preparedInput = React.useMemo(\n () => prepareFileTreeInput(relativePaths, { sort: sortComparator }),\n [relativePaths, sortComparator]\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. Files without\n // a thumbnail resolve through the built-in complete icon set instead — the\n // same colored file-type icons the other views use. 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 let thumbnailCount = 0\n\n for (const relativePath of relativePaths) {\n if (thumbnailCount >= TREE_THUMBNAIL_SPRITE_LIMIT) break\n\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 thumbnailCount += 1\n }\n\n return {\n byFileName,\n colored: true,\n remap: {\n "file-tree-icon-chevron": {\n name: "file-system-chevron",\n viewBox: "0 0 24 24",\n },\n },\n set: "complete" as const,\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 // Remounts (folder changes, manifest updates) keep the active filter.\n initialSearchQuery: searchQuery || null,\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 /* The primary surface is the opposite of the mode\'s background, so\n the row\'s light-dark() icon colors resolve against the opposite\n scheme — light-palette icons on the light pill in dark mode and\n vice versa. */\n color-scheme: var(--fs-selected-color-scheme, normal);\n }\n button[data-type=\'item\'][data-item-selected] *:not([data-icon-token]):not([data-icon-token] *),\n button[data-type=\'item\'][data-item-selected] [data-item-section]::before {\n color: var(--color-primary-foreground) !important;\n }\n [data-item-section=\'decoration\'] > span {\n display: grid;\n grid-template-columns: 11rem 5rem;\n white-space: nowrap;\n /* The size cell is the span\'s anonymous text item, so alignment\n rides on text-align: the span\'s right applies to it while the\n date cell (::before) overrides back to left. */\n text-align: right;\n }\n [data-item-section=\'decoration\'] > span::before {\n content: attr(title);\n text-align: left;\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 folders currently expanded in the mounted model, derived from the\n // given path list (the model knows the rows; the paths name the\n // directories to ask about).\n const collectExpandedDirectories = React.useCallback(\n (paths: readonly string[]) => {\n const expandedPaths: string[] = []\n\n for (const directoryPath of directoryPathsOf(paths)) {\n const item =\n model.getItem(directoryPath) ?? model.getItem(`${directoryPath}/`)\n\n if (item && "isExpanded" in item && item.isExpanded()) {\n expandedPaths.push(directoryPath)\n }\n }\n return expandedPaths\n },\n [model]\n )\n\n // Opens every given folder on the mounted model (no-ops on the already\n // open ones).\n const expandDirectories = React.useCallback(\n (directoryPaths: Iterable<string>) => {\n for (const directoryPath of directoryPaths) {\n const item =\n model.getItem(directoryPath) ?? model.getItem(`${directoryPath}/`)\n\n if (item && "isExpanded" in item && !item.isExpanded()) {\n item.toggle()\n }\n }\n },\n [model]\n )\n\n // Sort and filter changes swap the prepared input in place — remounting\n // would reset every folder\'s disclosure. The folders expanded in the\n // outgoing path list, the selection, and the active search query are\n // captured first and handed back to the reset.\n const appliedPreparedInputRef = React.useRef(preparedInput)\n // Filter bookkeeping: the latest prop (for unmount-time decisions), the\n // state at the last applied reset (for transition detection), and the\n // disclosure to restore once the filters clear.\n const hasActiveFiltersRef = React.useRef(hasActiveFilters)\n const filteredAtLastResetRef = React.useRef(hasActiveFilters)\n const preFilterExpansionRef = React.useRef<readonly string[] | null>(null)\n\n React.useEffect(() => {\n hasActiveFiltersRef.current = hasActiveFilters\n })\n\n React.useEffect(() => {\n const previousPreparedInput = appliedPreparedInputRef.current\n\n if (previousPreparedInput === preparedInput) return\n appliedPreparedInputRef.current = preparedInput\n\n const wasFiltered = filteredAtLastResetRef.current\n\n filteredAtLastResetRef.current = hasActiveFilters\n\n // Filters reveal their matches the way the search session does: every\n // folder on the way to a match opens. The disclosure from just before\n // filtering is kept aside and comes back when the filters clear.\n let expandedPaths: readonly string[]\n\n if (hasActiveFilters) {\n if (!wasFiltered) {\n preFilterExpansionRef.current = collectExpandedDirectories(\n previousPreparedInput.paths\n )\n }\n expandedPaths = [...directoryPathsOf(preparedInput.paths)]\n } else if (wasFiltered) {\n expandedPaths = preFilterExpansionRef.current ?? []\n preFilterExpansionRef.current = null\n } else {\n expandedPaths = collectExpandedDirectories(previousPreparedInput.paths)\n }\n\n const searchValue = model.getSearchValue()\n\n // The `paths` argument must stay unset: when both are given, resetPaths\n // re-prepares the paths with the comparator the model was CREATED with\n // and rejects the differently-ordered prepared input. Passing only the\n // prepared input makes the reset adopt its path list as-is, and the\n // reset itself carries the selection over.\n model.resetPaths(undefined as unknown as readonly string[], {\n initialExpandedPaths: expandedPaths,\n preparedInput,\n })\n if (searchValue) model.setSearch(searchValue)\n }, [collectExpandedDirectories, hasActiveFilters, model, preparedInput])\n\n // View switches and navigation unmount the tree; remember which folders\n // were left expanded and reopen them on the next mount of this folder\n // (before paint, so the restored disclosure never flashes closed). While\n // filters are active their matches are revealed instead, and the\n // remembered disclosure is the pre-filter one.\n React.useLayoutEffect(() => {\n const expansionStore = treeExpansionRef.current\n const savedExpansion = expansionStore.get(currentPath) ?? []\n\n if (hasActiveFiltersRef.current) {\n preFilterExpansionRef.current = savedExpansion\n expandDirectories(directoryPathsOf(appliedPreparedInputRef.current.paths))\n } else {\n expandDirectories(savedExpansion)\n }\n\n return () => {\n expansionStore.set(\n currentPath,\n hasActiveFiltersRef.current\n ? (preFilterExpansionRef.current ?? [])\n : collectExpandedDirectories(appliedPreparedInputRef.current.paths)\n )\n }\n }, [\n collectExpandedDirectories,\n currentPath,\n expandDirectories,\n treeExpansionRef,\n ])\n\n // The toolbar search drives the tree\'s own search session, which filters\n // rows with hide-non-matches semantics and highlights the matched text.\n React.useEffect(() => {\n model.setSearch(searchQuery || null)\n }, [model, searchQuery])\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 // Rows live in the tree\'s shadow DOM; composedPath surfaces the row\n // element behind a pointer or keyboard event so it can resolve to a\n // manifest entry.\n const entryFromEvent = (event: React.SyntheticEvent) => {\n for (const target of event.nativeEvent.composedPath()) {\n if (!(target instanceof HTMLElement)) continue\n\n const relativePath = target.dataset?.itemPath\n\n if (!relativePath) continue\n\n const absolutePath = `${currentPath}${relativePath}`\n\n return (\n index.files.get(absolutePath) ??\n index.folders.get(normalizeFolderPath(absolutePath)) ??\n null\n )\n }\n return null\n }\n\n // The tree exposes rows by relative path; directory ids may or may not\n // carry the trailing slash depending on the call site.\n const resolveTreeItem = (relativePath: string) =>\n model.getItem(relativePath) ??\n model.getItem(\n relativePath.endsWith("/")\n ? relativePath.slice(0, -1)\n : `${relativePath}/`\n )\n\n // The tree\'s rows in display order — folders first per level, recursing\n // only into expanded folders — so type-ahead cycles exactly what\'s on\n // screen. Virtualization keeps this off the DOM; the index and the item\n // handles carry the same information.\n const collectVisibleEntries = () => {\n const visibleEntries: FileSystemEntry[] = []\n const walk = (folderPath: string) => {\n const children = index.children.get(folderPath) ?? []\n\n for (const child of children) {\n if (child.kind !== "folder") continue\n\n const item = resolveTreeItem(child.path.slice(currentPath.length))\n\n if (!item) continue\n visibleEntries.push(child)\n if ("isExpanded" in item && item.isExpanded()) walk(child.path)\n }\n for (const child of children) {\n if (child.kind === "file") visibleEntries.push(child)\n }\n }\n\n walk(currentPath)\n return visibleEntries\n }\n\n const typeAhead = useEntryTypeAhead()\n\n return (\n <PierreFileTree\n model={model}\n className="block min-h-0 flex-1"\n // Finder semantics: double-clicking a folder navigates into it and\n // double-clicking a file opens it; a single click still only toggles\n // the folder\'s disclosure.\n onDoubleClick={(event) => {\n const entry = entryFromEvent(event)\n\n if (entry) onOpen(entry)\n }}\n // Enter mirrors the other views: navigate into the focused folder or\n // open the focused file. Printable keys run the shared type-ahead\n // over the visible rows.\n onKeyDown={(event) => {\n if (event.key === "Enter") {\n const entry = entryFromEvent(event)\n\n if (entry) {\n event.preventDefault()\n onOpen(entry)\n }\n return\n }\n\n if (!isTypeAheadKey(event)) return\n\n const visibleEntries = collectVisibleEntries()\n const focusedPath = model.getFocusedPath()?.replace(/\\/$/, "") ?? null\n const focusedIndex = visibleEntries.findIndex(\n (entry) =>\n entry.path.slice(currentPath.length).replace(/\\/$/, "") ===\n focusedPath\n )\n const match = typeAhead(event, visibleEntries, focusedIndex)\n\n if (!match) return\n\n const item = resolveTreeItem(match.path.slice(currentPath.length))\n\n if (item) {\n model.scrollToPath(item.getPath())\n item.focus()\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 pageUrlCache,\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 const typeAhead = useEntryTypeAhead()\n\n const handleKeyDown = (event: React.KeyboardEvent) => {\n if (!ARROW_KEYS.has(event.key)) {\n // Type-ahead moves within the active column\'s rows, like Finder.\n const siblings =\n selectedEntry && selectedPath?.startsWith(currentPath)\n ? (index.children.get(selectedEntry.parentPath) ?? [])\n : (index.children.get(currentPath) ?? [])\n const match = typeAhead(\n event,\n siblings,\n siblings.findIndex((sibling) => sibling.path === selectedPath)\n )\n\n if (match) {\n onSelect(match)\n\n const row = rowRefs.current.get(match.path)\n\n if (row) {\n row.focus()\n } else {\n pendingFocusPathRef.current = match.path\n }\n }\n return\n }\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 // 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 {/* The Content part\'s ResizeObserver tells the scroll area when the\n trail shrinks (deselect, shallower selection) so the horizontal\n scrollbar hides; the viewport alone only observes its own box. Its\n built-in inline min-width (fit-content) would beat a min-w-full\n class, so the full-width floor is inline too. */}\n <ScrollAreaPrimitive.Content\n className="flex h-full w-max"\n style={{ minWidth: "100%" }}\n onKeyDown={handleKeyDown}\n >\n {columnPaths.map((columnPath, columnIndex) => (\n <FileSystemColumn\n key={columnPath || "(root)"}\n entries={index.children.get(columnPath) ?? []}\n index={index}\n isLoading={loadingFolders.has(columnPath)}\n onOpen={onOpen}\n onSelect={onSelect}\n rowRefs={rowRefs}\n // Scalar per-column props so the memoized column only\n // re-renders when its own rows change — a selection deeper in\n // the trail leaves ancestor columns untouched.\n selectedChildPath={\n selectedPath && pathParent(selectedPath) === columnPath\n ? selectedPath\n : null\n }\n tabStopChildPath={\n tabStopPath && pathParent(tabStopPath) === columnPath\n ? tabStopPath\n : null\n }\n trailChildPath={columnPaths[columnIndex + 1] ?? null}\n />\n ))}\n {selectedFile ? (\n // contain-inline-size zeroes the pane\'s intrinsic width so its\n // max-content contribution is exactly the min-w-60 floor — matching\n // a column\'s w-60. Otherwise long filenames or wide thumbnails\n // would nudge the overflowing trail\'s scroll width as the arrow-key\n // selection alternates between files and folders.\n <ScrollArea\n orientation="vertical"\n className="min-w-60 flex-1 contain-inline-size"\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 pageUrlCache={pageUrlCache}\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 </ScrollAreaPrimitive.Content>\n </ScrollArea>\n )\n}\n\n// Column row geometry (px at the default 16px root font size).\nconst COLUMN_PADDING = 6 // p-1.5\nconst COLUMN_ROW_HEIGHT = 28 // h-7\nconst COLUMN_ROW_GAP = 1 // gap-px\nconst COLUMN_ROW_STRIDE = COLUMN_ROW_HEIGHT + COLUMN_ROW_GAP\n\n// Memoized with scalar selection props: pressing into a deep trail only\n// re-renders the columns whose rows actually change.\nconst FileSystemColumn = React.memo(function FileSystemColumn({\n entries,\n index,\n isLoading,\n onOpen,\n onSelect,\n rowRefs,\n selectedChildPath,\n tabStopChildPath,\n trailChildPath,\n}: {\n entries: FileSystemEntry[]\n index: FileSystemIndex\n isLoading: boolean\n onOpen: (entry: FileSystemEntry) => void\n onSelect: (entry: FileSystemEntry | null) => void\n rowRefs: React.RefObject<Map<string, HTMLButtonElement>>\n selectedChildPath: string | null\n tabStopChildPath: string | null\n trailChildPath: string | null\n}) {\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const { end, start } = useVirtualWindow({\n count: entries.length,\n itemStride: COLUMN_ROW_STRIDE,\n leadingPx: COLUMN_PADDING,\n overscan: 10,\n viewportRef,\n })\n\n // Keyboard navigation can select a row this column hasn\'t mounted; scroll\n // it into the viewport so it mounts and the pending-focus effect can land.\n React.useLayoutEffect(() => {\n if (!selectedChildPath) return\n\n scrollIndexIntoView({\n index: entries.findIndex((entry) => entry.path === selectedChildPath),\n itemSize: COLUMN_ROW_HEIGHT,\n itemStride: COLUMN_ROW_STRIDE,\n leadingPx: COLUMN_PADDING,\n viewport: viewportRef.current,\n })\n }, [entries, selectedChildPath])\n\n return (\n <ScrollArea\n orientation="vertical"\n className="w-60 shrink-0 border-r"\n viewportRef={viewportRef}\n viewportClassName="p-1.5"\n viewportProps={{ "aria-label": "Files", role: "listbox" }}\n >\n {isLoading && entries.length === 0 ? (\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 <div\n className="relative"\n style={{\n height: entries.length\n ? entries.length * COLUMN_ROW_STRIDE - COLUMN_ROW_GAP\n : undefined,\n }}\n >\n <div\n className="absolute inset-x-0 flex flex-col gap-px"\n style={{ top: start * COLUMN_ROW_STRIDE }}\n >\n {entries.slice(start, end).map((entry) => {\n const isSelected = entry.path === selectedChildPath\n const isOnTrail =\n entry.kind === "folder" && entry.path === trailChildPath\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 // Selected rows sit on the primary surface — the opposite\n // of the mode\'s background — so the file-type icon swaps\n // to the opposite palette.\n data-file-system-on-primary={isSelected ? "" : undefined}\n tabIndex={entry.path === tabStopChildPath ? 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 // Selecting on press (mouse only) starts mounting the\n // child column a beat before mouseup — the immediacy\n // @pierre/trees rows have. Touch keeps selection on the\n // click so scroll gestures don\'t select.\n onPointerDown={(event) => {\n if (event.pointerType === "mouse" && event.button === 0) {\n onSelect(entry)\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 h-7 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 // eslint-disable-next-line @next/next/no-img-element -- Cover thumbnails come from caller-provided file preview URLs.\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 <FileTypeIcon\n fileName={entry.name}\n className="size-4 shrink-0"\n />\n )}\n <span className="min-w-0 flex-1 truncate">{entry.name}</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 </div>\n </div>\n )}\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\n// Filmstrip geometry (px at the default 16px root font size).\nconst GALLERY_STRIP_PADDING = 8 // p-2\nconst GALLERY_TILE_SIZE = 56 // size-14\nconst GALLERY_TILE_GAP = 6 // gap-1.5\nconst GALLERY_TILE_STRIDE = GALLERY_TILE_SIZE + GALLERY_TILE_GAP\n// How many visited stages stay mounted so stepping back to a recent file\n// restores its already-loaded preview without refetching or re-parsing;\n// also bounds the memory the keep-alive pool can hold onto.\nconst GALLERY_STAGE_POOL_SIZE = 4\n// Of those, how many stay attached to the DOM (the active stage plus the\n// two before it, keeping the usual two-or-three-file rotation instant).\n// The rest wait detached, costing no layout or style-recalc work until\n// they return — their page canvases remount on the way back, so returning\n// to a detached stage briefly rebuilds the page content.\nconst GALLERY_STAGE_ATTACHED_COUNT = 3\n\n// The preview for one pooled file. Each stage owns its URL resolution and\n// viewer state, so a mounted stage is self-contained: the root keeps\n// recently shown stages alive (reparented between hosts rather than\n// remounted, because the document viewers load in effects and would\n// refetch and re-parse on remount) and revisiting one — in the gallery or\n// the dialog — skips the presign, download, and parse work instead of\n// re-running it behind a spinner. The two variants share one element\n// structure, differing only in props and classes, so flipping a mounted\n// stage between them keeps the viewer instance.\nfunction FileSystemGalleryStage({\n file,\n getFileUrl,\n loadPreviewImageUrl,\n pageUrlCache,\n renderFilePreview,\n toolbarActions,\n urlCache,\n variant = "stage",\n}: {\n file: FileEntry\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n pageUrlCache?: Map<string, string>\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n /** Rendered in the viewer toolbar in the `"dialog"` variant. */\n toolbarActions?: React.ReactNode\n urlCache: Map<string, string>\n /** `"stage"` is toolbar-less in a bordered tile; `"dialog"` shows the full viewer chrome. */\n variant?: "dialog" | "stage"\n}) {\n const viewerKind = viewerKindForFile(file)\n // Only viewer-backed stages need a URL; thumbnail stages render from the\n // manifest\'s preview images, so selecting them never triggers a presign.\n const { isResolving, url } = useResolvedFileUrl(\n viewerKind ? file : null,\n getFileUrl,\n urlCache\n )\n const isDialog = variant === "dialog"\n const [isDark, setIsDark] = React.useState(false)\n const viewerFrameClassName = cn(\n "size-full",\n !isDialog && "overflow-hidden rounded-lg border"\n )\n\n if (viewerKind && isResolving) {\n return <Spinner className="size-6 text-muted-foreground" />\n }\n if (viewerKind === "image" && url) {\n return (\n // eslint-disable-next-line @next/next/no-img-element -- Image file previews render caller-provided URLs that may be object or presigned URLs.\n <img\n src={url}\n alt={file.name}\n className="max-h-full max-w-full rounded-lg object-contain"\n />\n )\n }\n if (viewerKind === "pdf" && url) {\n return (\n <div className={viewerFrameClassName}>\n <React.Suspense fallback={<FileSystemViewerLoading />}>\n <LazyPDFViewer\n src={url}\n className={cn(\n "h-full",\n isDialog && "min-h-0 overflow-hidden rounded-2xl"\n )}\n fileName={file.name}\n showToolbar={isDialog}\n showUpload={false}\n toolbarActions={toolbarActions}\n />\n </React.Suspense>\n </div>\n )\n }\n if (viewerKind === "docx" && url) {\n return (\n <div className={viewerFrameClassName}>\n <React.Suspense fallback={<FileSystemViewerLoading />}>\n <LazyDocxViewerPreview\n src={url}\n fileName={file.name}\n isDark={isDark}\n className={cn(\n "h-full min-h-0",\n isDialog && "overflow-hidden rounded-2xl"\n )}\n onIsDarkChange={setIsDark}\n showToolbar={isDialog}\n showUpload={false}\n toolbarActions={toolbarActions}\n />\n </React.Suspense>\n </div>\n )\n }\n if (viewerKind === "xlsx" && url) {\n return (\n <div className={viewerFrameClassName}>\n <React.Suspense fallback={<FileSystemViewerLoading />}>\n <LazyXlsxViewerPreview\n src={url}\n fileName={file.name}\n isDark={isDark}\n className={cn(\n "h-full min-h-0",\n isDialog && "overflow-hidden rounded-2xl"\n )}\n onIsDarkChange={setIsDark}\n showToolbar={isDialog}\n showUpload={false}\n toolbarActions={toolbarActions}\n />\n </React.Suspense>\n </div>\n )\n }\n return (\n <FileVisual\n file={file}\n className="w-56 max-w-full"\n loadPreviewImageUrl={loadPreviewImageUrl}\n pageable\n pageUrlCache={pageUrlCache}\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )\n}\n\nfunction FileSystemGalleryView(props: FileSystemViewProps) {\n const {\n attachedStagePaths,\n entries,\n index,\n onOpen,\n onSelect,\n poolStagePath,\n registerStageHost,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n } = props\n const stripRefs = React.useRef(new Map<string, HTMLButtonElement>())\n const stripViewportRef = React.useRef<HTMLDivElement | null>(null)\n const typeAhead = useEntryTypeAhead()\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 // While arrow keys are scrubbing the strip, the center pane shows a\n // spinner; a file is only admitted to the preview pool (mounting its\n // viewer and resolving its URL) once the selection settles so each\n // keystroke stays cheap.\n const settledPath = useSettledValue(activeEntry?.path ?? null, 200)\n\n React.useEffect(() => {\n if (settledPath) poolStagePath(settledPath)\n }, [poolStagePath, settledPath])\n\n // Hosts for the root-owned preview pool: one positioned wrapper per\n // pooled path; the root reparents each live preview into its wrapper.\n // Stable callbacks per path keep React from re-running the host refs on\n // unrelated renders.\n const stageHostRefs = React.useMemo(\n () =>\n new Map(\n attachedStagePaths.map(\n (path) =>\n [\n path,\n (element: HTMLElement | null) => registerStageHost(path, element),\n ] as const\n )\n ),\n [attachedStagePaths, registerStageHost]\n )\n\n const activeFileSize = activeFile ? formatByteSize(activeFile.size) : null\n\n const handleKeyDown = (event: React.KeyboardEvent) => {\n if (entries.length === 0) return\n\n const currentIndex = activeEntry\n ? entries.findIndex((entry) => entry.path === activeEntry.path)\n : -1\n\n if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") {\n const match = typeAhead(event, entries, currentIndex)\n\n if (match) {\n onSelect(match)\n // The matched tile may be outside the strip\'s virtual window; the\n // active-tile effect scrolls it in, and focus follows once mounted.\n requestAnimationFrame(() => stripRefs.current.get(match.path)?.focus())\n }\n return\n }\n\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 const { end: stripEnd, start: stripStart } = useVirtualWindow({\n count: entries.length,\n horizontal: true,\n itemStride: GALLERY_TILE_STRIDE,\n leadingPx: GALLERY_STRIP_PADDING,\n overscan: 8,\n viewportRef: stripViewportRef,\n })\n\n // Keep the active tile mounted and visible while scrubbing or when the\n // selection arrives from another view.\n const activePath = activeEntry?.path ?? null\n\n React.useLayoutEffect(() => {\n if (!activePath) return\n\n scrollIndexIntoView({\n horizontal: true,\n index: entries.findIndex((entry) => entry.path === activePath),\n itemSize: GALLERY_TILE_SIZE,\n itemStride: GALLERY_TILE_STRIDE,\n leadingPx: GALLERY_STRIP_PADDING,\n viewport: stripViewportRef.current,\n })\n }, [activePath, entries])\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 viewportRef={stripViewportRef}\n viewportClassName="p-2"\n >\n <div\n className="relative h-14 min-w-full"\n style={{\n width: entries.length\n ? entries.length * GALLERY_TILE_STRIDE - GALLERY_TILE_GAP\n : undefined,\n }}\n >\n <div\n role="listbox"\n aria-label="Files"\n className="absolute inset-y-0 flex items-center gap-1.5"\n style={{ left: stripStart * GALLERY_TILE_STRIDE }}\n >\n {entries.slice(stripStart, stripEnd).map((entry) => {\n const isActive =\n 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 </div>\n </ScrollArea>\n <div className="flex min-h-0 flex-1">\n <div className="relative flex min-h-0 min-w-0 flex-1 items-center justify-center p-3">\n {activeEntry?.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-40 max-h-full w-auto drop-shadow-md" />\n ) : activeFile && !attachedStagePaths.includes(activeFile.path) ? (\n <Spinner className="size-6 text-muted-foreground" />\n ) : null}\n {/* Inactive hosts hide via `visibility` + `opacity`, never\n `display`: the document viewers size pages off ResizeObserver\n measurements, and display:none would collapse them to zero\n width — every reveal would re-lay-out and re-rasterize behind\n a blank pane. Stacking absolutely keeps each hidden stage at\n its real size so revealing one is pure paint. `opacity-0`\n matters: descendants can override an inherited\n visibility:hidden with their own visibility:visible (the\n spreadsheet grid\'s cell-selection overlay does), but nothing\n can opt out of an ancestor\'s zero opacity. `inert` keeps the\n hidden viewer\'s focusables out of reach. */}\n {attachedStagePaths.map((path) => {\n const isActiveStage = path === activeFile?.path\n\n return (\n <div\n key={path}\n ref={stageHostRefs.get(path)}\n inert={!isActiveStage || undefined}\n className={cn(\n "absolute inset-0 flex items-center justify-center p-3",\n !isActiveStage && "invisible opacity-0"\n )}\n />\n )\n })}\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/layout-blocks-docs.tsx b/apps/v4/components/layout-blocks-docs.tsxindex d52f557..33a3809 100644--- a/apps/v4/components/layout-blocks-docs.tsx+++ b/apps/v4/components/layout-blocks-docs.tsx@@ -8294,6 +8294,7 @@ function OcrBlocksPanel({},[blocks])+ // eslint-disable-next-line react-hooks/incompatible-library -- TanStack Virtual returns imperative helpers used by the OCR block list.const virtualizer = useVirtualizer({count: blocks.length,estimateSize: estimateBlockSize,diff --git a/apps/v4/components/pdf-viewer-source-code.tsx b/apps/v4/components/pdf-viewer-source-code.tsxindex b6be7a8..d3c6eb1 100644--- a/apps/v4/components/pdf-viewer-source-code.tsx+++ b/apps/v4/components/pdf-viewer-source-code.tsx@@ -5,7 +5,7 @@ import { DocsSourceCodeBlock } from "@/components/docs-code-block"// Generated from components/ui/pdf-viewer.tsx - keep in sync when the// component changes.export const pdfViewerSourceCode =- '"use client"\n\nimport * as React from "react"\nimport { createPluginRegistration, refreshPages } from "@embedpdf/core"\nimport { EmbedPDF, useRegistry } from "@embedpdf/core/react"\nimport type {\n PdfDocumentObject,\n PdfEngine,\n Rect,\n Rotation,\n} from "@embedpdf/models"\nimport {\n DocumentManagerPluginPackage,\n useActiveDocument,\n useDocumentManagerCapability,\n} from "@embedpdf/plugin-document-manager/react"\nimport {\n GlobalPointerProvider,\n InteractionManagerPluginPackage,\n PagePointerProvider,\n} from "@embedpdf/plugin-interaction-manager/react"\nimport { RenderLayer, RenderPluginPackage } from "@embedpdf/plugin-render/react"\nimport { Rotate, RotatePluginPackage } from "@embedpdf/plugin-rotate/react"\nimport {\n ScrollPluginPackage,\n ScrollStrategy,\n useScroll,\n useScrollPlugin,\n type PageLayout,\n type ScrollerLayout,\n type VirtualItem,\n} from "@embedpdf/plugin-scroll/react"\nimport {\n SearchLayer,\n SearchPluginPackage,\n useSearch,\n} from "@embedpdf/plugin-search/react"\nimport {\n CopyToClipboard,\n SelectionPluginPackage,\n useSelectionCapability,\n useSelectionPlugin,\n} from "@embedpdf/plugin-selection/react"\nimport {\n ThumbImg,\n ThumbnailPluginPackage,\n useThumbnailCapability,\n useThumbnailPlugin,\n type ThumbMeta,\n type WindowState,\n} from "@embedpdf/plugin-thumbnail/react"\nimport { TilingLayer, TilingPluginPackage } from "@embedpdf/plugin-tiling/react"\nimport {\n useIsViewportGated,\n useViewportCapability,\n useViewportElement,\n useViewportRef,\n ViewportElementContext,\n ViewportPluginPackage,\n} from "@embedpdf/plugin-viewport/react"\nimport { useZoom, ZoomPluginPackage } from "@embedpdf/plugin-zoom/react"\nimport {\n ArrowLeft01Icon,\n ArrowRight01Icon,\n Download01Icon,\n MinusSignCircleIcon,\n MoreHorizontalIcon,\n PlusSignCircleIcon,\n RotateClockwiseIcon,\n Search01Icon,\n SidebarLeftIcon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { flushSync } from "react-dom"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DocumentViewerSidebarSkeleton,\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/ui/document-viewer-sidebar"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { Input } from "@/components/ui/input"\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from "@/components/ui/popover"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport { loadSharedPdfEngine } from "@/components/pdf-thumbnail-utils"\n\nexport type PDFViewerPageOverlayProps = {\n pageNumber: number\n pageWidth: number\n pageHeight: number\n scale: number\n rotation: number\n}\n\nexport type PDFViewerHandle = {\n scrollToPage: (pageNumber: number, options?: ScrollIntoViewOptions) => void\n scrollToPageArea: (\n pageNumber: number,\n area: { top: number; left?: number; width?: number; height?: number },\n options?: ScrollToOptions\n ) => void\n getViewportElement: () => HTMLDivElement | null\n}\n\nexport type PDFViewerProps = {\n className?: string\n defaultZoom?: number\n fileName?: string\n showDownload?: boolean\n showToolbar?: boolean\n showRotateControls?: boolean\n showUpload?: boolean\n src?: string\n toolbarActions?: React.ReactNode\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onActivePageChange?: (pageNumber: number) => void\n onDocumentLoadSuccess?: (numPages: number) => void\n onPdfUpload?: (file: File) => void\n onPagePointerDown?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerMove?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerUp?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerCancel?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n}\n\nconst DEFAULT_ZOOM = 1\nconst ZOOM_OPTIONS = [0.1, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2]\nconst PAGE_GAP = 24\nconst THUMBNAIL_PAGE_WIDTH = 92\nconst THUMBNAIL_IMAGE_PADDING = 8\nconst THUMBNAIL_WIDTH = THUMBNAIL_PAGE_WIDTH + THUMBNAIL_IMAGE_PADDING * 2\nconst THUMBNAIL_LABEL_HEIGHT = 24\nconst THUMBNAIL_GAP = 12\nconst THUMBNAIL_PANE_PADDING_Y = 16\nconst THUMBNAIL_SIDEBAR_WIDTH_CLASS = "w-40"\nconst THUMBNAIL_SIDEBAR_CLOSED_CLASS = "-ml-40"\nconst PAGE_BASE_RENDER_MAX_SCALE = 1\nconst PAGE_BASE_RENDER_DPR = 1\nconst PDF_SEARCH_DEBOUNCE_MS = 300\nconst TEXT_SELECTION_BACKGROUND = "rgba(59, 130, 246, 0.14)"\nconst THUMBNAIL_FOCUS_RING_CLASS =\n "group-focus-visible/pdf-thumbnail-sidebar:ring-2 group-focus-visible/pdf-thumbnail-sidebar:ring-ring group-focus-visible/pdf-thumbnail-sidebar:ring-offset-1 group-focus-visible/pdf-thumbnail-sidebar:ring-offset-background"\n\ntype PageRotationDeltas = Map<number, Rotation>\ntype ThumbnailSelectionMode = "replace" | "toggle" | "range"\n\nfunction getPageIndexRange(from: number, to: number): Set<number> {\n const start = Math.min(from, to)\n const end = Math.max(from, to)\n const range = new Set<number>()\n\n for (let pageIndex = start; pageIndex <= end; pageIndex += 1) {\n range.add(pageIndex)\n }\n\n return range\n}\n\nfunction arePageIndexSetsEqual(left: Set<number>, right: Set<number>) {\n if (left.size !== right.size) return false\n\n for (const value of left) {\n if (!right.has(value)) return false\n }\n\n return true\n}\n\nfunction normalizeRotation(rotation: number): Rotation {\n return (((rotation % 4) + 4) % 4) as Rotation\n}\n\nfunction useSharedPdfEngine() {\n const [engine, setEngine] = React.useState<PdfEngine | null>(null)\n const [error, setError] = React.useState<Error | null>(null)\n\n React.useEffect(() => {\n let cancelled = false\n\n loadSharedPdfEngine().then(\n (loadedEngine) => {\n if (!cancelled) setEngine(loadedEngine)\n },\n (loadError: Error) => {\n if (!cancelled) setError(loadError)\n }\n )\n\n return () => {\n cancelled = true\n }\n }, [])\n\n return { engine, error }\n}\n\nfunction rotationToDegrees(rotation: Rotation) {\n return (rotation as number) * 90\n}\n\nfunction normalizeDegrees(rotation: number) {\n return ((rotation % 360) + 360) % 360\n}\n\nfunction ensurePdfExtension(fileName: string) {\n return fileName.toLowerCase().endsWith(".pdf") ? fileName : `${fileName}.pdf`\n}\n\nfunction getPdfDownloadFileName(fileName: string | undefined, src: string) {\n if (fileName?.trim()) return ensurePdfExtension(fileName.trim())\n\n const pathname = src.split(/[?#]/)[0] ?? ""\n const rawName = pathname.split("/").pop() || "document.pdf"\n\n try {\n return ensurePdfExtension(decodeURIComponent(rawName))\n } catch {\n return ensurePdfExtension(rawName)\n }\n}\n\nfunction getRotatedPdfDownloadFileName(fileName: string) {\n return fileName.replace(/\\.pdf$/i, "-rotated.pdf")\n}\n\nfunction downloadBlob(blob: Blob, fileName: string) {\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n\n anchor.href = url\n anchor.download = fileName\n anchor.rel = "noopener"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nasync function downloadPdfWithPageRotations({\n fileName,\n pageRotationDeltas,\n src,\n}: {\n fileName: string\n pageRotationDeltas: PageRotationDeltas\n src: string\n}) {\n const response = await fetch(src)\n\n if (!response.ok) {\n throw new Error(`Failed to download PDF (${response.status})`)\n }\n\n if (pageRotationDeltas.size === 0) {\n downloadBlob(await response.blob(), fileName)\n return\n }\n\n const [{ PDFDocument, degrees }, pdfBytes] = await Promise.all([\n import("pdf-lib"),\n response.arrayBuffer(),\n ])\n const pdfDocument = await PDFDocument.load(pdfBytes)\n\n pdfDocument.getPages().forEach((page, pageIndex) => {\n const rotationDelta = pageRotationDeltas.get(pageIndex)\n\n if (!rotationDelta) return\n\n page.setRotation(\n degrees(\n normalizeDegrees(\n page.getRotation().angle + rotationToDegrees(rotationDelta)\n )\n )\n )\n })\n\n const nextPdfBytes = await pdfDocument.save()\n const nextPdfBuffer = new ArrayBuffer(nextPdfBytes.byteLength)\n new Uint8Array(nextPdfBuffer).set(nextPdfBytes)\n\n downloadBlob(\n new Blob([nextPdfBuffer], { type: "application/pdf" }),\n getRotatedPdfDownloadFileName(fileName)\n )\n}\n\nfunction getThumbnailMetaForPage({\n page,\n pageIndex,\n rotation,\n width,\n imagePadding,\n labelHeight,\n top,\n}: {\n page: PdfDocumentObject["pages"][number]\n pageIndex: number\n rotation: Rotation\n width: number\n imagePadding: number\n labelHeight: number\n top: number\n}): ThumbMeta {\n const innerWidth = Math.max(1, width - imagePadding * 2)\n const pageWidth = rotation % 2 === 1 ? page.size.height : page.size.width\n const pageHeight = rotation % 2 === 1 ? page.size.width : page.size.height\n const imageHeight = Math.round(innerWidth * (pageHeight / pageWidth))\n const wrapperHeight = imagePadding + imageHeight + imagePadding + labelHeight\n\n return {\n pageIndex,\n width: innerWidth,\n height: imageHeight,\n wrapperHeight,\n top,\n labelHeight,\n padding: imagePadding,\n }\n}\n\nfunction buildThumbnailLayout({\n basePageRotations,\n pageRotationDeltas,\n pdfDocument,\n width,\n gap,\n imagePadding,\n labelHeight,\n paddingY,\n}: {\n basePageRotations: Rotation[]\n pageRotationDeltas: PageRotationDeltas\n pdfDocument: PdfDocumentObject | null\n width: number\n gap: number\n imagePadding: number\n labelHeight: number\n paddingY: number\n}) {\n if (!pdfDocument) return null\n\n let top = paddingY\n const items = pdfDocument.pages.map((page, pageIndex) => {\n const basePageRotation =\n basePageRotations[pageIndex] ?? normalizeRotation(page.rotation)\n const pageRotation = normalizeRotation(\n basePageRotation + (pageRotationDeltas.get(pageIndex) ?? 0)\n )\n const meta = getThumbnailMetaForPage({\n page,\n pageIndex,\n rotation: pageRotation,\n width,\n imagePadding,\n labelHeight,\n top,\n })\n\n top += meta.wrapperHeight + gap\n return meta\n })\n\n return {\n items,\n totalHeight: items.length ? top - gap + paddingY : paddingY * 2,\n }\n}\n\nfunction getVisibleThumbnailItems({\n buffer,\n clientHeight,\n items,\n scrollTop,\n}: {\n buffer: number\n clientHeight: number\n items: ThumbMeta[]\n scrollTop: number\n}) {\n if (items.length === 0) return []\n if (clientHeight <= 0)\n return items.slice(0, Math.min(items.length, buffer * 2))\n\n const viewportBottom = scrollTop + clientHeight\n let start = items.findIndex(\n (item) => item.top + item.wrapperHeight >= scrollTop\n )\n\n if (start === -1) start = items.length - 1\n\n let end = start\n while (end < items.length && items[end].top <= viewportBottom) {\n end += 1\n }\n\n return items.slice(\n Math.max(0, start - buffer),\n Math.min(items.length, end + buffer)\n )\n}\n\nfunction PDFViewerLoadingSkeleton({\n sidebarOpen,\n sidebarInline,\n}: {\n sidebarOpen: boolean\n sidebarInline: boolean\n}) {\n return (\n <div className="absolute inset-0 z-20 flex bg-muted/30">\n {sidebarOpen ? (\n <DocumentViewerSidebarSkeleton\n className={THUMBNAIL_SIDEBAR_WIDTH_CLASS}\n inline={sidebarInline}\n />\n ) : null}\n <div className="grid min-w-0 flex-1 place-items-center">\n <Spinner className="size-4" />\n </div>\n </div>\n )\n}\n\n// Rendered while the engine or document is not ready: same frame as the\n// full viewer, with only the upload control usable.\nfunction PDFViewerFallbackShell({\n className,\n showToolbar,\n showUpload,\n sidebarOpen,\n state,\n onUploadFile,\n}: {\n className?: string\n showToolbar: boolean\n showUpload: boolean\n sidebarOpen: boolean\n state: "loading" | "error" | "empty"\n onUploadFile?: (file: File) => void\n}) {\n return (\n <div\n data-slot="pdf-viewer"\n className={cn(\n "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n {showToolbar ? (\n <div className="flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2">\n {showUpload && onUploadFile ? (\n <PDFViewerFileActionsMenu onUploadFile={onUploadFile} showUpload />\n ) : null}\n </div>\n ) : null}\n <div className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30">\n {state === "loading" ? (\n <PDFViewerLoadingSkeleton sidebarInline sidebarOpen={sidebarOpen} />\n ) : null}\n {state === "error" ? (\n <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-sm text-muted-foreground">\n Unable to load the PDF preview.\n </div>\n ) : null}\n {state === "empty" ? (\n <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-center text-sm text-muted-foreground">\n <div className="max-w-sm space-y-3">\n <div className="font-medium text-foreground">\n Upload a PDF to preview\n </div>\n <div>\n Pass a PDF URL with the <code>src</code> prop or use the upload\n control.\n </div>\n </div>\n </div>\n ) : null}\n </div>\n </div>\n )\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction PDFViewerFileActionsMenu({\n downloadDisabled,\n isPreparingDownload = false,\n onDownload,\n onUploadFile,\n showDownload = false,\n showUpload = false,\n}: {\n downloadDisabled?: boolean\n isPreparingDownload?: boolean\n onDownload?: () => void\n onUploadFile?: (file: File) => void\n showDownload?: boolean\n showUpload?: boolean\n}) {\n const inputRef = React.useRef<HTMLInputElement>(null)\n\n if (!showDownload && !showUpload) return null\n\n return (\n <>\n {showUpload && onUploadFile ? (\n <input\n ref={inputRef}\n type="file"\n accept="application/pdf,.pdf"\n className="sr-only"\n tabIndex={-1}\n onChange={(event) => {\n const nextFile = event.target.files?.[0]\n\n if (nextFile) {\n onUploadFile(nextFile)\n event.currentTarget.value = ""\n }\n }}\n />\n ) : null}\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Open PDF actions"\n >\n <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="w-40">\n {showDownload && onDownload ? (\n <DropdownMenuItem disabled={downloadDisabled} onClick={onDownload}>\n {isPreparingDownload ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n )}\n Download\n </DropdownMenuItem>\n ) : null}\n {showUpload && onUploadFile ? (\n <DropdownMenuItem onClick={() => inputRef.current?.click()}>\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload\n </DropdownMenuItem>\n ) : null}\n </DropdownMenuContent>\n </DropdownMenu>\n </>\n )\n}\n\nfunction PDFViewerPageNumberControl({\n activePage,\n controlsDisabled,\n numPages,\n onPageChange,\n}: {\n activePage: number\n controlsDisabled: boolean\n numPages: number\n onPageChange: (pageNumber: number) => void\n}) {\n const inputRef = React.useRef<HTMLInputElement>(null)\n const displayPage = numPages ? activePage : 1\n const [isEditing, setIsEditing] = React.useState(false)\n const [draftPage, setDraftPage] = React.useState(() => String(displayPage))\n\n React.useEffect(() => {\n if (!isEditing) {\n setDraftPage(String(displayPage))\n }\n }, [displayPage, isEditing])\n\n React.useEffect(() => {\n if (!isEditing) return\n\n inputRef.current?.focus()\n inputRef.current?.setSelectionRange(draftPage.length, draftPage.length)\n }, [isEditing])\n\n const applyPageDraft = React.useCallback(\n (value: string) => {\n const trimmedValue = value.trim()\n\n if (!trimmedValue) return\n\n const parsedPage = Number(trimmedValue)\n\n if (!Number.isInteger(parsedPage)) return\n\n onPageChange(Math.min(Math.max(parsedPage, 1), Math.max(numPages, 1)))\n },\n [numPages, onPageChange]\n )\n\n return (\n <div className="flex items-center text-sm whitespace-nowrap text-primary">\n <span>Page</span>\n {isEditing ? (\n <Input\n ref={inputRef}\n aria-label="Page number"\n inputMode="numeric"\n pattern="[0-9]*"\n size="sm"\n value={draftPage}\n className="mx-1 w-14 min-w-14 rounded-md [&_[data-slot=input]]:text-center"\n onBlur={() => setIsEditing(false)}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) => {\n const nextValue = event.target.value\n\n setDraftPage(nextValue)\n applyPageDraft(nextValue)\n }}\n onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key === "Enter" || event.key === "Escape") {\n event.currentTarget.blur()\n }\n }}\n />\n ) : (\n <Button\n type="button"\n variant="ghost"\n size="sm"\n className="font-normal"\n aria-label={`Current page ${displayPage}. Edit page number`}\n disabled={controlsDisabled || !numPages}\n onClick={() => {\n setDraftPage(String(displayPage))\n setIsEditing(true)\n }}\n >\n {displayPage}\n </Button>\n )}\n <span>of {numPages || "–"}</span>\n </div>\n )\n}\n\nfunction PDFViewerSearchControl({\n documentId,\n controlsDisabled,\n}: {\n documentId: string\n controlsDisabled: boolean\n}) {\n const { state, provides } = useSearch(documentId)\n const { provides: scroll } = useScroll(documentId)\n const [searchDraft, setSearchDraft] = React.useState("")\n const [searchQuery, setSearchQuery] = React.useState("")\n const [isSearching, setIsSearching] = React.useState(false)\n const providesRef = React.useRef(provides)\n const scrollRef = React.useRef(scroll)\n const searchRequestIdRef = React.useRef(0)\n const hasActiveQuery = Boolean(searchQuery.trim())\n const resultLabel = isSearching\n ? "Searching"\n : !hasActiveQuery\n ? "No search"\n : state.total\n ? `${state.activeResultIndex + 1} / ${state.total}`\n : "No results"\n\n const scrollToResult = React.useCallback(\n (index: number) => {\n const result = state.results[index]\n\n if (!result || !scroll) return\n\n const firstRect = result.rects[0]\n\n scroll.scrollToPage({\n pageNumber: result.pageIndex + 1,\n ...(firstRect\n ? {\n pageCoordinates: {\n x: firstRect.origin.x,\n y: firstRect.origin.y,\n },\n alignY: 30,\n }\n : {}),\n behavior: "auto",\n })\n },\n [scroll, state.results]\n )\n\n React.useEffect(() => {\n providesRef.current = provides\n scrollRef.current = scroll\n }, [provides, scroll])\n\n const runSearch = React.useCallback((rawQuery: string) => {\n const query = rawQuery.trim()\n const requestId = searchRequestIdRef.current + 1\n searchRequestIdRef.current = requestId\n setSearchQuery(query)\n\n const searchProvider = providesRef.current\n const scrollProvider = scrollRef.current\n\n if (!searchProvider) {\n setIsSearching(false)\n return\n }\n\n if (!query) {\n searchProvider.stopSearch()\n setIsSearching(false)\n return\n }\n\n setIsSearching(true)\n searchProvider.startSearch()\n searchProvider.searchAllPages(query).wait(\n (result) => {\n if (searchRequestIdRef.current !== requestId) return\n\n const firstResult = result.results[0]\n\n if (firstResult && scrollProvider) {\n searchProvider.goToResult(0)\n const firstRect = firstResult.rects[0]\n\n scrollProvider.scrollToPage({\n pageNumber: firstResult.pageIndex + 1,\n ...(firstRect\n ? {\n pageCoordinates: {\n x: firstRect.origin.x,\n y: firstRect.origin.y,\n },\n alignY: 30,\n }\n : {}),\n behavior: "auto",\n })\n }\n setIsSearching(false)\n },\n () => {\n if (searchRequestIdRef.current !== requestId) return\n setIsSearching(false)\n }\n )\n }, [])\n\n React.useEffect(() => {\n const trimmedDraft = searchDraft.trim()\n\n if (!trimmedDraft) {\n runSearch("")\n return\n }\n\n setIsSearching(true)\n const timeoutId = window.setTimeout(() => {\n runSearch(searchDraft)\n }, PDF_SEARCH_DEBOUNCE_MS)\n\n return () => window.clearTimeout(timeoutId)\n }, [runSearch, searchDraft])\n\n const clearSearch = React.useCallback(() => {\n searchRequestIdRef.current += 1\n setSearchDraft("")\n setSearchQuery("")\n setIsSearching(false)\n provides?.stopSearch()\n }, [provides])\n\n const navigate = React.useCallback(\n (direction: 1 | -1) => {\n if (!provides || state.total === 0) return\n\n const index =\n direction === 1 ? provides.nextResult() : provides.previousResult()\n\n scrollToResult(index)\n },\n [provides, scrollToResult, state.total]\n )\n\n return (\n <Popover>\n <ToolbarTooltip label="Search text">\n <PopoverTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search text"\n disabled={controlsDisabled}\n >\n <HugeiconsIcon icon={Search01Icon} className="size-4" />\n </Button>\n </PopoverTrigger>\n </ToolbarTooltip>\n <PopoverContent align="end" className="w-72">\n <div className="space-y-3">\n <Input\n placeholder="Search text"\n value={searchDraft}\n onChange={(event) => setSearchDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key !== "Enter") return\n\n event.preventDefault()\n if (event.shiftKey && state.total) {\n navigate(-1)\n } else if (state.total) {\n navigate(1)\n } else if (searchDraft.trim()) {\n runSearch(searchDraft)\n }\n }}\n />\n <div className="flex items-center justify-between gap-2">\n <div className="min-w-0 text-xs text-muted-foreground">\n <div className="truncate">\n {state.total ? (\n <>\n <span className="text-primary">\n {state.activeResultIndex + 1}\n </span>\n {` / ${state.total}`}\n </>\n ) : (\n resultLabel\n )}\n </div>\n </div>\n <div className="flex shrink-0 items-center gap-1">\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Previous result"\n disabled={isSearching || state.total === 0}\n onClick={() => navigate(-1)}\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4" />\n </Button>\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Next result"\n disabled={isSearching || state.total === 0}\n onClick={() => navigate(1)}\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-4" />\n </Button>\n </div>\n </div>\n <div className="flex justify-end">\n <Button\n type="button"\n variant="outline"\n size="sm"\n onClick={clearSearch}\n >\n Clear\n </Button>\n </div>\n </div>\n </PopoverContent>\n </Popover>\n )\n}\n\nfunction PDFViewerThumbnails({\n basePageRotations,\n documentId,\n activePage,\n pageCount,\n pageRotationDeltas,\n pdfDocument,\n selectedPageIndexes,\n onSelectPage,\n}: {\n basePageRotations: Rotation[]\n documentId: string\n activePage: number\n pageCount: number\n pageRotationDeltas: PageRotationDeltas\n pdfDocument: PdfDocumentObject | null\n selectedPageIndexes: Set<number>\n onSelectPage: (pageNumber: number, mode: ThumbnailSelectionMode) => void\n}) {\n const thumbnailListboxId = React.useId()\n const activeDescendantId =\n activePage > 0 ? `${thumbnailListboxId}-page-${activePage}` : undefined\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (pageCount < 1) return\n\n const currentPage = activePage > 0 ? activePage : 1\n let nextPage: number | null = null\n\n if (event.key === "ArrowDown") {\n nextPage = Math.min(pageCount, currentPage + 1)\n } else if (event.key === "ArrowUp") {\n nextPage = Math.max(1, currentPage - 1)\n } else if (event.key === "Home") {\n nextPage = 1\n } else if (event.key === "End") {\n nextPage = pageCount\n } else if (event.key === " ") {\n event.preventDefault()\n onSelectPage(currentPage, "toggle")\n return\n }\n\n if (nextPage === null) return\n\n event.preventDefault()\n onSelectPage(nextPage, event.shiftKey ? "range" : "replace")\n },\n [activePage, onSelectPage, pageCount]\n )\n\n return (\n <PDFViewerThumbnailScrollArea\n activeDescendantId={activeDescendantId}\n basePageRotations={basePageRotations}\n documentId={documentId}\n onKeyDown={handleKeyDown}\n pageRotationDeltas={pageRotationDeltas}\n pdfDocument={pdfDocument}\n >\n {(meta: ThumbMeta) => {\n const pageNumber = meta.pageIndex + 1\n const isActive = pageNumber === activePage\n const isSelected = selectedPageIndexes.has(meta.pageIndex)\n const imagePadding = meta.padding ?? 0\n const pageRotationDelta = pageRotationDeltas.get(meta.pageIndex) ?? 0\n const thumbnailImageStyle: React.CSSProperties =\n pageRotationDelta % 2 === 1\n ? {\n height: meta.width,\n transform: `rotate(${rotationToDegrees(pageRotationDelta)}deg)`,\n width: meta.height,\n }\n : {\n height: meta.height,\n transform:\n pageRotationDelta === 0\n ? undefined\n : `rotate(${rotationToDegrees(pageRotationDelta)}deg)`,\n width: meta.width,\n }\n\n return (\n <div\n key={meta.pageIndex}\n data-pdf-viewer-thumbnail={pageNumber}\n className={cn(\n "absolute right-0 left-0 flex justify-center",\n isActive && "z-10"\n )}\n style={{ top: meta.top, height: meta.wrapperHeight }}\n >\n <div\n id={`${thumbnailListboxId}-page-${pageNumber}`}\n role="option"\n data-pdf-viewer-thumbnail-option={pageNumber}\n aria-current={isActive ? "page" : undefined}\n aria-label={`Page ${pageNumber}`}\n aria-posinset={pageNumber}\n aria-selected={isSelected}\n aria-setsize={pageCount}\n data-selected={isSelected ? "" : undefined}\n className={cn(\n "flex h-full w-full cursor-default flex-col items-center justify-between rounded-md px-2 py-0 text-xs transition-shadow outline-none select-none hover:bg-sidebar-accent",\n isActive || isSelected\n ? "bg-sidebar-accent text-foreground"\n : "text-muted-foreground",\n isActive && THUMBNAIL_FOCUS_RING_CLASS\n )}\n onClick={(event) => {\n const mode = event.shiftKey\n ? "range"\n : event.metaKey || event.ctrlKey\n ? "toggle"\n : "replace"\n\n onSelectPage(pageNumber, mode)\n }}\n >\n <span\n className="mt-0 flex items-center justify-center overflow-hidden rounded-md bg-transparent"\n style={{\n width: meta.width + imagePadding * 2,\n height: meta.height + imagePadding * 2,\n padding: imagePadding,\n }}\n >\n <ThumbImg\n documentId={documentId}\n meta={meta}\n className="block rounded-sm object-contain"\n style={thumbnailImageStyle}\n />\n </span>\n <span\n className="flex items-center justify-center tabular-nums"\n style={{ height: meta.labelHeight }}\n >\n <span className="flex min-w-5 items-center justify-center px-1.5 text-center leading-5">\n {pageNumber}\n </span>\n </span>\n </div>\n </div>\n )\n }}\n </PDFViewerThumbnailScrollArea>\n )\n}\n\nfunction PDFViewerThumbnailScrollArea({\n activeDescendantId,\n basePageRotations,\n children,\n documentId,\n onKeyDown,\n pageRotationDeltas,\n pdfDocument,\n}: {\n activeDescendantId?: string\n basePageRotations: Rotation[]\n children: (meta: ThumbMeta) => React.ReactNode\n documentId: string\n onKeyDown: React.KeyboardEventHandler<HTMLDivElement>\n pageRotationDeltas: PageRotationDeltas\n pdfDocument: PdfDocumentObject | null\n}) {\n const { plugin: thumbnailPlugin } = useThumbnailPlugin()\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [windowData, setWindowData] = React.useState<{\n docId: string | null\n window: WindowState | null\n }>({ docId: null, window: null })\n const [viewportMetrics, setViewportMetrics] = React.useState({\n clientHeight: 0,\n scrollTop: 0,\n })\n\n const windowState = windowData.docId === documentId ? windowData.window : null\n const paddingY = thumbnailPlugin?.cfg.paddingY ?? 0\n const thumbnailLayout = React.useMemo(\n () =>\n buildThumbnailLayout({\n basePageRotations,\n pageRotationDeltas,\n pdfDocument,\n width: thumbnailPlugin?.cfg.width ?? THUMBNAIL_WIDTH,\n gap: thumbnailPlugin?.cfg.gap ?? THUMBNAIL_GAP,\n imagePadding: thumbnailPlugin?.cfg.imagePadding ?? 0,\n labelHeight: thumbnailPlugin?.cfg.labelHeight ?? THUMBNAIL_LABEL_HEIGHT,\n paddingY,\n }),\n [\n basePageRotations,\n pageRotationDeltas,\n pdfDocument,\n paddingY,\n thumbnailPlugin,\n ]\n )\n const effectiveWindowState = React.useMemo(() => {\n if (!thumbnailLayout) return windowState\n\n const items = getVisibleThumbnailItems({\n buffer: thumbnailPlugin?.cfg.buffer ?? 3,\n clientHeight: viewportMetrics.clientHeight,\n items: thumbnailLayout.items,\n scrollTop: viewportMetrics.scrollTop,\n })\n\n return {\n start: items[0]?.pageIndex ?? -1,\n end: items.at(-1)?.pageIndex ?? -1,\n items,\n totalHeight: thumbnailLayout.totalHeight,\n }\n }, [thumbnailLayout, thumbnailPlugin, viewportMetrics, windowState])\n\n React.useEffect(() => {\n if (!thumbnailPlugin) return\n\n const scope = thumbnailPlugin.provides().forDocument(documentId)\n const initialWindow = scope.getWindow()\n\n if (initialWindow) {\n setWindowData({ docId: documentId, window: initialWindow })\n }\n\n const unsubscribe = scope.onWindow((nextWindow) => {\n setWindowData({ docId: documentId, window: nextWindow })\n })\n\n return () => {\n unsubscribe()\n setWindowData({ docId: null, window: null })\n }\n }, [documentId, thumbnailPlugin])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailPlugin) return\n\n const scope = thumbnailPlugin.provides().forDocument(documentId)\n const updateWindow = () => {\n setViewportMetrics({\n clientHeight: viewport.clientHeight,\n scrollTop: viewport.scrollTop,\n })\n scope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n }\n\n viewport.addEventListener("scroll", updateWindow)\n updateWindow()\n\n return () => viewport.removeEventListener("scroll", updateWindow)\n }, [documentId, thumbnailPlugin])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailPlugin) return\n\n const scope = thumbnailPlugin.provides().forDocument(documentId)\n const resizeObserver = new ResizeObserver(() => {\n setViewportMetrics({\n clientHeight: viewport.clientHeight,\n scrollTop: viewport.scrollTop,\n })\n scope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n })\n\n resizeObserver.observe(viewport)\n\n return () => resizeObserver.disconnect()\n }, [documentId, thumbnailPlugin])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailPlugin) return\n\n const scope = thumbnailPlugin.provides().forDocument(documentId)\n setViewportMetrics({\n clientHeight: viewport.clientHeight,\n scrollTop: viewport.scrollTop,\n })\n scope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n }, [documentId, thumbnailPlugin, windowState, thumbnailLayout])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailPlugin || !windowState) return\n\n const scope = thumbnailPlugin.provides().forDocument(documentId)\n\n return scope.onScrollTo(({ top, behavior }) => {\n viewport.scrollTo({ top, behavior })\n })\n }, [documentId, thumbnailPlugin, Boolean(windowState)])\n\n return (\n <ScrollArea\n className="h-full w-full"\n orientation="vertical"\n scrollFade\n viewportClassName="group/pdf-thumbnail-sidebar px-4 focus-visible:ring-0 focus-visible:ring-offset-0"\n viewportProps={{\n "aria-activedescendant": activeDescendantId,\n "aria-label": "PDF pages",\n "aria-multiselectable": true,\n onKeyDown,\n onMouseDown: (event) => {\n event.currentTarget.focus({ preventScroll: true })\n },\n role: "listbox",\n style: {\n paddingBottom: paddingY,\n paddingTop: paddingY,\n },\n tabIndex: 0,\n }}\n viewportRef={viewportRef}\n >\n <div\n className="relative"\n style={{ height: effectiveWindowState?.totalHeight ?? 0 }}\n >\n {effectiveWindowState?.items.map((meta) => children(meta))}\n </div>\n </ScrollArea>\n )\n}\n\nfunction PDFViewerScrollAreaViewport({\n children,\n className,\n documentId,\n}: {\n children: React.ReactNode\n className?: string\n documentId: string\n}) {\n const viewportRef = useViewportRef(documentId)\n const { provides: viewport } = useViewportCapability()\n const isGated = useIsViewportGated(documentId)\n const [viewportGap, setViewportGap] = React.useState(0)\n\n React.useEffect(() => {\n if (!viewport) return\n\n setViewportGap(viewport.getViewportGap())\n }, [viewport])\n\n return (\n <ViewportElementContext.Provider value={viewportRef}>\n <ScrollArea\n className={className}\n orientation="both"\n viewportClassName="relative select-none selection:bg-transparent selection:text-inherit"\n viewportProps={{\n style: {\n padding: viewportGap,\n },\n }}\n viewportRef={viewportRef}\n >\n {isGated ? null : children}\n </ScrollArea>\n </ViewportElementContext.Provider>\n )\n}\n\n// Captures the scrollable viewport element so the imperative handle can expose\n// it.\nfunction PDFViewerViewportBridge({\n viewportElementRef,\n}: {\n viewportElementRef: React.MutableRefObject<HTMLDivElement | null>\n}) {\n const elementRef = useViewportElement()\n\n React.useEffect(() => {\n viewportElementRef.current = elementRef?.current ?? null\n })\n\n return null\n}\n\nfunction PDFViewerTextSelectionLayer({\n documentId,\n pageIndex,\n scale,\n}: {\n documentId: string\n pageIndex: number\n scale: number\n}) {\n const { plugin: selectionPlugin } = useSelectionPlugin()\n const [rects, setRects] = React.useState<Rect[]>([])\n\n React.useEffect(() => {\n if (!selectionPlugin) return\n\n return selectionPlugin.registerSelectionOnPage({\n documentId,\n pageIndex,\n onRectsChange: ({ rects: nextRects }) => {\n setRects(nextRects)\n },\n })\n }, [documentId, pageIndex, selectionPlugin])\n\n if (!rects.length) return null\n\n return (\n <>\n {rects.map((rect, index) => (\n <div\n key={`${index}-${rect.origin.x}-${rect.origin.y}`}\n className="pointer-events-none absolute"\n style={{\n background: TEXT_SELECTION_BACKGROUND,\n height: rect.size.height * scale,\n left: rect.origin.x * scale,\n top: rect.origin.y * scale,\n width: rect.size.width * scale,\n }}\n />\n ))}\n </>\n )\n}\n\nfunction PDFViewerSelectionReleaseGuard({\n documentId,\n}: {\n documentId: string\n}) {\n const { plugin: selectionPlugin } = useSelectionPlugin()\n const { provides: selection } = useSelectionCapability()\n const lastSelectionModeIdRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n if (!selection) return\n\n return selection.forDocument(documentId).onBeginSelection(({ modeId }) => {\n lastSelectionModeIdRef.current = modeId\n })\n }, [documentId, selection])\n\n React.useEffect(() => {\n if (!selection) return\n\n let cleanupFrame = 0\n const finalizeIfStillSelecting = () => {\n window.cancelAnimationFrame(cleanupFrame)\n cleanupFrame = window.requestAnimationFrame(() => {\n const selectionState = selection.getState(documentId)\n\n if (!selectionState.selecting) return\n\n if (selectionState.selection && selectionPlugin) {\n const pluginWithEndSelection = selectionPlugin as unknown as {\n endSelection?: (documentId: string, modeId: string) => void\n }\n\n pluginWithEndSelection.endSelection?.(\n documentId,\n lastSelectionModeIdRef.current ?? "pointerMode"\n )\n return\n }\n\n if (!selectionState.selection) {\n selection.clear(documentId)\n }\n })\n }\n\n window.addEventListener("pointerup", finalizeIfStillSelecting)\n window.addEventListener("pointercancel", finalizeIfStillSelecting)\n window.addEventListener("blur", finalizeIfStillSelecting)\n\n return () => {\n window.cancelAnimationFrame(cleanupFrame)\n window.removeEventListener("pointerup", finalizeIfStillSelecting)\n window.removeEventListener("pointercancel", finalizeIfStillSelecting)\n window.removeEventListener("blur", finalizeIfStillSelecting)\n }\n }, [documentId, selection, selectionPlugin])\n\n return null\n}\n\nfunction isEditableCopyTarget(target: EventTarget | null) {\n if (!(target instanceof HTMLElement)) return false\n\n if (target.isContentEditable) return true\n\n return Boolean(target.closest("input, textarea, [contenteditable=\'true\']"))\n}\n\nfunction PDFViewerSelectionCopyShortcut({\n documentId,\n}: {\n documentId: string\n}) {\n const { provides: selection } = useSelectionCapability()\n\n React.useEffect(() => {\n if (!selection) return\n\n const copySelectedPdfText = (event: Event) => {\n if (isEditableCopyTarget(event.target)) return\n if (!selection.getState(documentId).selection) return\n\n event.preventDefault()\n selection.copyToClipboard(documentId)\n }\n\n const handleKeyDown = (event: KeyboardEvent) => {\n if (event.key.toLowerCase() !== "c") return\n if (!event.metaKey && !event.ctrlKey) return\n\n copySelectedPdfText(event)\n }\n\n document.addEventListener("copy", copySelectedPdfText)\n document.addEventListener("keydown", handleKeyDown)\n\n return () => {\n document.removeEventListener("copy", copySelectedPdfText)\n document.removeEventListener("keydown", handleKeyDown)\n }\n }, [documentId, selection])\n\n return null\n}\n\nfunction isQuarterTurn(rotation: Rotation) {\n return rotation % 2 === 1\n}\n\nfunction getRotatedDimensions({\n height,\n rotation,\n width,\n}: {\n height: number\n rotation: Rotation\n width: number\n}) {\n return isQuarterTurn(rotation)\n ? { height: width, width: height }\n : { height, width }\n}\n\nfunction getRotatedPageDimensions(page: PageLayout, rotation: Rotation) {\n return getRotatedDimensions({\n height: page.height,\n rotation,\n width: page.width,\n })\n}\n\nfunction applyPageRotationDeltasToScrollerLayout({\n basePageRotations,\n layout,\n pageRotationDeltas,\n}: {\n basePageRotations: Rotation[]\n layout: ScrollerLayout\n pageRotationDeltas: PageRotationDeltas\n}): ScrollerLayout {\n if (pageRotationDeltas.size === 0) return layout\n\n let maxWidth = 0\n let maxHeight = 0\n let offset = 0\n const pageGap = layout.pageGap\n let startSpacingAdjustment = 0\n const items: VirtualItem[] = layout.items.map((item, itemIndex) => {\n let pageOffset = 0\n let itemWidth = 0\n let itemHeight = 0\n const pageLayouts = item.pageLayouts.map((page) => {\n const basePageRotation =\n basePageRotations[page.pageIndex] ?? normalizeRotation(0)\n const pageRotation = normalizeRotation(\n basePageRotation + (pageRotationDeltas.get(page.pageIndex) ?? 0)\n )\n const rotatedSize = getRotatedPageDimensions(page, pageRotation)\n const oldScrollAxisSize =\n layout.strategy === ScrollStrategy.Horizontal\n ? page.rotatedWidth\n : page.rotatedHeight\n const newScrollAxisSize =\n layout.strategy === ScrollStrategy.Horizontal\n ? rotatedSize.width\n : rotatedSize.height\n\n if (\n layout.startSpacing === 0 &&\n itemIndex === 0 &&\n pageOffset === 0 &&\n newScrollAxisSize < oldScrollAxisSize\n ) {\n startSpacingAdjustment = Math.max(\n startSpacingAdjustment,\n (oldScrollAxisSize - newScrollAxisSize) / 2\n )\n }\n\n const nextPageLayout = {\n ...page,\n rotatedHeight: rotatedSize.height,\n rotatedWidth: rotatedSize.width,\n x: layout.strategy === ScrollStrategy.Horizontal ? 0 : pageOffset,\n y: layout.strategy === ScrollStrategy.Horizontal ? pageOffset : 0,\n }\n\n pageOffset +=\n (layout.strategy === ScrollStrategy.Horizontal\n ? rotatedSize.height\n : rotatedSize.width) + pageGap\n itemWidth =\n layout.strategy === ScrollStrategy.Horizontal\n ? Math.max(itemWidth, rotatedSize.width)\n : itemWidth + rotatedSize.width\n itemHeight =\n layout.strategy === ScrollStrategy.Horizontal\n ? itemHeight + rotatedSize.height\n : Math.max(itemHeight, rotatedSize.height)\n\n return nextPageLayout\n })\n\n if (pageLayouts.length > 1) {\n if (layout.strategy === ScrollStrategy.Horizontal) {\n itemHeight -= pageGap\n } else {\n itemWidth -= pageGap\n }\n }\n\n const nextItem = {\n ...item,\n height: itemHeight,\n offset,\n pageLayouts,\n width: itemWidth,\n x: layout.strategy === ScrollStrategy.Horizontal ? offset : item.x,\n y: layout.strategy === ScrollStrategy.Horizontal ? item.y : offset,\n }\n\n if (layout.strategy === ScrollStrategy.Horizontal) {\n offset += itemWidth + pageGap\n maxHeight = Math.max(maxHeight, itemHeight)\n } else {\n offset += itemHeight + pageGap\n maxWidth = Math.max(maxWidth, itemWidth)\n }\n\n return nextItem\n })\n\n if (items.length > 0) {\n offset -= pageGap\n }\n\n return {\n ...layout,\n endSpacing: layout.endSpacing,\n items,\n startSpacing: layout.startSpacing + startSpacingAdjustment,\n totalHeight:\n layout.strategy === ScrollStrategy.Horizontal\n ? maxHeight\n : layout.startSpacing +\n startSpacingAdjustment +\n offset +\n layout.endSpacing,\n totalWidth:\n layout.strategy === ScrollStrategy.Horizontal\n ? layout.startSpacing +\n startSpacingAdjustment +\n offset +\n layout.endSpacing\n : maxWidth,\n }\n}\n\nfunction PDFViewerScroller({\n documentId,\n pageRotationDeltas,\n basePageRotations,\n renderPage,\n}: {\n documentId: string\n pageRotationDeltas: PageRotationDeltas\n basePageRotations: Rotation[]\n renderPage: (props: PageLayout) => React.ReactNode\n}) {\n const { plugin: scrollPlugin } = useScrollPlugin()\n const [layoutData, setLayoutData] = React.useState<{\n docId: string | null\n layout: ScrollerLayout | null\n }>({ docId: null, layout: null })\n\n React.useEffect(() => {\n if (!scrollPlugin || !documentId) return\n\n const unsubscribe = scrollPlugin.onScrollerData(documentId, (layout) => {\n setLayoutData({ docId: documentId, layout })\n })\n\n return () => {\n unsubscribe()\n setLayoutData({ docId: null, layout: null })\n scrollPlugin.clearLayoutReady(documentId)\n }\n }, [documentId, scrollPlugin])\n\n const scrollerLayout = React.useMemo(() => {\n if (layoutData.docId !== documentId || !layoutData.layout) return null\n\n return applyPageRotationDeltasToScrollerLayout({\n basePageRotations,\n layout: layoutData.layout,\n pageRotationDeltas,\n })\n }, [basePageRotations, documentId, layoutData, pageRotationDeltas])\n\n React.useLayoutEffect(() => {\n if (!scrollPlugin || !documentId || !scrollerLayout) return\n scrollPlugin.setLayoutReady(documentId)\n }, [documentId, scrollPlugin, scrollerLayout])\n\n if (!scrollerLayout) return null\n\n return (\n <div\n style={{\n width: `${scrollerLayout.totalWidth}px`,\n height: `${scrollerLayout.totalHeight}px`,\n position: "relative",\n boxSizing: "border-box",\n margin: "0 auto",\n ...(scrollerLayout.strategy === ScrollStrategy.Horizontal && {\n display: "flex",\n flexDirection: "row",\n }),\n }}\n >\n <div\n style={\n scrollerLayout.strategy === ScrollStrategy.Horizontal\n ? {\n width: scrollerLayout.startSpacing,\n height: "100%",\n flexShrink: 0,\n }\n : {\n height: scrollerLayout.startSpacing,\n width: "100%",\n }\n }\n />\n <div\n style={{\n gap: scrollerLayout.pageGap,\n display: "flex",\n alignItems: "center",\n position: "relative",\n boxSizing: "border-box",\n ...(scrollerLayout.strategy === ScrollStrategy.Horizontal\n ? {\n flexDirection: "row",\n minHeight: "100%",\n }\n : {\n flexDirection: "column",\n minWidth: "fit-content",\n }),\n }}\n >\n {scrollerLayout.items.map((item) => (\n <div\n key={item.pageNumbers[0]}\n style={{\n display: "flex",\n justifyContent: "center",\n gap: scrollerLayout.pageGap,\n }}\n >\n {item.pageLayouts.map((layout) => (\n <div\n key={layout.pageNumber}\n style={{\n width: `${layout.rotatedWidth}px`,\n height: `${layout.rotatedHeight}px`,\n position: "relative",\n zIndex: layout.elevated ? 1 : undefined,\n }}\n >\n {renderPage(layout)}\n </div>\n ))}\n </div>\n ))}\n </div>\n <div\n style={\n scrollerLayout.strategy === ScrollStrategy.Horizontal\n ? {\n width: scrollerLayout.endSpacing,\n height: "100%",\n flexShrink: 0,\n }\n : {\n height: scrollerLayout.endSpacing,\n width: "100%",\n }\n }\n />\n </div>\n )\n}\n\ntype PDFViewerInnerProps = {\n viewerRef: React.ForwardedRef<PDFViewerHandle>\n pdfFile: string\n documentId: string\n document: PdfDocumentObject | null\n defaultZoom: number\n className?: string\n fileName?: string\n showDownload: boolean\n showToolbar: boolean\n showRotateControls: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onActivePageChange?: (pageNumber: number) => void\n onPdfUpload?: (file: File) => void\n onPagePointerDown?: PDFViewerProps["onPagePointerDown"]\n onPagePointerMove?: PDFViewerProps["onPagePointerMove"]\n onPagePointerUp?: PDFViewerProps["onPagePointerUp"]\n onPagePointerCancel?: PDFViewerProps["onPagePointerCancel"]\n onUploadFile: (file: File) => void\n}\n\nfunction PDFViewerInner({\n viewerRef,\n pdfFile,\n documentId,\n document: pdfDocument,\n defaultZoom,\n className,\n fileName,\n showDownload,\n showToolbar,\n showRotateControls,\n showUpload,\n toolbarActions,\n pageClassName,\n renderPageOverlay,\n onActivePageChange,\n onPdfUpload,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n onUploadFile,\n}: PDFViewerInnerProps) {\n const { registry } = useRegistry()\n const { state: scrollState, provides: scroll } = useScroll(documentId)\n const { state: zoomState, provides: zoom } = useZoom(documentId)\n const { provides: thumbnails } = useThumbnailCapability()\n const { plugin: thumbnailPlugin } = useThumbnailPlugin()\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)\n const [pageRotationDeltas, setPageRotationDeltas] =\n React.useState<PageRotationDeltas>(() => new Map())\n const [selectedPageIndexes, setSelectedPageIndexes] = React.useState<\n Set<number>\n >(() => new Set())\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const viewportElementRef = React.useRef<HTMLDivElement | null>(null)\n const pageRotationDeltasRef = React.useRef(pageRotationDeltas)\n const selectedPageIndexesRef = React.useRef(selectedPageIndexes)\n const selectionAnchorPageIndexRef = React.useRef<number | null>(null)\n const suppressActivePageSelectionSyncRef = React.useRef<number | null>(null)\n const initializedSelectionDocumentRef = React.useRef<string | null>(null)\n const basePageRotationsRef = React.useRef<Rotation[]>([])\n const basePageRotationsDocumentRef = React.useRef<string | null>(null)\n\n const activePage = scrollState.currentPage\n const numPages = pdfDocument?.pageCount ?? 0\n const isLoading = !pdfDocument\n const controlsDisabled = !numPages\n const downloadDisabled = controlsDisabled || isPreparingDownload\n const thumbnailSidebarVisible = sidebarOpen && !isLoading\n const currentZoomLevel = zoomState.currentZoomLevel\n const alignedThumbnailSidebarDocumentRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n pageRotationDeltasRef.current = pageRotationDeltas\n }, [pageRotationDeltas])\n\n React.useEffect(() => {\n selectedPageIndexesRef.current = selectedPageIndexes\n }, [selectedPageIndexes])\n\n React.useEffect(() => {\n const emptyDeltas = new Map<number, Rotation>()\n pageRotationDeltasRef.current = emptyDeltas\n setPageRotationDeltas(emptyDeltas)\n const emptySelection = new Set<number>()\n selectedPageIndexesRef.current = emptySelection\n setSelectedPageIndexes(emptySelection)\n selectionAnchorPageIndexRef.current = null\n suppressActivePageSelectionSyncRef.current = null\n initializedSelectionDocumentRef.current = null\n basePageRotationsRef.current = []\n basePageRotationsDocumentRef.current = null\n }, [documentId])\n\n React.useEffect(() => {\n if (!pdfDocument || basePageRotationsDocumentRef.current === documentId) {\n return\n }\n\n basePageRotationsRef.current = pdfDocument.pages.map((page) =>\n normalizeRotation(page.rotation)\n )\n basePageRotationsDocumentRef.current = documentId\n }, [documentId, pdfDocument])\n\n React.useEffect(() => {\n if (activePage > 0) onActivePageChange?.(activePage)\n }, [activePage, onActivePageChange])\n\n React.useEffect(() => {\n if (activePage < 1 || numPages < 1) return\n\n const activePageIndex = activePage - 1\n const suppressedPageIndex = suppressActivePageSelectionSyncRef.current\n\n suppressActivePageSelectionSyncRef.current = null\n\n if (suppressedPageIndex === activePageIndex) return\n\n const nextSelection = new Set([activePageIndex])\n\n selectionAnchorPageIndexRef.current = activePageIndex\n selectedPageIndexesRef.current = nextSelection\n setSelectedPageIndexes((previousSelection) =>\n arePageIndexSetsEqual(previousSelection, nextSelection)\n ? previousSelection\n : nextSelection\n )\n }, [activePage, numPages])\n\n React.useEffect(() => {\n if (\n numPages < 1 ||\n initializedSelectionDocumentRef.current === documentId\n ) {\n return\n }\n\n const initialPageIndex = Math.max(0, (activePage > 0 ? activePage : 1) - 1)\n const initialSelection = new Set([initialPageIndex])\n\n initializedSelectionDocumentRef.current = documentId\n selectionAnchorPageIndexRef.current = initialPageIndex\n selectedPageIndexesRef.current = initialSelection\n setSelectedPageIndexes(initialSelection)\n }, [activePage, documentId, numPages])\n\n React.useEffect(() => {\n if (!thumbnailSidebarVisible) {\n alignedThumbnailSidebarDocumentRef.current = null\n return\n }\n\n if (\n activePage < 1 ||\n !thumbnails ||\n alignedThumbnailSidebarDocumentRef.current === documentId\n ) {\n return\n }\n\n alignedThumbnailSidebarDocumentRef.current = documentId\n const frame = window.requestAnimationFrame(() => {\n thumbnails.forDocument(documentId).scrollToThumb(activePage - 1)\n })\n\n return () => window.cancelAnimationFrame(frame)\n }, [activePage, documentId, thumbnailSidebarVisible, thumbnails])\n\n // The zoom plugin only releases its viewport gate for mode-based zoom\n // levels (automatic/fit); with a numeric default the gate would never\n // lift, so apply the initial zoom explicitly once the document loads.\n const initialZoomDocumentRef = React.useRef<string | null>(null)\n React.useEffect(() => {\n if (!pdfDocument || !zoom) return\n if (initialZoomDocumentRef.current === documentId) return\n\n initialZoomDocumentRef.current = documentId\n zoom.requestZoom(defaultZoom)\n }, [defaultZoom, documentId, pdfDocument, zoom])\n\n const scrollToPage = React.useCallback(\n (pageNumber: number, options?: ScrollIntoViewOptions) => {\n scroll?.scrollToPage({\n pageNumber,\n behavior: options?.behavior === "smooth" ? "smooth" : "auto",\n })\n },\n [scroll]\n )\n\n const selectThumbnailPage = React.useCallback(\n (pageNumber: number, mode: ThumbnailSelectionMode) => {\n const pageIndex = pageNumber - 1\n\n if (pageIndex < 0 || pageIndex >= numPages) return\n\n suppressActivePageSelectionSyncRef.current = pageIndex\n\n setSelectedPageIndexes((previousSelection) => {\n let nextSelection: Set<number>\n\n if (mode === "range") {\n const anchorPageIndex =\n selectionAnchorPageIndexRef.current ??\n (activePage > 0 ? activePage - 1 : pageIndex)\n\n nextSelection = getPageIndexRange(anchorPageIndex, pageIndex)\n } else if (mode === "toggle") {\n nextSelection = new Set(previousSelection)\n\n if (nextSelection.has(pageIndex)) {\n nextSelection.delete(pageIndex)\n } else {\n nextSelection.add(pageIndex)\n }\n\n selectionAnchorPageIndexRef.current = pageIndex\n } else {\n nextSelection = new Set([pageIndex])\n selectionAnchorPageIndexRef.current = pageIndex\n }\n\n selectedPageIndexesRef.current = nextSelection\n return nextSelection\n })\n\n scrollToPage(pageNumber)\n },\n [activePage, numPages, scrollToPage]\n )\n\n React.useImperativeHandle(\n viewerRef,\n () => ({\n scrollToPage,\n scrollToPageArea: (pageNumber, area, options) => {\n const pageSize = pdfDocument?.pages[pageNumber - 1]?.size\n\n scroll?.scrollToPage({\n pageNumber,\n ...(pageSize\n ? {\n pageCoordinates: {\n x: ((area.left ?? 0) / 100) * pageSize.width,\n y: (area.top / 100) * pageSize.height,\n },\n alignY: 25,\n }\n : {}),\n behavior: options?.behavior === "smooth" ? "smooth" : "auto",\n })\n },\n getViewportElement: () => viewportElementRef.current,\n }),\n [pdfDocument, scroll, scrollToPage]\n )\n\n const handleDownload = React.useCallback(async () => {\n if (!pdfFile || isPreparingDownload) return\n\n setIsPreparingDownload(true)\n\n try {\n await downloadPdfWithPageRotations({\n fileName: getPdfDownloadFileName(fileName, pdfFile),\n pageRotationDeltas,\n src: pdfFile,\n })\n } catch (error) {\n console.error(error)\n } finally {\n setIsPreparingDownload(false)\n }\n }, [fileName, isPreparingDownload, pageRotationDeltas, pdfFile])\n\n const rotateSelectedPages = React.useCallback(\n (direction: -1 | 1) => {\n if (!pdfDocument || !registry || activePage < 1) return\n\n const documentState = registry.getStore().getState().core.documents[\n documentId\n ]\n const currentDocument = documentState?.document ?? pdfDocument\n const selectedTargetPageIndexes = Array.from(\n selectedPageIndexesRef.current\n ).filter((pageIndex) => currentDocument.pages[pageIndex])\n const fallbackPageIndex = activePage - 1\n const targetPageIndexes = (\n selectedTargetPageIndexes.length\n ? selectedTargetPageIndexes\n : [fallbackPageIndex]\n )\n .filter((pageIndex) => currentDocument.pages[pageIndex])\n .sort((a, b) => a - b)\n\n if (targetPageIndexes.length === 0) return\n\n const previousDeltas = pageRotationDeltasRef.current\n const nextDeltas = new Map(previousDeltas)\n const referencePageIndex =\n activePage > 0 && currentDocument.pages[activePage - 1]\n ? activePage - 1\n : targetPageIndexes[0]\n let scrollDelta = 0\n\n for (const pageIndex of targetPageIndexes) {\n const currentPage = currentDocument.pages[pageIndex]\n if (!currentPage) continue\n\n const previousDelta = previousDeltas.get(pageIndex) ?? 0\n const nextDelta = normalizeRotation(previousDelta + direction)\n const basePageRotation =\n basePageRotationsRef.current[pageIndex] ??\n normalizeRotation(currentPage.rotation)\n const previousPageRotation = normalizeRotation(\n basePageRotation + previousDelta\n )\n const nextPageRotation = normalizeRotation(basePageRotation + nextDelta)\n const previousRotatedSize = getRotatedDimensions({\n height: currentPage.size.height * currentZoomLevel,\n rotation: previousPageRotation,\n width: currentPage.size.width * currentZoomLevel,\n })\n const nextRotatedSize = getRotatedDimensions({\n height: currentPage.size.height * currentZoomLevel,\n rotation: nextPageRotation,\n width: currentPage.size.width * currentZoomLevel,\n })\n const heightDelta = nextRotatedSize.height - previousRotatedSize.height\n\n if (pageIndex < referencePageIndex) {\n scrollDelta += heightDelta\n } else if (pageIndex === referencePageIndex) {\n scrollDelta += heightDelta / 2\n }\n\n if (nextDelta) {\n nextDeltas.set(pageIndex, nextDelta)\n } else {\n nextDeltas.delete(pageIndex)\n }\n }\n\n const store = registry.getStore()\n const viewport = viewportElementRef.current\n\n pageRotationDeltasRef.current = nextDeltas\n flushSync(() => {\n setPageRotationDeltas(nextDeltas)\n store.dispatchToCore(refreshPages(documentId, targetPageIndexes))\n })\n\n if (viewport && scrollDelta !== 0) {\n viewport.scrollTop += scrollDelta\n }\n ;(\n thumbnailPlugin as {\n calculateWindowState?: (documentId: string) => void\n } | null\n )?.calculateWindowState?.(documentId)\n },\n [\n activePage,\n currentZoomLevel,\n documentId,\n pdfDocument,\n registry,\n thumbnailPlugin,\n ]\n )\n\n const handleUpload = React.useCallback(\n (file: File) => {\n onUploadFile(file)\n onPdfUpload?.(file)\n },\n [onPdfUpload, onUploadFile]\n )\n\n const renderPage = React.useCallback(\n (page: PageLayout) => {\n const pageNumber = page.pageNumber\n const basePageRotation =\n basePageRotationsRef.current[page.pageIndex] ??\n pdfDocument?.pages[page.pageIndex]?.rotation ??\n normalizeRotation(0)\n const pageRotation = normalizeRotation(\n basePageRotation + (pageRotationDeltas.get(page.pageIndex) ?? 0)\n )\n\n return (\n <Rotate\n documentId={documentId}\n pageIndex={page.pageIndex}\n rotation={pageRotation}\n >\n <PagePointerProvider\n documentId={documentId}\n pageIndex={page.pageIndex}\n rotation={pageRotation}\n key={`${page.pageIndex}-${pageRotation}`}\n data-pdf-viewer-page={pageNumber}\n className={cn(\n "relative border border-transparent bg-transparent shadow-xs select-none selection:bg-transparent selection:text-inherit",\n pageClassName?.(pageNumber)\n )}\n style={{ backgroundColor: "transparent" }}\n onPointerDown={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerDown?.(event, pageNumber)\n }\n onPointerMove={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerMove?.(event, pageNumber)\n }\n onPointerUp={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerUp?.(event, pageNumber)\n }\n onPointerCancel={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerCancel?.(event, pageNumber)\n }\n >\n <div\n aria-hidden="true"\n className="pointer-events-none absolute inset-0 bg-white"\n />\n <RenderLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n scale={Math.min(currentZoomLevel, PAGE_BASE_RENDER_MAX_SCALE)}\n dpr={PAGE_BASE_RENDER_DPR}\n className="pointer-events-none absolute inset-0 h-full w-full object-fill opacity-100 blur-[0.35px] transition-none"\n />\n <TilingLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n key={`tiles-${page.pageIndex}-${pageRotation}`}\n className="pointer-events-none opacity-100 transition-none [&_img]:opacity-100 [&_img]:transition-none"\n />\n <SearchLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n className="pointer-events-none"\n highlightColor="rgba(253, 224, 71, 0.45)"\n activeHighlightColor="rgba(249, 115, 22, 0.55)"\n />\n <PDFViewerTextSelectionLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n scale={currentZoomLevel}\n />\n {renderPageOverlay?.({\n pageNumber,\n pageWidth: page.width,\n pageHeight: page.height,\n scale: currentZoomLevel,\n rotation: rotationToDegrees(pageRotation),\n })}\n </PagePointerProvider>\n </Rotate>\n )\n },\n [\n currentZoomLevel,\n onPagePointerCancel,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n pageClassName,\n pageRotationDeltas,\n renderPageOverlay,\n documentId,\n pdfDocument,\n ]\n )\n\n return (\n <div\n data-slot="pdf-viewer"\n className={cn(\n "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n "select-none selection:bg-transparent selection:text-inherit",\n className\n )}\n >\n {showToolbar ? (\n <div className="flex min-h-12 flex-wrap items-center justify-between gap-2 border-b bg-background px-3 py-2">\n <div className="flex min-w-0 flex-wrap items-center gap-2">\n <TooltipProvider>\n <ToolbarTooltip label="Toggle thumbnails">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Toggle thumbnails"\n disabled={controlsDisabled}\n onClick={() => setSidebarOpen((open) => !open)}\n >\n <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </TooltipProvider>\n <PDFViewerPageNumberControl\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n numPages={numPages}\n onPageChange={scrollToPage}\n />\n </div>\n <TooltipProvider>\n <div className="flex min-w-0 flex-wrap items-center justify-end gap-1">\n {showRotateControls ? (\n <>\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Rotate counterclockwise">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Rotate counterclockwise"\n disabled={controlsDisabled}\n onClick={() => rotateSelectedPages(-1)}\n >\n <HugeiconsIcon\n icon={RotateClockwiseIcon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Rotate clockwise">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Rotate clockwise"\n disabled={controlsDisabled}\n onClick={() => rotateSelectedPages(1)}\n >\n <HugeiconsIcon\n icon={RotateClockwiseIcon}\n className="size-4 -scale-x-100"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom out"\n disabled={\n controlsDisabled || currentZoomLevel <= ZOOM_OPTIONS[0]\n }\n onClick={() => {\n const nextZoom = [...ZOOM_OPTIONS]\n .reverse()\n .find((option) => option < currentZoomLevel)\n\n zoom?.requestZoom(nextZoom ?? ZOOM_OPTIONS[0])\n }}\n >\n <HugeiconsIcon\n icon={MinusSignCircleIcon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={String(currentZoomLevel)}\n onValueChange={(value) => zoom?.requestZoom(Number(value))}\n disabled={controlsDisabled}\n modal={false}\n >\n <SelectTrigger size="sm" className="w-[84px] min-w-[84px]">\n <SelectValue placeholder="Zoom">\n {Math.round(currentZoomLevel * 100)}%\n </SelectValue>\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((option) => (\n <SelectItem key={option} value={String(option)}>\n {Math.round(option * 100)}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom in"\n disabled={\n controlsDisabled ||\n currentZoomLevel >= ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n }\n onClick={() => {\n const nextZoom = ZOOM_OPTIONS.find(\n (option) => option > currentZoomLevel\n )\n\n zoom?.requestZoom(\n nextZoom ?? ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n )\n }}\n >\n <HugeiconsIcon\n icon={PlusSignCircleIcon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <PDFViewerSearchControl\n key={documentId}\n documentId={documentId}\n controlsDisabled={controlsDisabled}\n />\n {toolbarActions ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {toolbarActions}\n </>\n ) : null}\n {showDownload || showUpload ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <PDFViewerFileActionsMenu\n downloadDisabled={downloadDisabled}\n isPreparingDownload={isPreparingDownload}\n onDownload={handleDownload}\n onUploadFile={handleUpload}\n showDownload={showDownload}\n showUpload={showUpload}\n />\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\n ) : null}\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {isLoading ? (\n <PDFViewerLoadingSkeleton\n sidebarInline={sidebarInline}\n sidebarOpen={sidebarOpen}\n />\n ) : null}\n <div className="flex h-full max-h-full min-h-0 w-full flex-1 overflow-hidden">\n <DocumentViewerThumbnailSidebar\n closedInlineClassName={THUMBNAIL_SIDEBAR_CLOSED_CLASS}\n inline={sidebarInline}\n open={thumbnailSidebarVisible}\n widthClassName={THUMBNAIL_SIDEBAR_WIDTH_CLASS}\n >\n {thumbnailSidebarVisible ? (\n <PDFViewerThumbnails\n basePageRotations={basePageRotationsRef.current}\n documentId={documentId}\n activePage={activePage}\n pageCount={numPages}\n pageRotationDeltas={pageRotationDeltas}\n pdfDocument={pdfDocument}\n selectedPageIndexes={selectedPageIndexes}\n onSelectPage={selectThumbnailPage}\n />\n ) : null}\n </DocumentViewerThumbnailSidebar>\n <PDFViewerScrollAreaViewport\n documentId={documentId}\n className="relative h-full max-h-full min-h-0 min-w-0 flex-1"\n >\n <PDFViewerViewportBridge viewportElementRef={viewportElementRef} />\n <PDFViewerSelectionCopyShortcut documentId={documentId} />\n <PDFViewerSelectionReleaseGuard documentId={documentId} />\n <GlobalPointerProvider documentId={documentId}>\n <PDFViewerScroller\n basePageRotations={basePageRotationsRef.current}\n documentId={documentId}\n pageRotationDeltas={pageRotationDeltas}\n renderPage={renderPage}\n />\n </GlobalPointerProvider>\n <CopyToClipboard />\n </PDFViewerScrollAreaViewport>\n </div>\n </div>\n </div>\n )\n}\n\nfunction PDFViewerDocumentLoader({\n pdfFile,\n onDocumentLoadSuccess,\n ...innerProps\n}: {\n pdfFile: string\n onDocumentLoadSuccess?: (numPages: number) => void\n} & Omit<PDFViewerInnerProps, "pdfFile" | "documentId" | "document">) {\n const { provides: documentManager } = useDocumentManagerCapability()\n const { activeDocumentId, activeDocument } = useActiveDocument()\n const [loadError, setLoadError] = React.useState(false)\n const openedFileRef = React.useRef<string | null>(null)\n const onDocumentLoadSuccessRef = React.useRef(onDocumentLoadSuccess)\n\n React.useEffect(() => {\n onDocumentLoadSuccessRef.current = onDocumentLoadSuccess\n })\n\n React.useEffect(() => {\n if (!documentManager || !pdfFile) return\n if (openedFileRef.current === pdfFile) return\n\n openedFileRef.current = pdfFile\n setLoadError(false)\n\n const previousDocumentIds = documentManager\n .getOpenDocuments()\n .map((openDocument) => openDocument.id)\n const handleOpenError = () => {\n if (openedFileRef.current === pdfFile) setLoadError(true)\n }\n\n documentManager\n .openDocumentUrl({\n url: pdfFile,\n mode: pdfFile.startsWith("blob:") ? "full-fetch" : "auto",\n })\n .wait((response) => {\n response.task.wait((openedDocument) => {\n onDocumentLoadSuccessRef.current?.(openedDocument.pageCount)\n previousDocumentIds.forEach((documentIdToClose) => {\n documentManager.closeDocument(documentIdToClose).wait(\n () => undefined,\n () => undefined\n )\n })\n }, handleOpenError)\n }, handleOpenError)\n }, [documentManager, pdfFile])\n\n const document =\n activeDocument?.status === "loaded" ? activeDocument.document : null\n const documentFailed = loadError || activeDocument?.status === "error"\n\n if (!activeDocumentId || documentFailed || !pdfFile) {\n return (\n <PDFViewerFallbackShell\n className={innerProps.className}\n showToolbar={innerProps.showToolbar}\n showUpload={innerProps.showUpload}\n sidebarOpen={false}\n state={!pdfFile ? "empty" : documentFailed ? "error" : "loading"}\n onUploadFile={(file) => {\n innerProps.onUploadFile(file)\n innerProps.onPdfUpload?.(file)\n }}\n />\n )\n }\n\n return (\n <PDFViewerInner\n {...innerProps}\n pdfFile={pdfFile}\n documentId={activeDocumentId}\n document={document}\n />\n )\n}\n\nexport const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(\n function PDFViewer(\n {\n className,\n defaultZoom = DEFAULT_ZOOM,\n fileName,\n showDownload = true,\n showRotateControls = true,\n showToolbar = true,\n showUpload = true,\n src,\n toolbarActions,\n pageClassName,\n renderPageOverlay,\n onActivePageChange,\n onDocumentLoadSuccess,\n onPdfUpload,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n },\n ref\n ) {\n const { engine, error: engineError } = useSharedPdfEngine()\n const [pdfFile, setPdfFile] = React.useState(src ?? "")\n const [uploadedPdfUrl, setUploadedPdfUrl] = React.useState<string | null>(\n null\n )\n\n React.useEffect(() => {\n setPdfFile(src ?? "")\n }, [src])\n\n React.useEffect(\n () => () => {\n if (uploadedPdfUrl) URL.revokeObjectURL(uploadedPdfUrl)\n },\n [uploadedPdfUrl]\n )\n\n const handleUploadFile = React.useCallback((nextFile: File) => {\n const nextUrl = URL.createObjectURL(nextFile)\n\n setUploadedPdfUrl((previousUrl) => {\n if (previousUrl) URL.revokeObjectURL(previousUrl)\n return nextUrl\n })\n setPdfFile(nextUrl)\n }, [])\n\n // Plugin registrations are created once per viewer instance.\n const [plugins] = React.useState(() => [\n createPluginRegistration(DocumentManagerPluginPackage),\n createPluginRegistration(ViewportPluginPackage, {\n viewportGap: PAGE_GAP,\n }),\n createPluginRegistration(ScrollPluginPackage, {\n defaultPageGap: PAGE_GAP,\n defaultBufferSize: 2,\n }),\n createPluginRegistration(RenderPluginPackage),\n createPluginRegistration(TilingPluginPackage, {\n tileSize: 768,\n overlapPx: 2.5,\n extraRings: 0,\n }),\n createPluginRegistration(InteractionManagerPluginPackage),\n createPluginRegistration(SelectionPluginPackage, {\n marquee: { enabled: false },\n }),\n createPluginRegistration(SearchPluginPackage, {\n showAllResults: true,\n }),\n createPluginRegistration(ThumbnailPluginPackage, {\n width: THUMBNAIL_WIDTH,\n gap: THUMBNAIL_GAP,\n imagePadding: THUMBNAIL_IMAGE_PADDING,\n labelHeight: THUMBNAIL_LABEL_HEIGHT,\n paddingY: THUMBNAIL_PANE_PADDING_Y,\n buffer: 3,\n autoScroll: true,\n scrollBehavior: "auto",\n }),\n createPluginRegistration(ZoomPluginPackage, {\n defaultZoomLevel: defaultZoom,\n minZoom: ZOOM_OPTIONS[0],\n maxZoom: ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1],\n }),\n createPluginRegistration(RotatePluginPackage),\n ])\n\n if (engineError) {\n return (\n <div\n data-slot="pdf-viewer"\n className={cn(\n "grid h-full w-full place-items-center bg-background p-6 text-sm text-muted-foreground",\n className\n )}\n >\n Unable to load the PDF engine.\n </div>\n )\n }\n\n if (!engine) {\n return (\n <div\n data-slot="pdf-viewer"\n className={cn(\n "relative flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n {showToolbar ? (\n <div className="min-h-12 border-b bg-background" />\n ) : null}\n <div className="relative min-h-0 flex-1">\n <PDFViewerLoadingSkeleton sidebarInline sidebarOpen={false} />\n </div>\n </div>\n )\n }\n\n return (\n <EmbedPDF engine={engine} plugins={plugins}>\n <PDFViewerDocumentLoader\n viewerRef={ref}\n pdfFile={pdfFile}\n defaultZoom={defaultZoom}\n className={className}\n fileName={fileName}\n showDownload={showDownload}\n showToolbar={showToolbar}\n showRotateControls={showRotateControls}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n pageClassName={pageClassName}\n renderPageOverlay={renderPageOverlay}\n onActivePageChange={onActivePageChange}\n onDocumentLoadSuccess={onDocumentLoadSuccess}\n onPdfUpload={onPdfUpload}\n onPagePointerDown={onPagePointerDown}\n onPagePointerMove={onPagePointerMove}\n onPagePointerUp={onPagePointerUp}\n onPagePointerCancel={onPagePointerCancel}\n onUploadFile={handleUploadFile}\n />\n </EmbedPDF>\n )\n }\n)\n'+ '"use client"\n\nimport * as React from "react"\nimport { createPluginRegistration, refreshPages } from "@embedpdf/core"\nimport { EmbedPDF, useRegistry } from "@embedpdf/core/react"\nimport type {\n PdfDocumentObject,\n PdfEngine,\n Rect,\n Rotation,\n} from "@embedpdf/models"\nimport {\n DocumentManagerPluginPackage,\n useActiveDocument,\n useDocumentManagerCapability,\n} from "@embedpdf/plugin-document-manager/react"\nimport {\n GlobalPointerProvider,\n InteractionManagerPluginPackage,\n PagePointerProvider,\n} from "@embedpdf/plugin-interaction-manager/react"\nimport { RenderLayer, RenderPluginPackage } from "@embedpdf/plugin-render/react"\nimport { Rotate, RotatePluginPackage } from "@embedpdf/plugin-rotate/react"\nimport {\n ScrollPluginPackage,\n ScrollStrategy,\n useScroll,\n useScrollPlugin,\n type PageLayout,\n type ScrollerLayout,\n type VirtualItem,\n} from "@embedpdf/plugin-scroll/react"\nimport {\n SearchLayer,\n SearchPluginPackage,\n useSearch,\n} from "@embedpdf/plugin-search/react"\nimport {\n CopyToClipboard,\n SelectionPluginPackage,\n useSelectionCapability,\n useSelectionPlugin,\n} from "@embedpdf/plugin-selection/react"\nimport {\n ThumbImg,\n ThumbnailPluginPackage,\n useThumbnailCapability,\n useThumbnailPlugin,\n type ThumbMeta,\n} from "@embedpdf/plugin-thumbnail/react"\nimport { TilingLayer, TilingPluginPackage } from "@embedpdf/plugin-tiling/react"\nimport {\n useIsViewportGated,\n useViewportCapability,\n useViewportElement,\n useViewportRef,\n ViewportElementContext,\n ViewportPluginPackage,\n} from "@embedpdf/plugin-viewport/react"\nimport { useZoom, ZoomPluginPackage } from "@embedpdf/plugin-zoom/react"\nimport {\n ArrowLeft01Icon,\n ArrowRight01Icon,\n Download01Icon,\n MinusSignCircleIcon,\n MoreHorizontalIcon,\n PlusSignCircleIcon,\n RotateClockwiseIcon,\n Search01Icon,\n SidebarLeftIcon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { flushSync } from "react-dom"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DocumentViewerSidebarSkeleton,\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/ui/document-viewer-sidebar"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { Input } from "@/components/ui/input"\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from "@/components/ui/popover"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport { loadSharedPdfEngine } from "@/components/pdf-thumbnail-utils"\n\nexport type PDFViewerPageOverlayProps = {\n pageNumber: number\n pageWidth: number\n pageHeight: number\n scale: number\n rotation: number\n}\n\nexport type PDFViewerHandle = {\n scrollToPage: (pageNumber: number, options?: ScrollIntoViewOptions) => void\n scrollToPageArea: (\n pageNumber: number,\n area: { top: number; left?: number; width?: number; height?: number },\n options?: ScrollToOptions\n ) => void\n getViewportElement: () => HTMLDivElement | null\n}\n\nexport type PDFViewerProps = {\n className?: string\n defaultZoom?: number\n fileName?: string\n showDownload?: boolean\n showToolbar?: boolean\n showRotateControls?: boolean\n showUpload?: boolean\n src?: string\n toolbarActions?: React.ReactNode\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onActivePageChange?: (pageNumber: number) => void\n onDocumentLoadSuccess?: (numPages: number) => void\n onPdfUpload?: (file: File) => void\n onPagePointerDown?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerMove?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerUp?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerCancel?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n}\n\nconst DEFAULT_ZOOM = 1\nconst ZOOM_OPTIONS = [0.1, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2]\nconst PAGE_GAP = 24\nconst THUMBNAIL_PAGE_WIDTH = 92\nconst THUMBNAIL_IMAGE_PADDING = 8\nconst THUMBNAIL_WIDTH = THUMBNAIL_PAGE_WIDTH + THUMBNAIL_IMAGE_PADDING * 2\nconst THUMBNAIL_LABEL_HEIGHT = 24\nconst THUMBNAIL_GAP = 12\nconst THUMBNAIL_PANE_PADDING_Y = 16\nconst THUMBNAIL_SIDEBAR_WIDTH_CLASS = "w-40"\nconst THUMBNAIL_SIDEBAR_CLOSED_CLASS = "-ml-40"\nconst PAGE_BASE_RENDER_MAX_SCALE = 1\nconst PAGE_BASE_RENDER_DPR = 1\nconst PDF_SEARCH_DEBOUNCE_MS = 300\nconst TEXT_SELECTION_BACKGROUND = "rgba(59, 130, 246, 0.14)"\nconst THUMBNAIL_FOCUS_RING_CLASS =\n "group-focus-visible/pdf-thumbnail-sidebar:ring-2 group-focus-visible/pdf-thumbnail-sidebar:ring-ring group-focus-visible/pdf-thumbnail-sidebar:ring-offset-1 group-focus-visible/pdf-thumbnail-sidebar:ring-offset-background"\n\ntype PageRotationDeltas = Map<number, Rotation>\ntype ThumbnailSelectionMode = "replace" | "toggle" | "range"\n\nfunction getPageIndexRange(from: number, to: number): Set<number> {\n const start = Math.min(from, to)\n const end = Math.max(from, to)\n const range = new Set<number>()\n\n for (let pageIndex = start; pageIndex <= end; pageIndex += 1) {\n range.add(pageIndex)\n }\n\n return range\n}\n\nfunction arePageIndexSetsEqual(left: Set<number>, right: Set<number>) {\n if (left.size !== right.size) return false\n\n for (const value of left) {\n if (!right.has(value)) return false\n }\n\n return true\n}\n\nfunction normalizeRotation(rotation: number): Rotation {\n return (((rotation % 4) + 4) % 4) as Rotation\n}\n\nfunction useSharedPdfEngine() {\n const [engine, setEngine] = React.useState<PdfEngine | null>(null)\n const [error, setError] = React.useState<Error | null>(null)\n\n React.useEffect(() => {\n let cancelled = false\n\n loadSharedPdfEngine().then(\n (loadedEngine) => {\n if (!cancelled) setEngine(loadedEngine)\n },\n (loadError: Error) => {\n if (!cancelled) setError(loadError)\n }\n )\n\n return () => {\n cancelled = true\n }\n }, [])\n\n return { engine, error }\n}\n\nfunction rotationToDegrees(rotation: Rotation) {\n return (rotation as number) * 90\n}\n\nfunction normalizeDegrees(rotation: number) {\n return ((rotation % 360) + 360) % 360\n}\n\nfunction ensurePdfExtension(fileName: string) {\n return fileName.toLowerCase().endsWith(".pdf") ? fileName : `${fileName}.pdf`\n}\n\nfunction getPdfDownloadFileName(fileName: string | undefined, src: string) {\n if (fileName?.trim()) return ensurePdfExtension(fileName.trim())\n\n const pathname = src.split(/[?#]/)[0] ?? ""\n const rawName = pathname.split("/").pop() || "document.pdf"\n\n try {\n return ensurePdfExtension(decodeURIComponent(rawName))\n } catch {\n return ensurePdfExtension(rawName)\n }\n}\n\nfunction getRotatedPdfDownloadFileName(fileName: string) {\n return fileName.replace(/\\.pdf$/i, "-rotated.pdf")\n}\n\nfunction downloadBlob(blob: Blob, fileName: string) {\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n\n anchor.href = url\n anchor.download = fileName\n anchor.rel = "noopener"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nasync function downloadPdfWithPageRotations({\n fileName,\n pageRotationDeltas,\n src,\n}: {\n fileName: string\n pageRotationDeltas: PageRotationDeltas\n src: string\n}) {\n const response = await fetch(src)\n\n if (!response.ok) {\n throw new Error(`Failed to download PDF (${response.status})`)\n }\n\n if (pageRotationDeltas.size === 0) {\n downloadBlob(await response.blob(), fileName)\n return\n }\n\n const [{ PDFDocument, degrees }, pdfBytes] = await Promise.all([\n import("pdf-lib"),\n response.arrayBuffer(),\n ])\n const pdfDocument = await PDFDocument.load(pdfBytes)\n\n pdfDocument.getPages().forEach((page, pageIndex) => {\n const rotationDelta = pageRotationDeltas.get(pageIndex)\n\n if (!rotationDelta) return\n\n page.setRotation(\n degrees(\n normalizeDegrees(\n page.getRotation().angle + rotationToDegrees(rotationDelta)\n )\n )\n )\n })\n\n const nextPdfBytes = await pdfDocument.save()\n const nextPdfBuffer = new ArrayBuffer(nextPdfBytes.byteLength)\n new Uint8Array(nextPdfBuffer).set(nextPdfBytes)\n\n downloadBlob(\n new Blob([nextPdfBuffer], { type: "application/pdf" }),\n getRotatedPdfDownloadFileName(fileName)\n )\n}\n\nfunction getThumbnailMetaForPage({\n page,\n pageIndex,\n rotation,\n width,\n imagePadding,\n labelHeight,\n top,\n}: {\n page: PdfDocumentObject["pages"][number]\n pageIndex: number\n rotation: Rotation\n width: number\n imagePadding: number\n labelHeight: number\n top: number\n}): ThumbMeta {\n const innerWidth = Math.max(1, width - imagePadding * 2)\n const pageWidth = rotation % 2 === 1 ? page.size.height : page.size.width\n const pageHeight = rotation % 2 === 1 ? page.size.width : page.size.height\n const imageHeight = Math.round(innerWidth * (pageHeight / pageWidth))\n const wrapperHeight = imagePadding + imageHeight + imagePadding + labelHeight\n\n return {\n pageIndex,\n width: innerWidth,\n height: imageHeight,\n wrapperHeight,\n top,\n labelHeight,\n padding: imagePadding,\n }\n}\n\nfunction buildThumbnailLayout({\n basePageRotations,\n pageRotationDeltas,\n pdfDocument,\n width,\n gap,\n imagePadding,\n labelHeight,\n paddingY,\n}: {\n basePageRotations: Rotation[]\n pageRotationDeltas: PageRotationDeltas\n pdfDocument: PdfDocumentObject | null\n width: number\n gap: number\n imagePadding: number\n labelHeight: number\n paddingY: number\n}) {\n if (!pdfDocument) return null\n\n let top = paddingY\n const items = pdfDocument.pages.map((page, pageIndex) => {\n const basePageRotation =\n basePageRotations[pageIndex] ?? normalizeRotation(page.rotation)\n const pageRotation = normalizeRotation(\n basePageRotation + (pageRotationDeltas.get(pageIndex) ?? 0)\n )\n const meta = getThumbnailMetaForPage({\n page,\n pageIndex,\n rotation: pageRotation,\n width,\n imagePadding,\n labelHeight,\n top,\n })\n\n top += meta.wrapperHeight + gap\n return meta\n })\n\n return {\n items,\n totalHeight: items.length ? top - gap + paddingY : paddingY * 2,\n }\n}\n\nfunction getVisibleThumbnailItems({\n buffer,\n clientHeight,\n items,\n scrollTop,\n}: {\n buffer: number\n clientHeight: number\n items: ThumbMeta[]\n scrollTop: number\n}) {\n if (items.length === 0) return []\n if (clientHeight <= 0)\n return items.slice(0, Math.min(items.length, buffer * 2))\n\n const viewportBottom = scrollTop + clientHeight\n let start = items.findIndex(\n (item) => item.top + item.wrapperHeight >= scrollTop\n )\n\n if (start === -1) start = items.length - 1\n\n let end = start\n while (end < items.length && items[end].top <= viewportBottom) {\n end += 1\n }\n\n return items.slice(\n Math.max(0, start - buffer),\n Math.min(items.length, end + buffer)\n )\n}\n\nfunction PDFViewerLoadingSkeleton({\n sidebarOpen,\n sidebarInline,\n}: {\n sidebarOpen: boolean\n sidebarInline: boolean\n}) {\n return (\n <div className="absolute inset-0 z-20 flex bg-muted/30">\n {sidebarOpen ? (\n <DocumentViewerSidebarSkeleton\n className={THUMBNAIL_SIDEBAR_WIDTH_CLASS}\n inline={sidebarInline}\n />\n ) : null}\n <div className="grid min-w-0 flex-1 place-items-center">\n <Spinner className="size-4" />\n </div>\n </div>\n )\n}\n\n// Rendered while the engine or document is not ready: same frame as the\n// full viewer, with only the upload control usable.\nfunction PDFViewerFallbackShell({\n className,\n showToolbar,\n showUpload,\n sidebarOpen,\n state,\n onUploadFile,\n}: {\n className?: string\n showToolbar: boolean\n showUpload: boolean\n sidebarOpen: boolean\n state: "loading" | "error" | "empty"\n onUploadFile?: (file: File) => void\n}) {\n return (\n <div\n data-slot="pdf-viewer"\n className={cn(\n "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n {showToolbar ? (\n <div className="flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2">\n {showUpload && onUploadFile ? (\n <PDFViewerFileActionsMenu onUploadFile={onUploadFile} showUpload />\n ) : null}\n </div>\n ) : null}\n <div className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30">\n {state === "loading" ? (\n <PDFViewerLoadingSkeleton sidebarInline sidebarOpen={sidebarOpen} />\n ) : null}\n {state === "error" ? (\n <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-sm text-muted-foreground">\n Unable to load the PDF preview.\n </div>\n ) : null}\n {state === "empty" ? (\n <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-center text-sm text-muted-foreground">\n <div className="max-w-sm space-y-3">\n <div className="font-medium text-foreground">\n Upload a PDF to preview\n </div>\n <div>\n Pass a PDF URL with the <code>src</code> prop or use the upload\n control.\n </div>\n </div>\n </div>\n ) : null}\n </div>\n </div>\n )\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction PDFViewerFileActionsMenu({\n downloadDisabled,\n isPreparingDownload = false,\n onDownload,\n onUploadFile,\n showDownload = false,\n showUpload = false,\n}: {\n downloadDisabled?: boolean\n isPreparingDownload?: boolean\n onDownload?: () => void\n onUploadFile?: (file: File) => void\n showDownload?: boolean\n showUpload?: boolean\n}) {\n const inputRef = React.useRef<HTMLInputElement>(null)\n\n if (!showDownload && !showUpload) return null\n\n return (\n <>\n {showUpload && onUploadFile ? (\n <input\n ref={inputRef}\n type="file"\n accept="application/pdf,.pdf"\n className="sr-only"\n tabIndex={-1}\n onChange={(event) => {\n const nextFile = event.target.files?.[0]\n\n if (nextFile) {\n onUploadFile(nextFile)\n event.currentTarget.value = ""\n }\n }}\n />\n ) : null}\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Open PDF actions"\n >\n <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="w-40">\n {showDownload && onDownload ? (\n <DropdownMenuItem disabled={downloadDisabled} onClick={onDownload}>\n {isPreparingDownload ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n )}\n Download\n </DropdownMenuItem>\n ) : null}\n {showUpload && onUploadFile ? (\n <DropdownMenuItem onClick={() => inputRef.current?.click()}>\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload\n </DropdownMenuItem>\n ) : null}\n </DropdownMenuContent>\n </DropdownMenu>\n </>\n )\n}\n\nfunction PDFViewerPageNumberControl({\n activePage,\n controlsDisabled,\n numPages,\n onPageChange,\n}: {\n activePage: number\n controlsDisabled: boolean\n numPages: number\n onPageChange: (pageNumber: number) => void\n}) {\n const inputRef = React.useRef<HTMLInputElement>(null)\n const displayPage = numPages ? activePage : 1\n const [isEditing, setIsEditing] = React.useState(false)\n const [draftPage, setDraftPage] = React.useState(() => String(displayPage))\n\n React.useEffect(() => {\n if (!isEditing) return\n\n inputRef.current?.focus()\n inputRef.current?.select()\n }, [isEditing])\n\n const applyPageDraft = React.useCallback(\n (value: string) => {\n const trimmedValue = value.trim()\n\n if (!trimmedValue) return\n\n const parsedPage = Number(trimmedValue)\n\n if (!Number.isInteger(parsedPage)) return\n\n onPageChange(Math.min(Math.max(parsedPage, 1), Math.max(numPages, 1)))\n },\n [numPages, onPageChange]\n )\n\n return (\n <div className="flex items-center text-sm whitespace-nowrap text-primary">\n <span>Page</span>\n {isEditing ? (\n <Input\n ref={inputRef}\n aria-label="Page number"\n inputMode="numeric"\n pattern="[0-9]*"\n size="sm"\n value={draftPage}\n className="mx-1 w-14 min-w-14 rounded-md [&_[data-slot=input]]:text-center"\n onBlur={() => setIsEditing(false)}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) => {\n const nextValue = event.target.value\n\n setDraftPage(nextValue)\n applyPageDraft(nextValue)\n }}\n onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key === "Enter" || event.key === "Escape") {\n event.currentTarget.blur()\n }\n }}\n />\n ) : (\n <Button\n type="button"\n variant="ghost"\n size="sm"\n className="font-normal"\n aria-label={`Current page ${displayPage}. Edit page number`}\n disabled={controlsDisabled || !numPages}\n onClick={() => {\n setDraftPage(String(displayPage))\n setIsEditing(true)\n }}\n >\n {displayPage}\n </Button>\n )}\n <span>of {numPages || "–"}</span>\n </div>\n )\n}\n\nfunction PDFViewerSearchControl({\n documentId,\n controlsDisabled,\n}: {\n documentId: string\n controlsDisabled: boolean\n}) {\n const { state, provides } = useSearch(documentId)\n const { provides: scroll } = useScroll(documentId)\n const [searchDraft, setSearchDraft] = React.useState("")\n const [searchQuery, setSearchQuery] = React.useState("")\n const [isSearching, setIsSearching] = React.useState(false)\n const providesRef = React.useRef(provides)\n const scrollRef = React.useRef(scroll)\n const searchRequestIdRef = React.useRef(0)\n const hasActiveQuery = Boolean(searchQuery.trim())\n const resultLabel = isSearching\n ? "Searching"\n : !hasActiveQuery\n ? "No search"\n : state.total\n ? `${state.activeResultIndex + 1} / ${state.total}`\n : "No results"\n\n const scrollToResult = React.useCallback(\n (index: number) => {\n const result = state.results[index]\n\n if (!result || !scroll) return\n\n const firstRect = result.rects[0]\n\n scroll.scrollToPage({\n pageNumber: result.pageIndex + 1,\n ...(firstRect\n ? {\n pageCoordinates: {\n x: firstRect.origin.x,\n y: firstRect.origin.y,\n },\n alignY: 30,\n }\n : {}),\n behavior: "auto",\n })\n },\n [scroll, state.results]\n )\n\n React.useEffect(() => {\n providesRef.current = provides\n scrollRef.current = scroll\n }, [provides, scroll])\n\n const runSearch = React.useCallback((rawQuery: string) => {\n const query = rawQuery.trim()\n const requestId = searchRequestIdRef.current + 1\n searchRequestIdRef.current = requestId\n setSearchQuery(query)\n\n const searchProvider = providesRef.current\n const scrollProvider = scrollRef.current\n\n if (!searchProvider) {\n setIsSearching(false)\n return\n }\n\n if (!query) {\n searchProvider.stopSearch()\n setIsSearching(false)\n return\n }\n\n setIsSearching(true)\n searchProvider.startSearch()\n searchProvider.searchAllPages(query).wait(\n (result) => {\n if (searchRequestIdRef.current !== requestId) return\n\n const firstResult = result.results[0]\n\n if (firstResult && scrollProvider) {\n searchProvider.goToResult(0)\n const firstRect = firstResult.rects[0]\n\n scrollProvider.scrollToPage({\n pageNumber: firstResult.pageIndex + 1,\n ...(firstRect\n ? {\n pageCoordinates: {\n x: firstRect.origin.x,\n y: firstRect.origin.y,\n },\n alignY: 30,\n }\n : {}),\n behavior: "auto",\n })\n }\n setIsSearching(false)\n },\n () => {\n if (searchRequestIdRef.current !== requestId) return\n setIsSearching(false)\n }\n )\n }, [])\n\n React.useEffect(() => {\n if (!searchDraft.trim()) return\n\n const timeoutId = window.setTimeout(() => {\n runSearch(searchDraft)\n }, PDF_SEARCH_DEBOUNCE_MS)\n\n return () => window.clearTimeout(timeoutId)\n }, [runSearch, searchDraft])\n\n const handleSearchDraftChange = React.useCallback(\n (event: React.ChangeEvent<HTMLInputElement>) => {\n const nextDraft = event.target.value\n\n setSearchDraft(nextDraft)\n\n if (nextDraft.trim()) {\n setIsSearching(true)\n return\n }\n\n searchRequestIdRef.current += 1\n setSearchQuery("")\n setIsSearching(false)\n provides?.stopSearch()\n },\n [provides]\n )\n\n const clearSearch = React.useCallback(() => {\n searchRequestIdRef.current += 1\n setSearchDraft("")\n setSearchQuery("")\n setIsSearching(false)\n provides?.stopSearch()\n }, [provides])\n\n const navigate = React.useCallback(\n (direction: 1 | -1) => {\n if (!provides || state.total === 0) return\n\n const index =\n direction === 1 ? provides.nextResult() : provides.previousResult()\n\n scrollToResult(index)\n },\n [provides, scrollToResult, state.total]\n )\n\n return (\n <Popover>\n <ToolbarTooltip label="Search text">\n <PopoverTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search text"\n disabled={controlsDisabled}\n >\n <HugeiconsIcon icon={Search01Icon} className="size-4" />\n </Button>\n </PopoverTrigger>\n </ToolbarTooltip>\n <PopoverContent align="end" className="w-72">\n <div className="space-y-3">\n <Input\n placeholder="Search text"\n value={searchDraft}\n onChange={handleSearchDraftChange}\n onKeyDown={(event) => {\n if (event.key !== "Enter") return\n\n event.preventDefault()\n if (event.shiftKey && state.total) {\n navigate(-1)\n } else if (state.total) {\n navigate(1)\n } else if (searchDraft.trim()) {\n runSearch(searchDraft)\n }\n }}\n />\n <div className="flex items-center justify-between gap-2">\n <div className="min-w-0 text-xs text-muted-foreground">\n <div className="truncate">\n {state.total ? (\n <>\n <span className="text-primary">\n {state.activeResultIndex + 1}\n </span>\n {` / ${state.total}`}\n </>\n ) : (\n resultLabel\n )}\n </div>\n </div>\n <div className="flex shrink-0 items-center gap-1">\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Previous result"\n disabled={isSearching || state.total === 0}\n onClick={() => navigate(-1)}\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4" />\n </Button>\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Next result"\n disabled={isSearching || state.total === 0}\n onClick={() => navigate(1)}\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-4" />\n </Button>\n </div>\n </div>\n <div className="flex justify-end">\n <Button\n type="button"\n variant="outline"\n size="sm"\n onClick={clearSearch}\n >\n Clear\n </Button>\n </div>\n </div>\n </PopoverContent>\n </Popover>\n )\n}\n\nfunction PDFViewerThumbnails({\n basePageRotations,\n documentId,\n activePage,\n pageCount,\n pageRotationDeltas,\n pdfDocument,\n selectedPageIndexes,\n onSelectPage,\n}: {\n basePageRotations: Rotation[]\n documentId: string\n activePage: number\n pageCount: number\n pageRotationDeltas: PageRotationDeltas\n pdfDocument: PdfDocumentObject | null\n selectedPageIndexes: Set<number>\n onSelectPage: (pageNumber: number, mode: ThumbnailSelectionMode) => void\n}) {\n const thumbnailListboxId = React.useId()\n const activeDescendantId =\n activePage > 0 ? `${thumbnailListboxId}-page-${activePage}` : undefined\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (pageCount < 1) return\n\n const currentPage = activePage > 0 ? activePage : 1\n let nextPage: number | null = null\n\n if (event.key === "ArrowDown") {\n nextPage = Math.min(pageCount, currentPage + 1)\n } else if (event.key === "ArrowUp") {\n nextPage = Math.max(1, currentPage - 1)\n } else if (event.key === "Home") {\n nextPage = 1\n } else if (event.key === "End") {\n nextPage = pageCount\n } else if (event.key === " ") {\n event.preventDefault()\n onSelectPage(currentPage, "toggle")\n return\n }\n\n if (nextPage === null) return\n\n event.preventDefault()\n onSelectPage(nextPage, event.shiftKey ? "range" : "replace")\n },\n [activePage, onSelectPage, pageCount]\n )\n\n return (\n <PDFViewerThumbnailScrollArea\n activeDescendantId={activeDescendantId}\n basePageRotations={basePageRotations}\n documentId={documentId}\n onKeyDown={handleKeyDown}\n pageRotationDeltas={pageRotationDeltas}\n pdfDocument={pdfDocument}\n >\n {(meta: ThumbMeta) => {\n const pageNumber = meta.pageIndex + 1\n const isActive = pageNumber === activePage\n const isSelected = selectedPageIndexes.has(meta.pageIndex)\n const imagePadding = meta.padding ?? 0\n const pageRotationDelta = pageRotationDeltas.get(meta.pageIndex) ?? 0\n const thumbnailImageStyle: React.CSSProperties =\n pageRotationDelta % 2 === 1\n ? {\n height: meta.width,\n transform: `rotate(${rotationToDegrees(pageRotationDelta)}deg)`,\n width: meta.height,\n }\n : {\n height: meta.height,\n transform:\n pageRotationDelta === 0\n ? undefined\n : `rotate(${rotationToDegrees(pageRotationDelta)}deg)`,\n width: meta.width,\n }\n\n return (\n <div\n key={meta.pageIndex}\n data-pdf-viewer-thumbnail={pageNumber}\n className={cn(\n "absolute right-0 left-0 flex justify-center",\n isActive && "z-10"\n )}\n style={{ top: meta.top, height: meta.wrapperHeight }}\n >\n <div\n id={`${thumbnailListboxId}-page-${pageNumber}`}\n role="option"\n data-pdf-viewer-thumbnail-option={pageNumber}\n aria-current={isActive ? "page" : undefined}\n aria-label={`Page ${pageNumber}`}\n aria-posinset={pageNumber}\n aria-selected={isSelected}\n aria-setsize={pageCount}\n data-selected={isSelected ? "" : undefined}\n className={cn(\n "flex h-full w-full cursor-default flex-col items-center justify-between rounded-md px-2 py-0 text-xs transition-shadow outline-none select-none hover:bg-sidebar-accent",\n isActive || isSelected\n ? "bg-sidebar-accent text-foreground"\n : "text-muted-foreground",\n isActive && THUMBNAIL_FOCUS_RING_CLASS\n )}\n onClick={(event) => {\n const mode = event.shiftKey\n ? "range"\n : event.metaKey || event.ctrlKey\n ? "toggle"\n : "replace"\n\n onSelectPage(pageNumber, mode)\n }}\n >\n <span\n className="mt-0 flex items-center justify-center overflow-hidden rounded-md bg-transparent"\n style={{\n width: meta.width + imagePadding * 2,\n height: meta.height + imagePadding * 2,\n padding: imagePadding,\n }}\n >\n <ThumbImg\n documentId={documentId}\n meta={meta}\n className="block rounded-sm object-contain"\n style={thumbnailImageStyle}\n />\n </span>\n <span\n className="flex items-center justify-center tabular-nums"\n style={{ height: meta.labelHeight }}\n >\n <span className="flex min-w-5 items-center justify-center px-1.5 text-center leading-5">\n {pageNumber}\n </span>\n </span>\n </div>\n </div>\n )\n }}\n </PDFViewerThumbnailScrollArea>\n )\n}\n\nfunction PDFViewerThumbnailScrollArea({\n activeDescendantId,\n basePageRotations,\n children,\n documentId,\n onKeyDown,\n pageRotationDeltas,\n pdfDocument,\n}: {\n activeDescendantId?: string\n basePageRotations: Rotation[]\n children: (meta: ThumbMeta) => React.ReactNode\n documentId: string\n onKeyDown: React.KeyboardEventHandler<HTMLDivElement>\n pageRotationDeltas: PageRotationDeltas\n pdfDocument: PdfDocumentObject | null\n}) {\n const { plugin: thumbnailPlugin } = useThumbnailPlugin()\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewportMetrics, setViewportMetrics] = React.useState({\n clientHeight: 0,\n scrollTop: 0,\n })\n const thumbnailScope = React.useMemo(\n () => thumbnailPlugin?.provides().forDocument(documentId) ?? null,\n [documentId, thumbnailPlugin]\n )\n\n const windowState = React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) => {\n if (!thumbnailScope) return () => undefined\n\n return thumbnailScope.onWindow(() => onStoreChange())\n },\n [thumbnailScope]\n ),\n React.useCallback(\n () => thumbnailScope?.getWindow() ?? null,\n [thumbnailScope]\n ),\n () => null\n )\n const hasWindowState = Boolean(windowState)\n const paddingY = thumbnailPlugin?.cfg.paddingY ?? 0\n const thumbnailLayout = React.useMemo(\n () =>\n buildThumbnailLayout({\n basePageRotations,\n pageRotationDeltas,\n pdfDocument,\n width: thumbnailPlugin?.cfg.width ?? THUMBNAIL_WIDTH,\n gap: thumbnailPlugin?.cfg.gap ?? THUMBNAIL_GAP,\n imagePadding: thumbnailPlugin?.cfg.imagePadding ?? 0,\n labelHeight: thumbnailPlugin?.cfg.labelHeight ?? THUMBNAIL_LABEL_HEIGHT,\n paddingY,\n }),\n [\n basePageRotations,\n pageRotationDeltas,\n pdfDocument,\n paddingY,\n thumbnailPlugin,\n ]\n )\n const effectiveWindowState = React.useMemo(() => {\n if (!thumbnailLayout) return windowState\n\n const items = getVisibleThumbnailItems({\n buffer: thumbnailPlugin?.cfg.buffer ?? 3,\n clientHeight: viewportMetrics.clientHeight,\n items: thumbnailLayout.items,\n scrollTop: viewportMetrics.scrollTop,\n })\n\n return {\n start: items[0]?.pageIndex ?? -1,\n end: items.at(-1)?.pageIndex ?? -1,\n items,\n totalHeight: thumbnailLayout.totalHeight,\n }\n }, [thumbnailLayout, thumbnailPlugin, viewportMetrics, windowState])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope) return\n\n const updateWindow = () => {\n setViewportMetrics({\n clientHeight: viewport.clientHeight,\n scrollTop: viewport.scrollTop,\n })\n thumbnailScope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n }\n\n viewport.addEventListener("scroll", updateWindow)\n const frame = window.requestAnimationFrame(updateWindow)\n\n return () => {\n window.cancelAnimationFrame(frame)\n viewport.removeEventListener("scroll", updateWindow)\n }\n }, [thumbnailScope])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope) return\n\n const resizeObserver = new ResizeObserver(() => {\n setViewportMetrics({\n clientHeight: viewport.clientHeight,\n scrollTop: viewport.scrollTop,\n })\n thumbnailScope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n })\n\n resizeObserver.observe(viewport)\n\n return () => resizeObserver.disconnect()\n }, [thumbnailScope])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope) return\n\n thumbnailScope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n }, [thumbnailLayout, thumbnailScope, windowState])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope || !hasWindowState) return\n\n return thumbnailScope.onScrollTo(({ top, behavior }) => {\n viewport.scrollTo({ top, behavior })\n })\n }, [hasWindowState, thumbnailScope])\n\n return (\n <ScrollArea\n className="h-full w-full"\n orientation="vertical"\n scrollFade\n viewportClassName="group/pdf-thumbnail-sidebar px-4 focus-visible:ring-0 focus-visible:ring-offset-0"\n viewportProps={{\n "aria-activedescendant": activeDescendantId,\n "aria-label": "PDF pages",\n "aria-multiselectable": true,\n onKeyDown,\n onMouseDown: (event) => {\n event.currentTarget.focus({ preventScroll: true })\n },\n role: "listbox",\n style: {\n paddingBottom: paddingY,\n paddingTop: paddingY,\n },\n tabIndex: 0,\n }}\n viewportRef={viewportRef}\n >\n <div\n className="relative"\n style={{ height: effectiveWindowState?.totalHeight ?? 0 }}\n >\n {effectiveWindowState?.items.map((meta) => children(meta))}\n </div>\n </ScrollArea>\n )\n}\n\nfunction PDFViewerScrollAreaViewport({\n children,\n className,\n documentId,\n}: {\n children: React.ReactNode\n className?: string\n documentId: string\n}) {\n const viewportRef = useViewportRef(documentId)\n const { provides: viewport } = useViewportCapability()\n const isGated = useIsViewportGated(documentId)\n const viewportGap = viewport?.getViewportGap() ?? 0\n\n return (\n <ViewportElementContext.Provider value={viewportRef}>\n <ScrollArea\n className={className}\n orientation="both"\n viewportClassName="relative select-none selection:bg-transparent selection:text-inherit"\n viewportProps={{\n style: {\n padding: viewportGap,\n },\n }}\n viewportRef={viewportRef}\n >\n {isGated ? null : children}\n </ScrollArea>\n </ViewportElementContext.Provider>\n )\n}\n\n// Captures the scrollable viewport element so the imperative handle can expose\n// it.\nfunction PDFViewerViewportBridge({\n viewportElementRef,\n}: {\n viewportElementRef: React.MutableRefObject<HTMLDivElement | null>\n}) {\n const elementRef = useViewportElement()\n\n React.useEffect(() => {\n viewportElementRef.current = elementRef?.current ?? null\n })\n\n return null\n}\n\nfunction PDFViewerTextSelectionLayer({\n documentId,\n pageIndex,\n scale,\n}: {\n documentId: string\n pageIndex: number\n scale: number\n}) {\n const { plugin: selectionPlugin } = useSelectionPlugin()\n const [rects, setRects] = React.useState<Rect[]>([])\n\n React.useEffect(() => {\n if (!selectionPlugin) return\n\n return selectionPlugin.registerSelectionOnPage({\n documentId,\n pageIndex,\n onRectsChange: ({ rects: nextRects }) => {\n setRects(nextRects)\n },\n })\n }, [documentId, pageIndex, selectionPlugin])\n\n if (!rects.length) return null\n\n return (\n <>\n {rects.map((rect, index) => (\n <div\n key={`${index}-${rect.origin.x}-${rect.origin.y}`}\n className="pointer-events-none absolute"\n style={{\n background: TEXT_SELECTION_BACKGROUND,\n height: rect.size.height * scale,\n left: rect.origin.x * scale,\n top: rect.origin.y * scale,\n width: rect.size.width * scale,\n }}\n />\n ))}\n </>\n )\n}\n\nfunction PDFViewerSelectionReleaseGuard({\n documentId,\n}: {\n documentId: string\n}) {\n const { plugin: selectionPlugin } = useSelectionPlugin()\n const { provides: selection } = useSelectionCapability()\n const lastSelectionModeIdRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n if (!selection) return\n\n return selection.forDocument(documentId).onBeginSelection(({ modeId }) => {\n lastSelectionModeIdRef.current = modeId\n })\n }, [documentId, selection])\n\n React.useEffect(() => {\n if (!selection) return\n\n let cleanupFrame = 0\n const finalizeIfStillSelecting = () => {\n window.cancelAnimationFrame(cleanupFrame)\n cleanupFrame = window.requestAnimationFrame(() => {\n const selectionState = selection.getState(documentId)\n\n if (!selectionState.selecting) return\n\n if (selectionState.selection && selectionPlugin) {\n const pluginWithEndSelection = selectionPlugin as unknown as {\n endSelection?: (documentId: string, modeId: string) => void\n }\n\n pluginWithEndSelection.endSelection?.(\n documentId,\n lastSelectionModeIdRef.current ?? "pointerMode"\n )\n return\n }\n\n if (!selectionState.selection) {\n selection.clear(documentId)\n }\n })\n }\n\n window.addEventListener("pointerup", finalizeIfStillSelecting)\n window.addEventListener("pointercancel", finalizeIfStillSelecting)\n window.addEventListener("blur", finalizeIfStillSelecting)\n\n return () => {\n window.cancelAnimationFrame(cleanupFrame)\n window.removeEventListener("pointerup", finalizeIfStillSelecting)\n window.removeEventListener("pointercancel", finalizeIfStillSelecting)\n window.removeEventListener("blur", finalizeIfStillSelecting)\n }\n }, [documentId, selection, selectionPlugin])\n\n return null\n}\n\nfunction isEditableCopyTarget(target: EventTarget | null) {\n if (!(target instanceof HTMLElement)) return false\n\n if (target.isContentEditable) return true\n\n return Boolean(target.closest("input, textarea, [contenteditable=\'true\']"))\n}\n\nfunction PDFViewerSelectionCopyShortcut({\n documentId,\n}: {\n documentId: string\n}) {\n const { provides: selection } = useSelectionCapability()\n\n React.useEffect(() => {\n if (!selection) return\n\n const copySelectedPdfText = (event: Event) => {\n if (isEditableCopyTarget(event.target)) return\n if (!selection.getState(documentId).selection) return\n\n event.preventDefault()\n selection.copyToClipboard(documentId)\n }\n\n const handleKeyDown = (event: KeyboardEvent) => {\n if (event.key.toLowerCase() !== "c") return\n if (!event.metaKey && !event.ctrlKey) return\n\n copySelectedPdfText(event)\n }\n\n document.addEventListener("copy", copySelectedPdfText)\n document.addEventListener("keydown", handleKeyDown)\n\n return () => {\n document.removeEventListener("copy", copySelectedPdfText)\n document.removeEventListener("keydown", handleKeyDown)\n }\n }, [documentId, selection])\n\n return null\n}\n\nfunction isQuarterTurn(rotation: Rotation) {\n return rotation % 2 === 1\n}\n\nfunction getRotatedDimensions({\n height,\n rotation,\n width,\n}: {\n height: number\n rotation: Rotation\n width: number\n}) {\n return isQuarterTurn(rotation)\n ? { height: width, width: height }\n : { height, width }\n}\n\nfunction getRotatedPageDimensions(page: PageLayout, rotation: Rotation) {\n return getRotatedDimensions({\n height: page.height,\n rotation,\n width: page.width,\n })\n}\n\nfunction applyPageRotationDeltasToScrollerLayout({\n basePageRotations,\n layout,\n pageRotationDeltas,\n}: {\n basePageRotations: Rotation[]\n layout: ScrollerLayout\n pageRotationDeltas: PageRotationDeltas\n}): ScrollerLayout {\n if (pageRotationDeltas.size === 0) return layout\n\n let maxWidth = 0\n let maxHeight = 0\n let offset = 0\n const pageGap = layout.pageGap\n let startSpacingAdjustment = 0\n const items: VirtualItem[] = layout.items.map((item, itemIndex) => {\n let pageOffset = 0\n let itemWidth = 0\n let itemHeight = 0\n const pageLayouts = item.pageLayouts.map((page) => {\n const basePageRotation =\n basePageRotations[page.pageIndex] ?? normalizeRotation(0)\n const pageRotation = normalizeRotation(\n basePageRotation + (pageRotationDeltas.get(page.pageIndex) ?? 0)\n )\n const rotatedSize = getRotatedPageDimensions(page, pageRotation)\n const oldScrollAxisSize =\n layout.strategy === ScrollStrategy.Horizontal\n ? page.rotatedWidth\n : page.rotatedHeight\n const newScrollAxisSize =\n layout.strategy === ScrollStrategy.Horizontal\n ? rotatedSize.width\n : rotatedSize.height\n\n if (\n layout.startSpacing === 0 &&\n itemIndex === 0 &&\n pageOffset === 0 &&\n newScrollAxisSize < oldScrollAxisSize\n ) {\n startSpacingAdjustment = Math.max(\n startSpacingAdjustment,\n (oldScrollAxisSize - newScrollAxisSize) / 2\n )\n }\n\n const nextPageLayout = {\n ...page,\n rotatedHeight: rotatedSize.height,\n rotatedWidth: rotatedSize.width,\n x: layout.strategy === ScrollStrategy.Horizontal ? 0 : pageOffset,\n y: layout.strategy === ScrollStrategy.Horizontal ? pageOffset : 0,\n }\n\n pageOffset +=\n (layout.strategy === ScrollStrategy.Horizontal\n ? rotatedSize.height\n : rotatedSize.width) + pageGap\n itemWidth =\n layout.strategy === ScrollStrategy.Horizontal\n ? Math.max(itemWidth, rotatedSize.width)\n : itemWidth + rotatedSize.width\n itemHeight =\n layout.strategy === ScrollStrategy.Horizontal\n ? itemHeight + rotatedSize.height\n : Math.max(itemHeight, rotatedSize.height)\n\n return nextPageLayout\n })\n\n if (pageLayouts.length > 1) {\n if (layout.strategy === ScrollStrategy.Horizontal) {\n itemHeight -= pageGap\n } else {\n itemWidth -= pageGap\n }\n }\n\n const nextItem = {\n ...item,\n height: itemHeight,\n offset,\n pageLayouts,\n width: itemWidth,\n x: layout.strategy === ScrollStrategy.Horizontal ? offset : item.x,\n y: layout.strategy === ScrollStrategy.Horizontal ? item.y : offset,\n }\n\n if (layout.strategy === ScrollStrategy.Horizontal) {\n offset += itemWidth + pageGap\n maxHeight = Math.max(maxHeight, itemHeight)\n } else {\n offset += itemHeight + pageGap\n maxWidth = Math.max(maxWidth, itemWidth)\n }\n\n return nextItem\n })\n\n if (items.length > 0) {\n offset -= pageGap\n }\n\n return {\n ...layout,\n endSpacing: layout.endSpacing,\n items,\n startSpacing: layout.startSpacing + startSpacingAdjustment,\n totalHeight:\n layout.strategy === ScrollStrategy.Horizontal\n ? maxHeight\n : layout.startSpacing +\n startSpacingAdjustment +\n offset +\n layout.endSpacing,\n totalWidth:\n layout.strategy === ScrollStrategy.Horizontal\n ? layout.startSpacing +\n startSpacingAdjustment +\n offset +\n layout.endSpacing\n : maxWidth,\n }\n}\n\nfunction PDFViewerScroller({\n documentId,\n pageRotationDeltas,\n basePageRotations,\n renderPage,\n}: {\n documentId: string\n pageRotationDeltas: PageRotationDeltas\n basePageRotations: Rotation[]\n renderPage: (props: PageLayout) => React.ReactNode\n}) {\n const { plugin: scrollPlugin } = useScrollPlugin()\n const [layoutData, setLayoutData] = React.useState<{\n docId: string | null\n layout: ScrollerLayout | null\n }>({ docId: null, layout: null })\n\n React.useEffect(() => {\n if (!scrollPlugin || !documentId) return\n let frame = 0\n\n const setCurrentLayout = () => {\n try {\n setLayoutData({\n docId: documentId,\n layout: scrollPlugin.getScrollerLayout(documentId),\n })\n } catch {\n setLayoutData({ docId: documentId, layout: null })\n }\n }\n\n const unsubscribe = scrollPlugin.onScrollerData(documentId, (layout) => {\n setLayoutData({ docId: documentId, layout })\n })\n\n frame = window.requestAnimationFrame(setCurrentLayout)\n\n return () => {\n window.cancelAnimationFrame(frame)\n unsubscribe()\n setLayoutData({ docId: null, layout: null })\n scrollPlugin.clearLayoutReady(documentId)\n }\n }, [documentId, scrollPlugin])\n\n const scrollerLayout = React.useMemo(() => {\n if (layoutData.docId !== documentId || !layoutData.layout) return null\n\n return applyPageRotationDeltasToScrollerLayout({\n basePageRotations,\n layout: layoutData.layout,\n pageRotationDeltas,\n })\n }, [basePageRotations, documentId, layoutData, pageRotationDeltas])\n\n React.useLayoutEffect(() => {\n if (!scrollPlugin || !documentId || !scrollerLayout) return\n scrollPlugin.setLayoutReady(documentId)\n }, [documentId, scrollPlugin, scrollerLayout])\n\n if (!scrollerLayout) return null\n\n return (\n <div\n style={{\n width: `${scrollerLayout.totalWidth}px`,\n height: `${scrollerLayout.totalHeight}px`,\n position: "relative",\n boxSizing: "border-box",\n margin: "0 auto",\n ...(scrollerLayout.strategy === ScrollStrategy.Horizontal && {\n display: "flex",\n flexDirection: "row",\n }),\n }}\n >\n <div\n style={\n scrollerLayout.strategy === ScrollStrategy.Horizontal\n ? {\n width: scrollerLayout.startSpacing,\n height: "100%",\n flexShrink: 0,\n }\n : {\n height: scrollerLayout.startSpacing,\n width: "100%",\n }\n }\n />\n <div\n style={{\n gap: scrollerLayout.pageGap,\n display: "flex",\n alignItems: "center",\n position: "relative",\n boxSizing: "border-box",\n ...(scrollerLayout.strategy === ScrollStrategy.Horizontal\n ? {\n flexDirection: "row",\n minHeight: "100%",\n }\n : {\n flexDirection: "column",\n minWidth: "fit-content",\n }),\n }}\n >\n {scrollerLayout.items.map((item) => (\n <div\n key={item.pageNumbers[0]}\n style={{\n display: "flex",\n justifyContent: "center",\n gap: scrollerLayout.pageGap,\n }}\n >\n {item.pageLayouts.map((layout) => (\n <div\n key={layout.pageNumber}\n style={{\n width: `${layout.rotatedWidth}px`,\n height: `${layout.rotatedHeight}px`,\n position: "relative",\n zIndex: layout.elevated ? 1 : undefined,\n }}\n >\n {renderPage(layout)}\n </div>\n ))}\n </div>\n ))}\n </div>\n <div\n style={\n scrollerLayout.strategy === ScrollStrategy.Horizontal\n ? {\n width: scrollerLayout.endSpacing,\n height: "100%",\n flexShrink: 0,\n }\n : {\n height: scrollerLayout.endSpacing,\n width: "100%",\n }\n }\n />\n </div>\n )\n}\n\ntype PDFViewerInnerProps = {\n viewerRef: React.ForwardedRef<PDFViewerHandle>\n pdfFile: string\n documentId: string\n document: PdfDocumentObject | null\n defaultZoom: number\n className?: string\n fileName?: string\n showDownload: boolean\n showToolbar: boolean\n showRotateControls: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onActivePageChange?: (pageNumber: number) => void\n onPdfUpload?: (file: File) => void\n onPagePointerDown?: PDFViewerProps["onPagePointerDown"]\n onPagePointerMove?: PDFViewerProps["onPagePointerMove"]\n onPagePointerUp?: PDFViewerProps["onPagePointerUp"]\n onPagePointerCancel?: PDFViewerProps["onPagePointerCancel"]\n onUploadFile: (file: File) => void\n}\n\nfunction PDFViewerInner({\n viewerRef,\n pdfFile,\n documentId,\n document: pdfDocument,\n defaultZoom,\n className,\n fileName,\n showDownload,\n showToolbar,\n showRotateControls,\n showUpload,\n toolbarActions,\n pageClassName,\n renderPageOverlay,\n onActivePageChange,\n onPdfUpload,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n onUploadFile,\n}: PDFViewerInnerProps) {\n const { registry } = useRegistry()\n const { state: scrollState, provides: scroll } = useScroll(documentId)\n const { state: zoomState, provides: zoom } = useZoom(documentId)\n const { provides: thumbnails } = useThumbnailCapability()\n const { plugin: thumbnailPlugin } = useThumbnailPlugin()\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)\n const [pageRotationDeltas, setPageRotationDeltas] =\n React.useState<PageRotationDeltas>(() => new Map())\n const [selectedPageIndexes, setSelectedPageIndexes] = React.useState<\n Set<number>\n >(() => new Set())\n const basePageRotations = React.useMemo(\n () =>\n pdfDocument?.pages.map((page) => normalizeRotation(page.rotation)) ?? [],\n [pdfDocument]\n )\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const viewportElementRef = React.useRef<HTMLDivElement | null>(null)\n const pageRotationDeltasRef = React.useRef(pageRotationDeltas)\n const selectedPageIndexesRef = React.useRef(selectedPageIndexes)\n const selectionAnchorPageIndexRef = React.useRef<number | null>(null)\n const suppressActivePageSelectionSyncRef = React.useRef<number | null>(null)\n const initializedSelectionDocumentRef = React.useRef<string | null>(null)\n\n const activePage = scrollState.currentPage\n const numPages = pdfDocument?.pageCount ?? 0\n const isLoading = !pdfDocument\n const controlsDisabled = !numPages\n const downloadDisabled = controlsDisabled || isPreparingDownload\n const thumbnailSidebarVisible = sidebarOpen && !isLoading\n const currentZoomLevel = zoomState.currentZoomLevel\n const alignedThumbnailSidebarDocumentRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n pageRotationDeltasRef.current = pageRotationDeltas\n }, [pageRotationDeltas])\n\n React.useEffect(() => {\n selectedPageIndexesRef.current = selectedPageIndexes\n }, [selectedPageIndexes])\n\n React.useEffect(() => {\n if (activePage > 0) onActivePageChange?.(activePage)\n }, [activePage, onActivePageChange])\n\n React.useEffect(() => {\n if (activePage < 1 || numPages < 1) return\n\n const activePageIndex = activePage - 1\n const suppressedPageIndex = suppressActivePageSelectionSyncRef.current\n\n suppressActivePageSelectionSyncRef.current = null\n\n if (suppressedPageIndex === activePageIndex) return\n\n const nextSelection = new Set([activePageIndex])\n\n selectionAnchorPageIndexRef.current = activePageIndex\n selectedPageIndexesRef.current = nextSelection\n setSelectedPageIndexes((previousSelection) =>\n arePageIndexSetsEqual(previousSelection, nextSelection)\n ? previousSelection\n : nextSelection\n )\n }, [activePage, numPages])\n\n React.useEffect(() => {\n if (\n numPages < 1 ||\n initializedSelectionDocumentRef.current === documentId\n ) {\n return\n }\n\n const initialPageIndex = Math.max(0, (activePage > 0 ? activePage : 1) - 1)\n const initialSelection = new Set([initialPageIndex])\n\n initializedSelectionDocumentRef.current = documentId\n selectionAnchorPageIndexRef.current = initialPageIndex\n selectedPageIndexesRef.current = initialSelection\n setSelectedPageIndexes(initialSelection)\n }, [activePage, documentId, numPages])\n\n React.useEffect(() => {\n if (!thumbnailSidebarVisible) {\n alignedThumbnailSidebarDocumentRef.current = null\n return\n }\n\n if (\n activePage < 1 ||\n !thumbnails ||\n alignedThumbnailSidebarDocumentRef.current === documentId\n ) {\n return\n }\n\n alignedThumbnailSidebarDocumentRef.current = documentId\n const frame = window.requestAnimationFrame(() => {\n thumbnails.forDocument(documentId).scrollToThumb(activePage - 1)\n })\n\n return () => window.cancelAnimationFrame(frame)\n }, [activePage, documentId, thumbnailSidebarVisible, thumbnails])\n\n // The zoom plugin only releases its viewport gate for mode-based zoom\n // levels (automatic/fit); with a numeric default the gate would never\n // lift, so apply the initial zoom explicitly once the document loads.\n const initialZoomDocumentRef = React.useRef<string | null>(null)\n React.useEffect(() => {\n if (!pdfDocument || !zoom) return\n if (initialZoomDocumentRef.current === documentId) return\n\n initialZoomDocumentRef.current = documentId\n zoom.requestZoom(defaultZoom)\n }, [defaultZoom, documentId, pdfDocument, zoom])\n\n const scrollToPage = React.useCallback(\n (pageNumber: number, options?: ScrollIntoViewOptions) => {\n scroll?.scrollToPage({\n pageNumber,\n behavior: options?.behavior === "smooth" ? "smooth" : "auto",\n })\n },\n [scroll]\n )\n\n const selectThumbnailPage = React.useCallback(\n (pageNumber: number, mode: ThumbnailSelectionMode) => {\n const pageIndex = pageNumber - 1\n\n if (pageIndex < 0 || pageIndex >= numPages) return\n\n suppressActivePageSelectionSyncRef.current = pageIndex\n\n setSelectedPageIndexes((previousSelection) => {\n let nextSelection: Set<number>\n\n if (mode === "range") {\n const anchorPageIndex =\n selectionAnchorPageIndexRef.current ??\n (activePage > 0 ? activePage - 1 : pageIndex)\n\n nextSelection = getPageIndexRange(anchorPageIndex, pageIndex)\n } else if (mode === "toggle") {\n nextSelection = new Set(previousSelection)\n\n if (nextSelection.has(pageIndex)) {\n nextSelection.delete(pageIndex)\n } else {\n nextSelection.add(pageIndex)\n }\n\n selectionAnchorPageIndexRef.current = pageIndex\n } else {\n nextSelection = new Set([pageIndex])\n selectionAnchorPageIndexRef.current = pageIndex\n }\n\n selectedPageIndexesRef.current = nextSelection\n return nextSelection\n })\n\n scrollToPage(pageNumber)\n },\n [activePage, numPages, scrollToPage]\n )\n\n React.useImperativeHandle(\n viewerRef,\n () => ({\n scrollToPage,\n scrollToPageArea: (pageNumber, area, options) => {\n const pageSize = pdfDocument?.pages[pageNumber - 1]?.size\n\n scroll?.scrollToPage({\n pageNumber,\n ...(pageSize\n ? {\n pageCoordinates: {\n x: ((area.left ?? 0) / 100) * pageSize.width,\n y: (area.top / 100) * pageSize.height,\n },\n alignY: 25,\n }\n : {}),\n behavior: options?.behavior === "smooth" ? "smooth" : "auto",\n })\n },\n getViewportElement: () => viewportElementRef.current,\n }),\n [pdfDocument, scroll, scrollToPage]\n )\n\n const handleDownload = React.useCallback(async () => {\n if (!pdfFile || isPreparingDownload) return\n\n setIsPreparingDownload(true)\n\n try {\n await downloadPdfWithPageRotations({\n fileName: getPdfDownloadFileName(fileName, pdfFile),\n pageRotationDeltas,\n src: pdfFile,\n })\n } catch (error) {\n console.error(error)\n } finally {\n setIsPreparingDownload(false)\n }\n }, [fileName, isPreparingDownload, pageRotationDeltas, pdfFile])\n\n const rotateSelectedPages = React.useCallback(\n (direction: -1 | 1) => {\n if (!pdfDocument || !registry || activePage < 1) return\n\n const documentState = registry.getStore().getState().core.documents[\n documentId\n ]\n const currentDocument = documentState?.document ?? pdfDocument\n const selectedTargetPageIndexes = Array.from(\n selectedPageIndexesRef.current\n ).filter((pageIndex) => currentDocument.pages[pageIndex])\n const fallbackPageIndex = activePage - 1\n const targetPageIndexes = (\n selectedTargetPageIndexes.length\n ? selectedTargetPageIndexes\n : [fallbackPageIndex]\n )\n .filter((pageIndex) => currentDocument.pages[pageIndex])\n .sort((a, b) => a - b)\n\n if (targetPageIndexes.length === 0) return\n\n const previousDeltas = pageRotationDeltasRef.current\n const nextDeltas = new Map(previousDeltas)\n const referencePageIndex =\n activePage > 0 && currentDocument.pages[activePage - 1]\n ? activePage - 1\n : targetPageIndexes[0]\n let scrollDelta = 0\n\n for (const pageIndex of targetPageIndexes) {\n const currentPage = currentDocument.pages[pageIndex]\n if (!currentPage) continue\n\n const previousDelta = previousDeltas.get(pageIndex) ?? 0\n const nextDelta = normalizeRotation(previousDelta + direction)\n const basePageRotation =\n basePageRotations[pageIndex] ??\n normalizeRotation(currentPage.rotation)\n const previousPageRotation = normalizeRotation(\n basePageRotation + previousDelta\n )\n const nextPageRotation = normalizeRotation(basePageRotation + nextDelta)\n const previousRotatedSize = getRotatedDimensions({\n height: currentPage.size.height * currentZoomLevel,\n rotation: previousPageRotation,\n width: currentPage.size.width * currentZoomLevel,\n })\n const nextRotatedSize = getRotatedDimensions({\n height: currentPage.size.height * currentZoomLevel,\n rotation: nextPageRotation,\n width: currentPage.size.width * currentZoomLevel,\n })\n const heightDelta = nextRotatedSize.height - previousRotatedSize.height\n\n if (pageIndex < referencePageIndex) {\n scrollDelta += heightDelta\n } else if (pageIndex === referencePageIndex) {\n scrollDelta += heightDelta / 2\n }\n\n if (nextDelta) {\n nextDeltas.set(pageIndex, nextDelta)\n } else {\n nextDeltas.delete(pageIndex)\n }\n }\n\n const store = registry.getStore()\n const viewport = viewportElementRef.current\n\n pageRotationDeltasRef.current = nextDeltas\n flushSync(() => {\n setPageRotationDeltas(nextDeltas)\n store.dispatchToCore(refreshPages(documentId, targetPageIndexes))\n })\n\n if (viewport && scrollDelta !== 0) {\n viewport.scrollTop += scrollDelta\n }\n ;(\n thumbnailPlugin as {\n calculateWindowState?: (documentId: string) => void\n } | null\n )?.calculateWindowState?.(documentId)\n },\n [\n activePage,\n basePageRotations,\n currentZoomLevel,\n documentId,\n pdfDocument,\n registry,\n thumbnailPlugin,\n ]\n )\n\n const handleUpload = React.useCallback(\n (file: File) => {\n onUploadFile(file)\n onPdfUpload?.(file)\n },\n [onPdfUpload, onUploadFile]\n )\n\n const renderPage = React.useCallback(\n (page: PageLayout) => {\n const pageNumber = page.pageNumber\n const basePageRotation =\n basePageRotations[page.pageIndex] ??\n pdfDocument?.pages[page.pageIndex]?.rotation ??\n normalizeRotation(0)\n const pageRotation = normalizeRotation(\n basePageRotation + (pageRotationDeltas.get(page.pageIndex) ?? 0)\n )\n\n return (\n <Rotate\n documentId={documentId}\n pageIndex={page.pageIndex}\n rotation={pageRotation}\n >\n <PagePointerProvider\n documentId={documentId}\n pageIndex={page.pageIndex}\n rotation={pageRotation}\n key={`${page.pageIndex}-${pageRotation}`}\n data-pdf-viewer-page={pageNumber}\n className={cn(\n "relative border border-transparent bg-transparent shadow-xs select-none selection:bg-transparent selection:text-inherit",\n pageClassName?.(pageNumber)\n )}\n style={{ backgroundColor: "transparent" }}\n onPointerDown={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerDown?.(event, pageNumber)\n }\n onPointerMove={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerMove?.(event, pageNumber)\n }\n onPointerUp={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerUp?.(event, pageNumber)\n }\n onPointerCancel={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerCancel?.(event, pageNumber)\n }\n >\n <div\n aria-hidden="true"\n className="pointer-events-none absolute inset-0 bg-white"\n />\n <RenderLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n scale={Math.min(currentZoomLevel, PAGE_BASE_RENDER_MAX_SCALE)}\n dpr={PAGE_BASE_RENDER_DPR}\n className="pointer-events-none absolute inset-0 h-full w-full object-fill opacity-100 blur-[0.35px] transition-none"\n />\n <TilingLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n key={`tiles-${page.pageIndex}-${pageRotation}`}\n className="pointer-events-none opacity-100 transition-none [&_img]:opacity-100 [&_img]:transition-none"\n />\n <SearchLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n className="pointer-events-none"\n highlightColor="rgba(253, 224, 71, 0.45)"\n activeHighlightColor="rgba(249, 115, 22, 0.55)"\n />\n <PDFViewerTextSelectionLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n scale={currentZoomLevel}\n />\n {renderPageOverlay?.({\n pageNumber,\n pageWidth: page.width,\n pageHeight: page.height,\n scale: currentZoomLevel,\n rotation: rotationToDegrees(pageRotation),\n })}\n </PagePointerProvider>\n </Rotate>\n )\n },\n [\n basePageRotations,\n currentZoomLevel,\n onPagePointerCancel,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n pageClassName,\n pageRotationDeltas,\n renderPageOverlay,\n documentId,\n pdfDocument,\n ]\n )\n\n return (\n <div\n data-slot="pdf-viewer"\n className={cn(\n "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n {showToolbar ? (\n <div className="flex min-h-12 flex-wrap items-center justify-between gap-2 border-b bg-background px-3 py-2">\n <div className="flex min-w-0 flex-wrap items-center gap-2">\n <TooltipProvider>\n <ToolbarTooltip label="Toggle thumbnails">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Toggle thumbnails"\n disabled={controlsDisabled}\n onClick={() => setSidebarOpen((open) => !open)}\n >\n <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </TooltipProvider>\n <PDFViewerPageNumberControl\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n numPages={numPages}\n onPageChange={scrollToPage}\n />\n </div>\n <TooltipProvider>\n <div className="flex min-w-0 flex-wrap items-center justify-end gap-1">\n {showRotateControls ? (\n <>\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Rotate counterclockwise">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Rotate counterclockwise"\n disabled={controlsDisabled}\n onClick={() => rotateSelectedPages(-1)}\n >\n <HugeiconsIcon\n icon={RotateClockwiseIcon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Rotate clockwise">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Rotate clockwise"\n disabled={controlsDisabled}\n onClick={() => rotateSelectedPages(1)}\n >\n <HugeiconsIcon\n icon={RotateClockwiseIcon}\n className="size-4 -scale-x-100"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom out"\n disabled={\n controlsDisabled || currentZoomLevel <= ZOOM_OPTIONS[0]\n }\n onClick={() => {\n const nextZoom = [...ZOOM_OPTIONS]\n .reverse()\n .find((option) => option < currentZoomLevel)\n\n zoom?.requestZoom(nextZoom ?? ZOOM_OPTIONS[0])\n }}\n >\n <HugeiconsIcon\n icon={MinusSignCircleIcon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={String(currentZoomLevel)}\n onValueChange={(value) => zoom?.requestZoom(Number(value))}\n disabled={controlsDisabled}\n modal={false}\n >\n <SelectTrigger size="sm" className="w-[84px] min-w-[84px]">\n <SelectValue placeholder="Zoom">\n {Math.round(currentZoomLevel * 100)}%\n </SelectValue>\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((option) => (\n <SelectItem key={option} value={String(option)}>\n {Math.round(option * 100)}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom in"\n disabled={\n controlsDisabled ||\n currentZoomLevel >= ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n }\n onClick={() => {\n const nextZoom = ZOOM_OPTIONS.find(\n (option) => option > currentZoomLevel\n )\n\n zoom?.requestZoom(\n nextZoom ?? ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n )\n }}\n >\n <HugeiconsIcon\n icon={PlusSignCircleIcon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <PDFViewerSearchControl\n key={documentId}\n documentId={documentId}\n controlsDisabled={controlsDisabled}\n />\n {toolbarActions ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {toolbarActions}\n </>\n ) : null}\n {showDownload || showUpload ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <PDFViewerFileActionsMenu\n downloadDisabled={downloadDisabled}\n isPreparingDownload={isPreparingDownload}\n onDownload={handleDownload}\n onUploadFile={handleUpload}\n showDownload={showDownload}\n showUpload={showUpload}\n />\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\n ) : null}\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {isLoading ? (\n <PDFViewerLoadingSkeleton\n sidebarInline={sidebarInline}\n sidebarOpen={sidebarOpen}\n />\n ) : null}\n <div className="flex h-full max-h-full min-h-0 w-full flex-1 overflow-hidden">\n <DocumentViewerThumbnailSidebar\n closedInlineClassName={THUMBNAIL_SIDEBAR_CLOSED_CLASS}\n inline={sidebarInline}\n open={thumbnailSidebarVisible}\n widthClassName={THUMBNAIL_SIDEBAR_WIDTH_CLASS}\n >\n {thumbnailSidebarVisible ? (\n <PDFViewerThumbnails\n basePageRotations={basePageRotations}\n documentId={documentId}\n activePage={activePage}\n pageCount={numPages}\n pageRotationDeltas={pageRotationDeltas}\n pdfDocument={pdfDocument}\n selectedPageIndexes={selectedPageIndexes}\n onSelectPage={selectThumbnailPage}\n />\n ) : null}\n </DocumentViewerThumbnailSidebar>\n <PDFViewerScrollAreaViewport\n documentId={documentId}\n className="relative h-full max-h-full min-h-0 min-w-0 flex-1"\n >\n <PDFViewerViewportBridge viewportElementRef={viewportElementRef} />\n <PDFViewerSelectionCopyShortcut documentId={documentId} />\n <PDFViewerSelectionReleaseGuard documentId={documentId} />\n <GlobalPointerProvider documentId={documentId}>\n <PDFViewerScroller\n basePageRotations={basePageRotations}\n documentId={documentId}\n pageRotationDeltas={pageRotationDeltas}\n renderPage={renderPage}\n />\n </GlobalPointerProvider>\n <CopyToClipboard />\n </PDFViewerScrollAreaViewport>\n </div>\n </div>\n </div>\n )\n}\n\nfunction PDFViewerDocumentLoader({\n pdfFile,\n onDocumentLoadSuccess,\n ...innerProps\n}: {\n pdfFile: string\n onDocumentLoadSuccess?: (numPages: number) => void\n} & Omit<PDFViewerInnerProps, "pdfFile" | "documentId" | "document">) {\n const { provides: documentManager } = useDocumentManagerCapability()\n const { activeDocumentId, activeDocument } = useActiveDocument()\n const [loadError, setLoadError] = React.useState(false)\n const openedFileRef = React.useRef<string | null>(null)\n const onDocumentLoadSuccessRef = React.useRef(onDocumentLoadSuccess)\n\n React.useEffect(() => {\n onDocumentLoadSuccessRef.current = onDocumentLoadSuccess\n })\n\n React.useEffect(() => {\n if (!documentManager || !pdfFile) return\n if (openedFileRef.current === pdfFile) return\n\n openedFileRef.current = pdfFile\n setLoadError(false)\n\n const previousDocumentIds = documentManager\n .getOpenDocuments()\n .map((openDocument) => openDocument.id)\n const handleOpenError = () => {\n if (openedFileRef.current === pdfFile) setLoadError(true)\n }\n\n documentManager\n .openDocumentUrl({\n url: pdfFile,\n mode: pdfFile.startsWith("blob:") ? "full-fetch" : "auto",\n })\n .wait((response) => {\n response.task.wait((openedDocument) => {\n onDocumentLoadSuccessRef.current?.(openedDocument.pageCount)\n previousDocumentIds.forEach((documentIdToClose) => {\n documentManager.closeDocument(documentIdToClose).wait(\n () => undefined,\n () => undefined\n )\n })\n }, handleOpenError)\n }, handleOpenError)\n }, [documentManager, pdfFile])\n\n const document =\n activeDocument?.status === "loaded" ? activeDocument.document : null\n const documentFailed = loadError || activeDocument?.status === "error"\n\n if (!activeDocumentId || documentFailed || !pdfFile) {\n return (\n <PDFViewerFallbackShell\n className={innerProps.className}\n showToolbar={innerProps.showToolbar}\n showUpload={innerProps.showUpload}\n sidebarOpen={false}\n state={!pdfFile ? "empty" : documentFailed ? "error" : "loading"}\n onUploadFile={(file) => {\n innerProps.onUploadFile(file)\n innerProps.onPdfUpload?.(file)\n }}\n />\n )\n }\n\n return (\n <PDFViewerInner\n key={activeDocumentId}\n {...innerProps}\n pdfFile={pdfFile}\n documentId={activeDocumentId}\n document={document}\n />\n )\n}\n\nexport const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(\n function PDFViewer(\n {\n className,\n defaultZoom = DEFAULT_ZOOM,\n fileName,\n showDownload = true,\n showRotateControls = true,\n showToolbar = true,\n showUpload = true,\n src,\n toolbarActions,\n pageClassName,\n renderPageOverlay,\n onActivePageChange,\n onDocumentLoadSuccess,\n onPdfUpload,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n },\n ref\n ) {\n const { engine, error: engineError } = useSharedPdfEngine()\n const [uploadedPdfFile, setUploadedPdfFile] = React.useState<{\n src: string | undefined\n url: string | null\n }>(() => ({ src, url: null }))\n const uploadedPdfUrl =\n uploadedPdfFile.src === src ? uploadedPdfFile.url : null\n const pdfFile = uploadedPdfUrl ?? src ?? ""\n\n React.useEffect(\n () => () => {\n if (uploadedPdfUrl) URL.revokeObjectURL(uploadedPdfUrl)\n },\n [uploadedPdfUrl]\n )\n\n const handleUploadFile = React.useCallback(\n (nextFile: File) => {\n const nextUrl = URL.createObjectURL(nextFile)\n\n setUploadedPdfFile({ src, url: nextUrl })\n },\n [src]\n )\n\n // Plugin registrations are created once per viewer instance.\n const [plugins] = React.useState(() => [\n createPluginRegistration(DocumentManagerPluginPackage),\n createPluginRegistration(ViewportPluginPackage, {\n viewportGap: PAGE_GAP,\n }),\n createPluginRegistration(ScrollPluginPackage, {\n defaultPageGap: PAGE_GAP,\n defaultBufferSize: 2,\n }),\n createPluginRegistration(RenderPluginPackage),\n createPluginRegistration(TilingPluginPackage, {\n tileSize: 768,\n overlapPx: 2.5,\n extraRings: 0,\n }),\n createPluginRegistration(InteractionManagerPluginPackage),\n createPluginRegistration(SelectionPluginPackage, {\n marquee: { enabled: false },\n }),\n createPluginRegistration(SearchPluginPackage, {\n showAllResults: true,\n }),\n createPluginRegistration(ThumbnailPluginPackage, {\n width: THUMBNAIL_WIDTH,\n gap: THUMBNAIL_GAP,\n imagePadding: THUMBNAIL_IMAGE_PADDING,\n labelHeight: THUMBNAIL_LABEL_HEIGHT,\n paddingY: THUMBNAIL_PANE_PADDING_Y,\n buffer: 3,\n autoScroll: true,\n scrollBehavior: "auto",\n }),\n createPluginRegistration(ZoomPluginPackage, {\n defaultZoomLevel: defaultZoom,\n minZoom: ZOOM_OPTIONS[0],\n maxZoom: ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1],\n }),\n createPluginRegistration(RotatePluginPackage),\n ])\n\n if (engineError) {\n return (\n <div\n data-slot="pdf-viewer"\n className={cn(\n "grid h-full w-full place-items-center bg-background p-6 text-sm text-muted-foreground",\n className\n )}\n >\n Unable to load the PDF engine.\n </div>\n )\n }\n\n if (!engine) {\n return (\n <div\n data-slot="pdf-viewer"\n className={cn(\n "relative flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n {showToolbar ? (\n <div className="min-h-12 border-b bg-background" />\n ) : null}\n <div className="relative min-h-0 flex-1">\n <PDFViewerLoadingSkeleton sidebarInline sidebarOpen={false} />\n </div>\n </div>\n )\n }\n\n return (\n <EmbedPDF engine={engine} plugins={plugins}>\n <PDFViewerDocumentLoader\n viewerRef={ref}\n pdfFile={pdfFile}\n defaultZoom={defaultZoom}\n className={className}\n fileName={fileName}\n showDownload={showDownload}\n showToolbar={showToolbar}\n showRotateControls={showRotateControls}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n pageClassName={pageClassName}\n renderPageOverlay={renderPageOverlay}\n onActivePageChange={onActivePageChange}\n onDocumentLoadSuccess={onDocumentLoadSuccess}\n onPdfUpload={onPdfUpload}\n onPagePointerDown={onPagePointerDown}\n onPagePointerMove={onPagePointerMove}\n onPagePointerUp={onPagePointerUp}\n onPagePointerCancel={onPagePointerCancel}\n onUploadFile={handleUploadFile}\n />\n </EmbedPDF>\n )\n }\n)\n'export function PdfViewerSourceCode() {return (diff --git a/apps/v4/components/ui/docx-viewer.tsx b/apps/v4/components/ui/docx-viewer.tsxindex 01c99c2..96c0586 100644--- a/apps/v4/components/ui/docx-viewer.tsx+++ b/apps/v4/components/ui/docx-viewer.tsx@@ -78,6 +78,7 @@ const DOCX_THUMBNAIL_FOCUS_RING_CLASS =type UploadedDocxFile = {file: Fileidentity: string+ sourceUrl: string | undefined}async function loadDocxFile(@@ -190,19 +191,19 @@ function useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {const [showSpinner, setShowSpinner] = React.useState(false)React.useEffect(() => {- if (!isLoading) {- setShowSpinner(false)- return- }+ if (!isLoading) returnconst timeoutId = window.setTimeout(() => {setShowSpinner(true)}, delayMs)- return () => window.clearTimeout(timeoutId)+ return () => {+ window.clearTimeout(timeoutId)+ setShowSpinner(false)+ }}, [delayMs, isLoading])- return showSpinner+ return isLoading && showSpinner}function isDocxPaddingWarning(args: unknown[]) {@@ -379,12 +380,6 @@ function DocxPageNumberControl({const [isEditing, setIsEditing] = React.useState(false)const [draftPage, setDraftPage] = React.useState(() => String(displayPage))- React.useEffect(() => {- if (!isEditing) {- setDraftPage(String(displayPage))- }- }, [displayPage, isEditing])-React.useEffect(() => {if (!isEditing) return@@ -676,6 +671,7 @@ function DocxThumbnailSidebarList({activePage > 0 && visibleThumbnails.length? `${thumbnailListboxId}-page-${activePage}`: undefined+ // eslint-disable-next-line react-hooks/incompatible-library -- TanStack Virtual returns imperative helpers used by the thumbnail rail.const virtualizer = useVirtualizer({count: visibleThumbnails.length,estimateSize: () => DOCX_THUMBNAIL_ROW_ESTIMATE,@@ -889,17 +885,40 @@ function DocxViewerContent({const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()const [uploadedDocxFile, setUploadedDocxFile] =React.useState<UploadedDocxFile | null>(null)- const [activePage, setActivePage] = React.useState(1)const [sidebarOpen, setSidebarOpen] = React.useState(false)const resolvedDefaultZoomScale = normalizeDocxZoomScale(defaultZoom)+ const activeUploadedDocxFile =+ uploadedDocxFile?.sourceUrl === url ? uploadedDocxFile : null+ const documentKey = activeUploadedDocxFile?.identity ?? url ?? ""+ const [activePageState, setActivePageState] = React.useState({+ documentKey: "",+ value: 1,+ })+ const activePage =+ activePageState.documentKey === documentKey ? activePageState.value : 1+ const setActivePage = React.useCallback<+ React.Dispatch<React.SetStateAction<number>>+ >(+ (nextPage) => {+ setActivePageState((currentState) => {+ const currentPage =+ currentState.documentKey === documentKey ? currentState.value : 1+ const value =+ typeof nextPage === "function" ? nextPage(currentPage) : nextPage++ return { documentKey, value }+ })+ },+ [documentKey]+ )const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)const viewerBackgroundColor ="color-mix(in oklab, var(--muted) 40%, transparent)"const displayFileName = React.useMemo(() =>- uploadedDocxFile?.file.name ??+ activeUploadedDocxFile?.file.name ??(url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),- [fileName, uploadedDocxFile?.file.name, url]+ [activeUploadedDocxFile?.file.name, fileName, url])const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>effectiveIsDark ? "dark" : "light"@@ -942,8 +961,32 @@ function DocxViewerContent({thumbnailEditor,thumbnailOptions)- const [zoomScale, setZoomScale] = React.useState<number>(- resolvedDefaultZoomScale+ const [zoomScaleState, setZoomScaleState] = React.useState({+ documentKey: "",+ value: resolvedDefaultZoomScale,+ })+ const zoomScale =+ zoomScaleState.documentKey === documentKey+ ? zoomScaleState.value+ : resolvedDefaultZoomScale+ const setZoomScale = React.useCallback<+ React.Dispatch<React.SetStateAction<number>>+ >(+ (nextZoomScale) => {+ setZoomScaleState((currentState) => {+ const currentZoomScale =+ currentState.documentKey === documentKey+ ? currentState.value+ : resolvedDefaultZoomScale+ const value =+ typeof nextZoomScale === "function"+ ? nextZoomScale(currentZoomScale)+ : nextZoomScale++ return { documentKey, value }+ })+ },+ [documentKey, resolvedDefaultZoomScale])const [loadError, setLoadError] = React.useState<string>()const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)@@ -955,7 +998,7 @@ function DocxViewerContent({const loadingState = (<ViewerLoadingSurface showSpinner={shouldShowDocumentSpinner} />)- const hasDocument = Boolean(url || uploadedDocxFile)+ const hasDocument = Boolean(url || activeUploadedDocxFile)const pageCount =hasDocument && !isLoadingDocument && !loadError? Math.max(1, reportedPageCount || editor.totalPages)@@ -984,13 +1027,13 @@ function DocxViewerContent({)const handleDownload = React.useCallback(async () => {if (isPreparingDownload) return- if (!uploadedDocxFile && !url) return+ if (!activeUploadedDocxFile && !url) returnsetIsPreparingDownload(true)try {await downloadDocxFile({- file: uploadedDocxFile?.file,+ file: activeUploadedDocxFile?.file,fileName: displayFileName,url,})@@ -999,7 +1042,7 @@ function DocxViewerContent({} finally {setIsPreparingDownload(false)}- }, [displayFileName, isPreparingDownload, uploadedDocxFile, url])+ }, [activeUploadedDocxFile, displayFileName, isPreparingDownload, url])const handleShowDocumentMarkupChange = React.useCallback((checked: boolean) => {setShowComments(checked)@@ -1011,10 +1054,8 @@ function DocxViewerContent({useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)React.useEffect(() => {- setZoomScale(resolvedDefaultZoomScale)- setActivePage(1)viewportRef.current?.scrollTo({ top: 0, left: 0 })- }, [resolvedDefaultZoomScale, url])+ }, [documentKey])React.useEffect(() => {setDocumentTheme(effectiveIsDark ? "dark" : "light")@@ -1025,8 +1066,12 @@ function DocxViewerContent({status.startsWith("Failed to load file") ||status === "Only .docx files are supported") {- setLoadError(status)- setIsLoadingDocument(false)+ const frame = window.requestAnimationFrame(() => {+ setLoadError(status)+ setIsLoadingDocument(false)+ })++ return () => window.cancelAnimationFrame(frame)}}, [status])@@ -1041,7 +1086,7 @@ function DocxViewerContent({async function load() {// Superseded while queued — let the newest import run instead.if (!isCurrent) return- if (!uploadedDocxFile && !url) {+ if (!activeUploadedDocxFile && !url) {setIsLoadingDocument(false)setLoadError(undefined)setReportedPageCount(0)@@ -1054,7 +1099,7 @@ function DocxViewerContent({try {const docxFile =- uploadedDocxFile?.file ??+ activeUploadedDocxFile?.file ??(url ? await loadDocxFile(url, displayFileName) : null)if (!docxFile) returnawait importDocxFile(docxFile)@@ -1079,13 +1124,13 @@ function DocxViewerContent({return () => {isCurrent = false}- }, [displayFileName, importDocxFile, uploadedDocxFile, url])-- React.useEffect(() => {- if (url) {- setUploadedDocxFile(null)- }- }, [url])+ }, [+ activeUploadedDocxFile,+ displayFileName,+ importDocxFile,+ setActivePage,+ url,+ ])const updateActivePageFromViewport = React.useCallback(() => {const viewport = viewportRef.current@@ -1117,7 +1162,7 @@ function DocxViewerContent({setActivePage((currentPage) =>currentPage === closestPage ? currentPage : closestPage)- }, [pageCount])+ }, [pageCount, setActivePage])React.useEffect(() => {const viewport = viewportRef.current@@ -1171,7 +1216,12 @@ function DocxViewerContent({behavior: "auto",})},- [pageLayout.pageHeightPx, pageLayout.viewportDefaults.pageGapPx, zoomScale]+ [+ pageLayout.pageHeightPx,+ pageLayout.viewportDefaults.pageGapPx,+ setActivePage,+ zoomScale,+ ])async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {@@ -1186,6 +1236,7 @@ function DocxViewerContent({setUploadedDocxFile({file,identity: `${file.name}-${file.size}-${file.lastModified}`,+ sourceUrl: url,})}@@ -1259,7 +1310,7 @@ function DocxViewerContent({}}viewportRef={setViewportRef}>- {!url && !uploadedDocxFile ? (+ {!url && !activeUploadedDocxFile ? (<div className="grid h-full min-h-96 place-items-center p-6 text-center"><div className="max-w-md rounded-lg border bg-background p-4 text-sm shadow-xs"><div className="font-medium">Upload a DOCX to preview</div>diff --git a/apps/v4/components/ui/file-system.tsx b/apps/v4/components/ui/file-system.tsxindex 01cb49f..cb7add9 100644--- a/apps/v4/components/ui/file-system.tsx+++ b/apps/v4/components/ui/file-system.tsx@@ -790,6 +790,7 @@ const FOLDER_GLYPH_DATA_URL = `data:image/svg+xml,${encodeURIComponent(FOLDER_GLfunction FileSystemFolderGlyph({ className }: { className?: string }) {return (+ // eslint-disable-next-line @next/next/no-img-element -- The folder glyph is an inline SVG data URL shared with the tree sprite.<imgsrc={FOLDER_GLYPH_DATA_URL}alt=""@@ -2201,6 +2202,7 @@ export function FileSystem({><DialogTitle className="sr-only">{openedFileName}</DialogTitle>{openedFile.kind === "image" ? (+ // eslint-disable-next-line @next/next/no-img-element -- File previews render caller-provided URLs that may be object or presigned URLs.<imgsrc={openedFile.url}alt={openedFileName}@@ -4584,6 +4586,7 @@ const FileSystemColumn = React.memo(function FileSystemColumn({{entry.kind === "folder" ? (<FileSystemFolderGlyph className="h-3.5 w-auto shrink-0" />) : coverUrl ? (+ // eslint-disable-next-line @next/next/no-img-element -- Cover thumbnails come from caller-provided file preview URLs.<imgsrc={coverUrl}alt=""@@ -4733,6 +4736,7 @@ function FileSystemGalleryStage({}if (viewerKind === "image" && url) {return (+ // eslint-disable-next-line @next/next/no-img-element -- Image file previews render caller-provided URLs that may be object or presigned URLs.<imgsrc={url}alt={file.name}diff --git a/apps/v4/components/ui/file-thumbnail.tsx b/apps/v4/components/ui/file-thumbnail.tsxindex a9555e3..fd27e75 100644--- a/apps/v4/components/ui/file-thumbnail.tsx+++ b/apps/v4/components/ui/file-thumbnail.tsx@@ -40,7 +40,6 @@ export function FileThumbnailLoadingOverlay() {}export function FileThumbnail({- file: _file,className,previewAspectRatio,previewClassName,@@ -104,11 +103,6 @@ export function FileThumbnail({React.useEffect(() => {cancelImageReveal()-- if (previewImageUrl) return-- setLoadedPreviewImageUrl(null)- setFailedPreviewImageUrl(null)}, [cancelImageReveal, previewImageUrl])React.useEffect(() => cancelImageReveal, [cancelImageReveal])@@ -142,6 +136,7 @@ export function FileThumbnail({}>{previewImageUrl ? (+ // eslint-disable-next-line @next/next/no-img-element -- Preview URLs can be transient object or presigned URLs outside Next image optimization.<imgref={imageRef}src={previewImageUrl}diff --git a/apps/v4/components/ui/pdf-viewer.tsx b/apps/v4/components/ui/pdf-viewer.tsxindex 94fc131..695d58b 100644--- a/apps/v4/components/ui/pdf-viewer.tsx+++ b/apps/v4/components/ui/pdf-viewer.tsx@@ -47,7 +47,6 @@ import {useThumbnailCapability,useThumbnailPlugin,type ThumbMeta,- type WindowState,} from "@embedpdf/plugin-thumbnail/react"import { TilingLayer, TilingPluginPackage } from "@embedpdf/plugin-tiling/react"import {@@ -627,17 +626,11 @@ function PDFViewerPageNumberControl({const [isEditing, setIsEditing] = React.useState(false)const [draftPage, setDraftPage] = React.useState(() => String(displayPage))- React.useEffect(() => {- if (!isEditing) {- setDraftPage(String(displayPage))- }- }, [displayPage, isEditing])-React.useEffect(() => {if (!isEditing) returninputRef.current?.focus()- inputRef.current?.setSelectionRange(draftPage.length, draftPage.length)+ inputRef.current?.select()}, [isEditing])const applyPageDraft = React.useCallback(@@ -811,14 +804,8 @@ function PDFViewerSearchControl({}, [])React.useEffect(() => {- const trimmedDraft = searchDraft.trim()-- if (!trimmedDraft) {- runSearch("")- return- }+ if (!searchDraft.trim()) return- setIsSearching(true)const timeoutId = window.setTimeout(() => {runSearch(searchDraft)}, PDF_SEARCH_DEBOUNCE_MS)@@ -826,6 +813,25 @@ function PDFViewerSearchControl({return () => window.clearTimeout(timeoutId)}, [runSearch, searchDraft])+ const handleSearchDraftChange = React.useCallback(+ (event: React.ChangeEvent<HTMLInputElement>) => {+ const nextDraft = event.target.value++ setSearchDraft(nextDraft)++ if (nextDraft.trim()) {+ setIsSearching(true)+ return+ }++ searchRequestIdRef.current += 1+ setSearchQuery("")+ setIsSearching(false)+ provides?.stopSearch()+ },+ [provides]+ )+const clearSearch = React.useCallback(() => {searchRequestIdRef.current += 1setSearchDraft("")@@ -866,7 +872,7 @@ function PDFViewerSearchControl({<Inputplaceholder="Search text"value={searchDraft}- onChange={(event) => setSearchDraft(event.target.value)}+ onChange={handleSearchDraftChange}onKeyDown={(event) => {if (event.key !== "Enter") return@@ -1104,16 +1110,31 @@ function PDFViewerThumbnailScrollArea({}) {const { plugin: thumbnailPlugin } = useThumbnailPlugin()const viewportRef = React.useRef<HTMLDivElement | null>(null)- const [windowData, setWindowData] = React.useState<{- docId: string | null- window: WindowState | null- }>({ docId: null, window: null })const [viewportMetrics, setViewportMetrics] = React.useState({clientHeight: 0,scrollTop: 0,})+ const thumbnailScope = React.useMemo(+ () => thumbnailPlugin?.provides().forDocument(documentId) ?? null,+ [documentId, thumbnailPlugin]+ )- const windowState = windowData.docId === documentId ? windowData.window : null+ const windowState = React.useSyncExternalStore(+ React.useCallback(+ (onStoreChange) => {+ if (!thumbnailScope) return () => undefined++ return thumbnailScope.onWindow(() => onStoreChange())+ },+ [thumbnailScope]+ ),+ React.useCallback(+ () => thumbnailScope?.getWindow() ?? null,+ [thumbnailScope]+ ),+ () => null+ )+ const hasWindowState = Boolean(windowState)const paddingY = thumbnailPlugin?.cfg.paddingY ?? 0const thumbnailLayout = React.useMemo(() =>@@ -1153,85 +1174,59 @@ function PDFViewerThumbnailScrollArea({}}, [thumbnailLayout, thumbnailPlugin, viewportMetrics, windowState])- React.useEffect(() => {- if (!thumbnailPlugin) return-- const scope = thumbnailPlugin.provides().forDocument(documentId)- const initialWindow = scope.getWindow()-- if (initialWindow) {- setWindowData({ docId: documentId, window: initialWindow })- }-- const unsubscribe = scope.onWindow((nextWindow) => {- setWindowData({ docId: documentId, window: nextWindow })- })-- return () => {- unsubscribe()- setWindowData({ docId: null, window: null })- }- }, [documentId, thumbnailPlugin])-React.useEffect(() => {const viewport = viewportRef.current- if (!viewport || !thumbnailPlugin) return+ if (!viewport || !thumbnailScope) return- const scope = thumbnailPlugin.provides().forDocument(documentId)const updateWindow = () => {setViewportMetrics({clientHeight: viewport.clientHeight,scrollTop: viewport.scrollTop,})- scope.updateWindow(viewport.scrollTop, viewport.clientHeight)+ thumbnailScope.updateWindow(viewport.scrollTop, viewport.clientHeight)}viewport.addEventListener("scroll", updateWindow)- updateWindow()+ const frame = window.requestAnimationFrame(updateWindow)- return () => viewport.removeEventListener("scroll", updateWindow)- }, [documentId, thumbnailPlugin])+ return () => {+ window.cancelAnimationFrame(frame)+ viewport.removeEventListener("scroll", updateWindow)+ }+ }, [thumbnailScope])React.useEffect(() => {const viewport = viewportRef.current- if (!viewport || !thumbnailPlugin) return+ if (!viewport || !thumbnailScope) return- const scope = thumbnailPlugin.provides().forDocument(documentId)const resizeObserver = new ResizeObserver(() => {setViewportMetrics({clientHeight: viewport.clientHeight,scrollTop: viewport.scrollTop,})- scope.updateWindow(viewport.scrollTop, viewport.clientHeight)+ thumbnailScope.updateWindow(viewport.scrollTop, viewport.clientHeight)})resizeObserver.observe(viewport)return () => resizeObserver.disconnect()- }, [documentId, thumbnailPlugin])+ }, [thumbnailScope])React.useEffect(() => {const viewport = viewportRef.current- if (!viewport || !thumbnailPlugin) return+ if (!viewport || !thumbnailScope) return- const scope = thumbnailPlugin.provides().forDocument(documentId)- setViewportMetrics({- clientHeight: viewport.clientHeight,- scrollTop: viewport.scrollTop,- })- scope.updateWindow(viewport.scrollTop, viewport.clientHeight)- }, [documentId, thumbnailPlugin, windowState, thumbnailLayout])+ thumbnailScope.updateWindow(viewport.scrollTop, viewport.clientHeight)+ }, [thumbnailLayout, thumbnailScope, windowState])React.useEffect(() => {const viewport = viewportRef.current- if (!viewport || !thumbnailPlugin || !windowState) return+ if (!viewport || !thumbnailScope || !hasWindowState) return- const scope = thumbnailPlugin.provides().forDocument(documentId)-- return scope.onScrollTo(({ top, behavior }) => {+ return thumbnailScope.onScrollTo(({ top, behavior }) => {viewport.scrollTo({ top, behavior })})- }, [documentId, thumbnailPlugin, Boolean(windowState)])+ }, [hasWindowState, thumbnailScope])return (<ScrollArea@@ -1278,13 +1273,7 @@ function PDFViewerScrollAreaViewport({const viewportRef = useViewportRef(documentId)const { provides: viewport } = useViewportCapability()const isGated = useIsViewportGated(documentId)- const [viewportGap, setViewportGap] = React.useState(0)-- React.useEffect(() => {- if (!viewport) return-- setViewportGap(viewport.getViewportGap())- }, [viewport])+ const viewportGap = viewport?.getViewportGap() ?? 0return (<ViewportElementContext.Provider value={viewportRef}>@@ -1644,12 +1633,27 @@ function PDFViewerScroller({React.useEffect(() => {if (!scrollPlugin || !documentId) return+ let frame = 0++ const setCurrentLayout = () => {+ try {+ setLayoutData({+ docId: documentId,+ layout: scrollPlugin.getScrollerLayout(documentId),+ })+ } catch {+ setLayoutData({ docId: documentId, layout: null })+ }+ }const unsubscribe = scrollPlugin.onScrollerData(documentId, (layout) => {setLayoutData({ docId: documentId, layout })})+ frame = window.requestAnimationFrame(setCurrentLayout)+return () => {+ window.cancelAnimationFrame(frame)unsubscribe()setLayoutData({ docId: null, layout: null })scrollPlugin.clearLayoutReady(documentId)@@ -1821,6 +1825,11 @@ function PDFViewerInner({const [selectedPageIndexes, setSelectedPageIndexes] = React.useState<Set<number>>(() => new Set())+ const basePageRotations = React.useMemo(+ () =>+ pdfDocument?.pages.map((page) => normalizeRotation(page.rotation)) ?? [],+ [pdfDocument]+ )const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)const viewportElementRef = React.useRef<HTMLDivElement | null>(null)@@ -1829,8 +1838,6 @@ function PDFViewerInner({const selectionAnchorPageIndexRef = React.useRef<number | null>(null)const suppressActivePageSelectionSyncRef = React.useRef<number | null>(null)const initializedSelectionDocumentRef = React.useRef<string | null>(null)- const basePageRotationsRef = React.useRef<Rotation[]>([])- const basePageRotationsDocumentRef = React.useRef<string | null>(null)const activePage = scrollState.currentPageconst numPages = pdfDocument?.pageCount ?? 0@@ -1849,31 +1856,6 @@ function PDFViewerInner({selectedPageIndexesRef.current = selectedPageIndexes}, [selectedPageIndexes])- React.useEffect(() => {- const emptyDeltas = new Map<number, Rotation>()- pageRotationDeltasRef.current = emptyDeltas- setPageRotationDeltas(emptyDeltas)- const emptySelection = new Set<number>()- selectedPageIndexesRef.current = emptySelection- setSelectedPageIndexes(emptySelection)- selectionAnchorPageIndexRef.current = null- suppressActivePageSelectionSyncRef.current = null- initializedSelectionDocumentRef.current = null- basePageRotationsRef.current = []- basePageRotationsDocumentRef.current = null- }, [documentId])-- React.useEffect(() => {- if (!pdfDocument || basePageRotationsDocumentRef.current === documentId) {- return- }-- basePageRotationsRef.current = pdfDocument.pages.map((page) =>- normalizeRotation(page.rotation)- )- basePageRotationsDocumentRef.current = documentId- }, [documentId, pdfDocument])-React.useEffect(() => {if (activePage > 0) onActivePageChange?.(activePage)}, [activePage, onActivePageChange])@@ -2082,7 +2064,7 @@ function PDFViewerInner({const previousDelta = previousDeltas.get(pageIndex) ?? 0const nextDelta = normalizeRotation(previousDelta + direction)const basePageRotation =- basePageRotationsRef.current[pageIndex] ??+ basePageRotations[pageIndex] ??normalizeRotation(currentPage.rotation)const previousPageRotation = normalizeRotation(basePageRotation + previousDelta@@ -2133,6 +2115,7 @@ function PDFViewerInner({},[activePage,+ basePageRotations,currentZoomLevel,documentId,pdfDocument,@@ -2153,7 +2136,7 @@ function PDFViewerInner({(page: PageLayout) => {const pageNumber = page.pageNumberconst basePageRotation =- basePageRotationsRef.current[page.pageIndex] ??+ basePageRotations[page.pageIndex] ??pdfDocument?.pages[page.pageIndex]?.rotation ??normalizeRotation(0)const pageRotation = normalizeRotation(@@ -2231,6 +2214,7 @@ function PDFViewerInner({)},[+ basePageRotations,currentZoomLevel,onPagePointerCancel,onPagePointerDown,@@ -2249,7 +2233,6 @@ function PDFViewerInner({data-slot="pdf-viewer"className={cn("flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",- "select-none selection:bg-transparent selection:text-inherit",className)}>@@ -2446,7 +2429,7 @@ function PDFViewerInner({>{thumbnailSidebarVisible ? (<PDFViewerThumbnails- basePageRotations={basePageRotationsRef.current}+ basePageRotations={basePageRotations}documentId={documentId}activePage={activePage}pageCount={numPages}@@ -2466,7 +2449,7 @@ function PDFViewerInner({<PDFViewerSelectionReleaseGuard documentId={documentId} /><GlobalPointerProvider documentId={documentId}><PDFViewerScroller- basePageRotations={basePageRotationsRef.current}+ basePageRotations={basePageRotations}documentId={documentId}pageRotationDeltas={pageRotationDeltas}renderPage={renderPage}@@ -2552,6 +2535,7 @@ function PDFViewerDocumentLoader({return (<PDFViewerInner+ key={activeDocumentId}{...innerProps}pdfFile={pdfFile}documentId={activeDocumentId}@@ -2585,14 +2569,13 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(ref) {const { engine, error: engineError } = useSharedPdfEngine()- const [pdfFile, setPdfFile] = React.useState(src ?? "")- const [uploadedPdfUrl, setUploadedPdfUrl] = React.useState<string | null>(- null- )-- React.useEffect(() => {- setPdfFile(src ?? "")- }, [src])+ const [uploadedPdfFile, setUploadedPdfFile] = React.useState<{+ src: string | undefined+ url: string | null+ }>(() => ({ src, url: null }))+ const uploadedPdfUrl =+ uploadedPdfFile.src === src ? uploadedPdfFile.url : null+ const pdfFile = uploadedPdfUrl ?? src ?? ""React.useEffect(() => () => {@@ -2601,15 +2584,14 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>([uploadedPdfUrl])- const handleUploadFile = React.useCallback((nextFile: File) => {- const nextUrl = URL.createObjectURL(nextFile)+ const handleUploadFile = React.useCallback(+ (nextFile: File) => {+ const nextUrl = URL.createObjectURL(nextFile)- setUploadedPdfUrl((previousUrl) => {- if (previousUrl) URL.revokeObjectURL(previousUrl)- return nextUrl- })- setPdfFile(nextUrl)- }, [])+ setUploadedPdfFile({ src, url: nextUrl })+ },+ [src]+ )// Plugin registrations are created once per viewer instance.const [plugins] = React.useState(() => [diff --git a/apps/v4/components/ui/xlsx-viewer.tsx b/apps/v4/components/ui/xlsx-viewer.tsxindex 8fdeaba..e41d23d 100644--- a/apps/v4/components/ui/xlsx-viewer.tsx+++ b/apps/v4/components/ui/xlsx-viewer.tsx@@ -1283,6 +1283,7 @@ const WorkbookSheetTabsInner = React.memo(function WorkbookSheetTabsInner({}}><div className="relative aspect-[11/7] w-full overflow-hidden bg-muted/60">+ {/* eslint-disable-next-line @next/next/no-img-element -- Workbook sheet previews are generated runtime image URLs. */}<imgkey={`${workbookIdentity}-${visiblePreviewIndex}-${previewUrl}`}src={previewUrl}