TypeScript
Sync PDF viewer rotation and thumbnail state
Andrew Luo4e971ed918fe
diff --git a/apps/v4/components/csv-viewer-docs.tsx b/apps/v4/components/csv-viewer-docs.tsxindex 8f616f8..acefee2 100644--- a/apps/v4/components/csv-viewer-docs.tsx+++ b/apps/v4/components/csv-viewer-docs.tsx@@ -66,7 +66,7 @@ export function CsvViewerExample() {}`const csvViewerSourceCode =- "\"use client\"\n\nimport * as React from \"react\"\nimport type * as GlideDataGrid from \"@glideapps/glide-data-grid\"\nimport type {\n DataEditorRef,\n GridCell,\n GridCellKind,\n GridColumn,\n GridSelection,\n Item,\n Theme,\n} from \"@glideapps/glide-data-grid\"\nimport {\n CompactSelection,\n emptyGridSelection,\n} from \"@glideapps/glide-data-grid\"\n\nimport \"@glideapps/glide-data-grid/dist/index.css\"\n\nimport {\n ArrowLeft01Icon,\n ArrowRight01Icon,\n MinusSignCircleIcon,\n PlusSignCircleIcon,\n Search01Icon,\n Upload01Icon,\n} from \"@hugeicons/core-free-icons\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport Papa from \"papaparse\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport { Input } from \"@/components/ui/input\"\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from \"@/components/ui/popover\"\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\"\n\nconst ZOOM_OPTIONS = [0.75, 1, 1.25, 1.5, 2] as const\nconst CSV_SEARCH_BATCH_ROW_COUNT = 500\nconst CSV_SEARCH_DEBOUNCE_MS = 300\n\ntype GlideDataGridModule = typeof GlideDataGrid\ntype CsvViewerProps = {\n className?: string\n data?: string\n search?: boolean\n}\n\ntype CsvSearchResult = {\n col: number\n row: number\n displayValue: string\n columnTitle: string\n}\n\nfunction toDisplayString(value: unknown): string {\n return value === null || value === undefined ? \"\" : String(value)\n}\n\nfunction normalizeHeaderTitle(header: string, index: number): string {\n const trimmed = header.trim()\n return trimmed.length > 0 ? trimmed : `Column ${index + 1}`\n}\n\nfunction columnIndexToA1(col: number) {\n let columnNumber = col + 1\n let columnName = \"\"\n\n while (columnNumber > 0) {\n const remainder = (columnNumber - 1) % 26\n columnName = String.fromCharCode(65 + remainder) + columnName\n columnNumber = Math.floor((columnNumber - 1) / 26)\n }\n\n return columnName\n}\n\nfunction cellAddressToA1(col: number, row: number) {\n return `${columnIndexToA1(col)}${row + 1}`\n}\n\nfunction cellMatchesQuery(displayValue: string, query: string) {\n return displayValue.toLowerCase().includes(query)\n}\n\nfunction createSingleCellSelection(cell: Item): GridSelection {\n const [col, row] = cell\n\n return {\n columns: CompactSelection.empty(),\n rows: CompactSelection.empty(),\n current: {\n cell,\n range: { x: col, y: row, width: 1, height: 1 },\n rangeStack: [],\n },\n }\n}\n\nasync function findCsvSearchResults(\n headers: string[],\n rows: string[][],\n rawQuery: string\n) {\n const query = rawQuery.trim().toLowerCase()\n if (!query) return []\n\n const results: CsvSearchResult[] = []\n const columnCount = Math.max(\n headers.length,\n rows.reduce((maxCount, row) => Math.max(maxCount, row.length), 0)\n )\n\n for (\n let batchStartRow = 0;\n batchStartRow < rows.length;\n batchStartRow += CSV_SEARCH_BATCH_ROW_COUNT\n ) {\n const batchEndRow = Math.min(\n batchStartRow + CSV_SEARCH_BATCH_ROW_COUNT,\n rows.length\n )\n\n for (let row = batchStartRow; row < batchEndRow; row += 1) {\n const rowValues = rows[row] ?? []\n\n for (let col = 0; col < columnCount; col += 1) {\n const displayValue = rowValues[col] ?? \"\"\n if (!cellMatchesQuery(displayValue, query)) continue\n\n results.push({\n col,\n row,\n displayValue,\n columnTitle: headers[col] ?? `Column ${col + 1}`,\n })\n }\n }\n\n if (batchEndRow < rows.length) {\n await new Promise<void>((resolve) => {\n window.setTimeout(resolve, 0)\n })\n }\n }\n\n return results\n}\n\nfunction parseDelimitedText(text: string): {\n headers: string[]\n rows: string[][]\n error: string | null\n} {\n const results = Papa.parse<Record<string, unknown>>(text, {\n header: true,\n skipEmptyLines: \"greedy\",\n })\n\n const objectRows = Array.isArray(results.data)\n ? results.data.filter(\n (row): row is Record<string, unknown> =>\n !!row && typeof row === \"object\" && !Array.isArray(row)\n )\n : []\n const metaFields = Array.isArray(results.meta.fields)\n ? results.meta.fields.map((field) => String(field))\n : []\n const fieldKeys =\n metaFields.length > 0\n ? metaFields\n : Object.keys(objectRows[0] ?? {}).filter(\n (key) => key !== \"__parsed_extra\"\n )\n const extraColumnCount = objectRows.reduce((maxCount, row) => {\n const extras = row.__parsed_extra\n return Array.isArray(extras) ? Math.max(maxCount, extras.length) : maxCount\n }, 0)\n const headers = [\n ...fieldKeys.map((field, index) => normalizeHeaderTitle(field, index)),\n ...Array.from(\n { length: extraColumnCount },\n (_, index) => `Extra ${index + 1}`\n ),\n ]\n\n const rows = objectRows.map((row) => {\n const baseValues = fieldKeys.map((fieldKey) =>\n toDisplayString(row[fieldKey])\n )\n const extras = Array.isArray(row.__parsed_extra)\n ? row.__parsed_extra.map((value) => toDisplayString(value))\n : []\n const paddedExtras =\n extras.length >= extraColumnCount\n ? extras.slice(0, extraColumnCount)\n : [\n ...extras,\n ...Array.from(\n { length: extraColumnCount - extras.length },\n () => \"\"\n ),\n ]\n\n return [...baseValues, ...paddedExtras]\n })\n\n const firstError =\n Array.isArray(results.errors) && results.errors.length > 0\n ? results.errors[0]\n : null\n\n return {\n headers,\n rows,\n error:\n rows.length === 0 && firstError\n ? String(firstError.message ?? \"Could not parse CSV file.\")\n : null,\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 CsvSearchPopover({\n headers,\n rows,\n gridRef,\n dataIdentity,\n controlsDisabled,\n onGridSelectionChange,\n}: {\n headers: string[]\n rows: string[][]\n gridRef: React.RefObject<DataEditorRef | null>\n dataIdentity: string\n controlsDisabled: boolean\n onGridSelectionChange: (selection: GridSelection) => void\n}) {\n const [searchDraft, setSearchDraft] = React.useState(\"\")\n const [searchQuery, setSearchQuery] = React.useState(\"\")\n const [searchResults, setSearchResults] = React.useState<CsvSearchResult[]>(\n []\n )\n const [activeResultIndex, setActiveResultIndex] = React.useState(0)\n const [isSearching, setIsSearching] = React.useState(false)\n const searchRequestIdRef = React.useRef(0)\n const appliedResultKeyRef = React.useRef(\"\")\n const activeResult = searchResults[activeResultIndex] ?? null\n const activeResultKey = activeResult\n ? `${activeResult.row}:${activeResult.col}`\n : \"\"\n const hasActiveQuery = Boolean(searchQuery.trim())\n const resultLabel = isSearching\n ? \"Searching\"\n : !hasActiveQuery\n ? \"No search\"\n : searchResults.length\n ? `${activeResultIndex + 1} / ${searchResults.length}`\n : \"No results\"\n\n const runSearch = React.useCallback(\n (rawQuery: string) => {\n const nextQuery = rawQuery.trim()\n const requestId = searchRequestIdRef.current + 1\n searchRequestIdRef.current = requestId\n appliedResultKeyRef.current = \"\"\n setSearchQuery(nextQuery)\n setActiveResultIndex(0)\n\n if (!nextQuery) {\n setSearchResults([])\n setIsSearching(false)\n return\n }\n\n setIsSearching(true)\n void findCsvSearchResults(headers, rows, nextQuery)\n .then((nextResults) => {\n if (searchRequestIdRef.current !== requestId) return\n setSearchResults(nextResults)\n })\n .catch(() => {\n if (searchRequestIdRef.current !== requestId) return\n setSearchResults([])\n })\n .finally(() => {\n if (searchRequestIdRef.current !== requestId) return\n setIsSearching(false)\n })\n },\n [headers, rows]\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 }, CSV_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 setSearchResults([])\n setActiveResultIndex(0)\n setIsSearching(false)\n appliedResultKeyRef.current = \"\"\n onGridSelectionChange(emptyGridSelection)\n }, [onGridSelectionChange])\n\n const goToRelativeResult = React.useCallback(\n (direction: 1 | -1) => {\n if (!searchResults.length) return\n\n setActiveResultIndex((currentIndex) => {\n return (\n (currentIndex + direction + searchResults.length) %\n searchResults.length\n )\n })\n },\n [searchResults.length]\n )\n\n React.useEffect(() => {\n searchRequestIdRef.current += 1\n setSearchDraft(\"\")\n setSearchQuery(\"\")\n setSearchResults([])\n setActiveResultIndex(0)\n setIsSearching(false)\n appliedResultKeyRef.current = \"\"\n onGridSelectionChange(emptyGridSelection)\n }, [dataIdentity, onGridSelectionChange])\n\n React.useEffect(() => {\n if (!activeResult) return\n\n if (appliedResultKeyRef.current === activeResultKey) return\n appliedResultKeyRef.current = activeResultKey\n\n const cell: Item = [activeResult.col, activeResult.row]\n onGridSelectionChange(createSingleCellSelection(cell))\n\n const frame = window.requestAnimationFrame(() => {\n gridRef.current?.scrollTo(\n activeResult.col,\n activeResult.row,\n \"both\",\n 48,\n 48,\n {\n vAlign: \"center\",\n hAlign: \"center\",\n }\n )\n })\n\n return () => window.cancelAnimationFrame(frame)\n }, [activeResult, activeResultKey, gridRef, onGridSelectionChange])\n\n return (\n <Popover>\n <ToolbarTooltip label=\"Search CSV\">\n <PopoverTrigger asChild>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Search CSV\"\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 CSV\"\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 && searchResults.length) {\n goToRelativeResult(-1)\n } else if (searchResults.length) {\n goToRelativeResult(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 {searchResults.length ? (\n <>\n <span className=\"text-primary\">{activeResultIndex + 1}</span>\n {` / ${searchResults.length}`}\n </>\n ) : (\n resultLabel\n )}\n </div>\n {activeResult ? (\n <div className=\"mt-0.5 truncate\">\n {activeResult.columnTitle}!{cellAddressToA1(activeResult.col, activeResult.row)}\n </div>\n ) : null}\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 || searchResults.length === 0}\n onClick={() => goToRelativeResult(-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 || searchResults.length === 0}\n onClick={() => goToRelativeResult(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 readIsDarkTheme() {\n return (\n typeof document !== \"undefined\" &&\n document.documentElement.classList.contains(\"dark\")\n )\n}\n\nfunction useIsDarkTheme() {\n const [isDark, setIsDark] = React.useState(readIsDarkTheme)\n\n React.useEffect(() => {\n if (typeof document === \"undefined\") return\n\n const updateTheme = () => setIsDark(readIsDarkTheme())\n\n updateTheme()\n\n if (typeof MutationObserver === \"undefined\") return\n\n const observer = new MutationObserver(updateTheme)\n observer.observe(document.documentElement, {\n attributes: true,\n attributeFilter: [\"class\"],\n })\n\n return () => observer.disconnect()\n }, [])\n\n return isDark\n}\n\nexport function CsvViewer({ className, data, search = false }: CsvViewerProps) {\n const inputRef = React.useRef<HTMLInputElement | null>(null)\n const gridRef = React.useRef<DataEditorRef | null>(null)\n const isDark = useIsDarkTheme()\n const [glide, setGlide] = React.useState<GlideDataGridModule | null>(null)\n const [zoom, setZoom] = React.useState<(typeof ZOOM_OPTIONS)[number]>(1)\n const [gridSelection, setGridSelection] =\n React.useState<GridSelection>(emptyGridSelection)\n const [parsed, setParsed] = React.useState(() =>\n data ? parseDelimitedText(data) : { headers: [], rows: [], error: null }\n )\n const [isPending, setIsPending] = React.useState(false)\n const [dataRevision, setDataRevision] = React.useState(0)\n\n const dataIdentity = React.useMemo(\n () =>\n `${dataRevision}:${parsed.headers.join(\"\\u0001\")}:${parsed.rows.length}:${parsed.error ?? \"\"}`,\n [dataRevision, parsed.error, parsed.headers, parsed.rows.length]\n )\n\n const handleGridSelectionChange = React.useCallback(\n (selection: GridSelection) => {\n setGridSelection(selection)\n },\n []\n )\n\n React.useEffect(() => {\n if (data) {\n setParsed(parseDelimitedText(data))\n setDataRevision((revision) => revision + 1)\n }\n }, [data])\n\n React.useEffect(() => {\n if (!search) {\n setGridSelection(emptyGridSelection)\n }\n }, [search])\n\n React.useEffect(() => {\n let mounted = true\n\n void import(\"@glideapps/glide-data-grid\").then((module) => {\n if (mounted) {\n setGlide(module)\n }\n })\n\n return () => {\n mounted = false\n }\n }, [])\n\n const columnCount = Math.max(1, parsed.headers.length)\n const scale = React.useCallback(\n (value: number) => Math.round(value * zoom),\n [zoom]\n )\n const searchDisabled =\n Boolean(parsed.error) || parsed.rows.length === 0 || isPending\n\n const theme = React.useMemo<Partial<Theme>>(\n () => ({\n accentColor: isDark ? \"#60a5fa\" : \"#2563eb\",\n accentLight: isDark ? \"#1d4ed826\" : \"#dbeafe\",\n accentFg: \"#ffffff\",\n textDark: isDark ? \"#e5e5e5\" : \"#171717\",\n textMedium: isDark ? \"#a3a3a3\" : \"#525252\",\n textLight: isDark ? \"#737373\" : \"#a3a3a3\",\n textBubble: isDark ? \"#f5f5f5\" : \"#171717\",\n textHeader: isDark ? \"#f5f5f5\" : \"#171717\",\n textGroupHeader: isDark ? \"#a3a3a3\" : \"#525252\",\n bgCell: isDark ? \"#0a0a0a\" : \"#ffffff\",\n bgCellMedium: isDark ? \"#171717\" : \"#fafafa\",\n bgHeader: isDark ? \"#171717\" : \"#fafafa\",\n bgHeaderHasFocus: isDark ? \"#262626\" : \"#f5f5f5\",\n bgHeaderHovered: isDark ? \"#262626\" : \"#f5f5f5\",\n borderColor: isDark ? \"#262626\" : \"#e5e5e5\",\n horizontalBorderColor: isDark ? \"#262626\" : \"#e5e5e5\",\n cellHorizontalPadding: scale(8),\n cellVerticalPadding: Math.max(2, scale(3)),\n headerIconSize: scale(18),\n baseFontStyle: `${scale(13)}px`,\n headerFontStyle: `600 ${scale(13)}px`,\n markerFontStyle: `${scale(11)}px`,\n fontFamily: '-apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif',\n editorFontSize: `${scale(13)}px`,\n }),\n [isDark, scale]\n )\n\n const columns = React.useMemo<GridColumn[]>(\n () =>\n Array.from({ length: columnCount }, (_, index) => ({\n id: `column-${index}`,\n title: parsed.headers[index] ?? `Column ${index + 1}`,\n width: scale(index === 0 ? 180 : 160),\n })),\n [columnCount, parsed.headers, scale]\n )\n\n const getCellContent = React.useCallback(\n ([col, row]: Item): GridCell => {\n const value = parsed.rows[row]?.[col] ?? \"\"\n const textKind = glide?.GridCellKind.Text as GridCellKind.Text\n\n return {\n kind: textKind,\n data: value,\n displayData: value,\n allowOverlay: true,\n readonly: true,\n }\n },\n [glide, parsed.rows]\n )\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n if (!file) return\n\n setIsPending(true)\n try {\n const text = await file.text()\n setParsed(parseDelimitedText(text))\n setDataRevision((revision) => revision + 1)\n } catch (error) {\n setParsed({\n headers: [],\n rows: [],\n error:\n error instanceof Error ? error.message : \"Could not read CSV file.\",\n })\n setDataRevision((revision) => revision + 1)\n } finally {\n event.target.value = \"\"\n setIsPending(false)\n }\n }\n\n function stepZoom(direction: -1 | 1) {\n const index = ZOOM_OPTIONS.indexOf(zoom)\n const nextIndex = Math.min(\n ZOOM_OPTIONS.length - 1,\n Math.max(0, index + direction)\n )\n setZoom(ZOOM_OPTIONS[nextIndex])\n }\n\n return (\n <div\n className={cn(\n \"flex h-[560px] w-full flex-col overflow-hidden bg-background\",\n className\n )}\n >\n <div className=\"flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2\">\n <TooltipProvider>\n <div className=\"ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1\">\n <div className=\"flex flex-none items-center gap-1\">\n <ToolbarTooltip label=\"Zoom out\">\n <Button\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Zoom out\"\n disabled={zoom <= ZOOM_OPTIONS[0]}\n onClick={() => stepZoom(-1)}\n >\n <HugeiconsIcon\n icon={MinusSignCircleIcon}\n className=\"size-4\"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={zoom.toString()}\n onValueChange={(value) =>\n setZoom(Number(value) as (typeof ZOOM_OPTIONS)[number])\n }\n modal={false}\n >\n <SelectTrigger\n size=\"sm\"\n className=\"w-[84px] min-w-[84px]\"\n aria-label=\"Zoom level\"\n >\n <SelectValue>{Math.round(zoom * 100)}%</SelectValue>\n </SelectTrigger>\n <SelectContent align=\"end\" alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((option) => (\n <SelectItem key={option} value={option.toString()}>\n {Math.round(option * 100)}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label=\"Zoom in\">\n <Button\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Zoom in\"\n disabled={zoom >= ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]}\n onClick={() => stepZoom(1)}\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n </div>\n {search ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n <CsvSearchPopover\n headers={parsed.headers}\n rows={parsed.rows}\n gridRef={gridRef}\n dataIdentity={dataIdentity}\n controlsDisabled={searchDisabled}\n onGridSelectionChange={handleGridSelectionChange}\n />\n </>\n ) : null}\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n <input\n ref={inputRef}\n type=\"file\"\n accept=\".csv,.tsv,text/csv,text/tab-separated-values\"\n className=\"hidden\"\n onChange={handleUpload}\n />\n <ToolbarTooltip label=\"Upload CSV\">\n <Button\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Upload CSV\"\n loading={isPending}\n onClick={() => inputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n </div>\n </TooltipProvider>\n </div>\n <div className=\"min-h-0 flex-1\">\n {parsed.error ? (\n <div className=\"flex h-full items-center justify-center px-4 text-center text-sm text-destructive\">\n {parsed.error}\n </div>\n ) : parsed.rows.length === 0 ? (\n <div className=\"grid h-full place-items-center bg-muted/30 p-4\">\n <div className=\"max-w-md rounded-lg border bg-background p-4 text-center text-sm shadow-xs\">\n <p className=\"font-medium\">Upload a CSV to preview</p>\n <p className=\"mt-1 text-muted-foreground\">\n Pass delimited text with the <code>data</code> prop or upload a\n CSV file.\n </p>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n className=\"mt-4\"\n loading={isPending}\n onClick={() => inputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className=\"size-4\" />\n Upload CSV\n </Button>\n </div>\n </div>\n ) : !glide ? (\n <div className=\"grid h-full place-items-center bg-background\">\n <Spinner className=\"size-4\" />\n </div>\n ) : (\n <glide.DataEditor\n ref={search ? gridRef : undefined}\n key={zoom}\n columns={columns}\n rows={parsed.rows.length}\n getCellContent={getCellContent}\n rowMarkers=\"number\"\n rowSelectionMode=\"multi\"\n gridSelection={search ? gridSelection : undefined}\n onGridSelectionChange={\n search ? handleGridSelectionChange : undefined\n }\n scrollToActiveCell={search}\n keybindings={{ search: true }}\n smoothScrollX\n smoothScrollY\n getCellsForSelection\n width=\"100%\"\n height=\"100%\"\n theme={theme}\n rowHeight={scale(34)}\n headerHeight={scale(36)}\n />\n )}\n </div>\n </div>\n )\n}\n"+ '"use client"\n\nimport * as React from "react"\nimport type * as GlideDataGrid from "@glideapps/glide-data-grid"\nimport type {\n DataEditorRef,\n GridCell,\n GridCellKind,\n GridColumn,\n GridSelection,\n Item,\n Theme,\n} from "@glideapps/glide-data-grid"\nimport {\n CompactSelection,\n emptyGridSelection,\n} from "@glideapps/glide-data-grid"\n\nimport "@glideapps/glide-data-grid/dist/index.css"\n\nimport {\n ArrowLeft01Icon,\n ArrowRight01Icon,\n Download01Icon,\n MinusSignCircleIcon,\n MoreHorizontalIcon,\n PlusSignCircleIcon,\n Search01Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport Papa from "papaparse"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\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 {\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"\n\nconst ZOOM_OPTIONS = [0.75, 1, 1.25, 1.5, 2] as const\nconst CSV_SEARCH_BATCH_ROW_COUNT = 500\nconst CSV_SEARCH_DEBOUNCE_MS = 300\n\ntype GlideDataGridModule = typeof GlideDataGrid\ntype CsvViewerProps = {\n className?: string\n data?: string\n search?: boolean\n}\n\ntype CsvSearchResult = {\n col: number\n row: number\n displayValue: string\n columnTitle: string\n}\n\nfunction toDisplayString(value: unknown): string {\n return value === null || value === undefined ? "" : String(value)\n}\n\nfunction normalizeHeaderTitle(header: string, index: number): string {\n const trimmed = header.trim()\n return trimmed.length > 0 ? trimmed : `Column ${index + 1}`\n}\n\nfunction columnIndexToA1(col: number) {\n let columnNumber = col + 1\n let columnName = ""\n\n while (columnNumber > 0) {\n const remainder = (columnNumber - 1) % 26\n columnName = String.fromCharCode(65 + remainder) + columnName\n columnNumber = Math.floor((columnNumber - 1) / 26)\n }\n\n return columnName\n}\n\nfunction cellAddressToA1(col: number, row: number) {\n return `${columnIndexToA1(col)}${row + 1}`\n}\n\nfunction cellMatchesQuery(displayValue: string, query: string) {\n return displayValue.toLowerCase().includes(query)\n}\n\nfunction createSingleCellSelection(cell: Item): GridSelection {\n const [col, row] = cell\n\n return {\n columns: CompactSelection.empty(),\n rows: CompactSelection.empty(),\n current: {\n cell,\n range: { x: col, y: row, width: 1, height: 1 },\n rangeStack: [],\n },\n }\n}\n\nasync function findCsvSearchResults(\n headers: string[],\n rows: string[][],\n rawQuery: string\n) {\n const query = rawQuery.trim().toLowerCase()\n if (!query) return []\n\n const results: CsvSearchResult[] = []\n const columnCount = Math.max(\n headers.length,\n rows.reduce((maxCount, row) => Math.max(maxCount, row.length), 0)\n )\n\n for (\n let batchStartRow = 0;\n batchStartRow < rows.length;\n batchStartRow += CSV_SEARCH_BATCH_ROW_COUNT\n ) {\n const batchEndRow = Math.min(\n batchStartRow + CSV_SEARCH_BATCH_ROW_COUNT,\n rows.length\n )\n\n for (let row = batchStartRow; row < batchEndRow; row += 1) {\n const rowValues = rows[row] ?? []\n\n for (let col = 0; col < columnCount; col += 1) {\n const displayValue = rowValues[col] ?? ""\n if (!cellMatchesQuery(displayValue, query)) continue\n\n results.push({\n col,\n row,\n displayValue,\n columnTitle: headers[col] ?? `Column ${col + 1}`,\n })\n }\n }\n\n if (batchEndRow < rows.length) {\n await new Promise<void>((resolve) => {\n window.setTimeout(resolve, 0)\n })\n }\n }\n\n return results\n}\n\nfunction parseDelimitedText(text: string): {\n headers: string[]\n rows: string[][]\n error: string | null\n} {\n const results = Papa.parse<Record<string, unknown>>(text, {\n header: true,\n skipEmptyLines: "greedy",\n })\n\n const objectRows = Array.isArray(results.data)\n ? results.data.filter(\n (row): row is Record<string, unknown> =>\n !!row && typeof row === "object" && !Array.isArray(row)\n )\n : []\n const metaFields = Array.isArray(results.meta.fields)\n ? results.meta.fields.map((field) => String(field))\n : []\n const fieldKeys =\n metaFields.length > 0\n ? metaFields\n : Object.keys(objectRows[0] ?? {}).filter(\n (key) => key !== "__parsed_extra"\n )\n const extraColumnCount = objectRows.reduce((maxCount, row) => {\n const extras = row.__parsed_extra\n return Array.isArray(extras) ? Math.max(maxCount, extras.length) : maxCount\n }, 0)\n const headers = [\n ...fieldKeys.map((field, index) => normalizeHeaderTitle(field, index)),\n ...Array.from(\n { length: extraColumnCount },\n (_, index) => `Extra ${index + 1}`\n ),\n ]\n\n const rows = objectRows.map((row) => {\n const baseValues = fieldKeys.map((fieldKey) =>\n toDisplayString(row[fieldKey])\n )\n const extras = Array.isArray(row.__parsed_extra)\n ? row.__parsed_extra.map((value) => toDisplayString(value))\n : []\n const paddedExtras =\n extras.length >= extraColumnCount\n ? extras.slice(0, extraColumnCount)\n : [\n ...extras,\n ...Array.from(\n { length: extraColumnCount - extras.length },\n () => ""\n ),\n ]\n\n return [...baseValues, ...paddedExtras]\n })\n\n const firstError =\n Array.isArray(results.errors) && results.errors.length > 0\n ? results.errors[0]\n : null\n\n return {\n headers,\n rows,\n error:\n rows.length === 0 && firstError\n ? String(firstError.message ?? "Could not parse CSV file.")\n : null,\n }\n}\n\nfunction ensureCsvExtension(fileName: string) {\n const lowerFileName = fileName.toLowerCase()\n return lowerFileName.endsWith(".csv") || lowerFileName.endsWith(".tsv")\n ? fileName\n : `${fileName}.csv`\n}\n\nfunction downloadTextFile(text: string, fileName: string, type: string) {\n const url = URL.createObjectURL(new Blob([text], { type }))\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\nfunction CsvFileActionsMenu({\n downloadDisabled,\n isPending,\n onDownload,\n onUploadClick,\n}: {\n downloadDisabled: boolean\n isPending: boolean\n onDownload: () => void\n onUploadClick: () => void\n}) {\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Open CSV actions"\n disabled={isPending}\n >\n <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="w-40">\n <DropdownMenuItem disabled={downloadDisabled} onClick={onDownload}>\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n Download\n </DropdownMenuItem>\n <DropdownMenuItem disabled={isPending} onClick={onUploadClick}>\n {isPending ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n )}\n Upload\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\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 CsvSearchPopover({\n headers,\n rows,\n gridRef,\n dataIdentity,\n controlsDisabled,\n onGridSelectionChange,\n}: {\n headers: string[]\n rows: string[][]\n gridRef: React.RefObject<DataEditorRef | null>\n dataIdentity: string\n controlsDisabled: boolean\n onGridSelectionChange: (selection: GridSelection) => void\n}) {\n const [searchDraft, setSearchDraft] = React.useState("")\n const [searchQuery, setSearchQuery] = React.useState("")\n const [searchResults, setSearchResults] = React.useState<CsvSearchResult[]>(\n []\n )\n const [activeResultIndex, setActiveResultIndex] = React.useState(0)\n const [isSearching, setIsSearching] = React.useState(false)\n const searchRequestIdRef = React.useRef(0)\n const appliedResultKeyRef = React.useRef("")\n const activeResult = searchResults[activeResultIndex] ?? null\n const activeResultKey = activeResult\n ? `${activeResult.row}:${activeResult.col}`\n : ""\n const hasActiveQuery = Boolean(searchQuery.trim())\n const resultLabel = isSearching\n ? "Searching"\n : !hasActiveQuery\n ? "No search"\n : searchResults.length\n ? `${activeResultIndex + 1} / ${searchResults.length}`\n : "No results"\n\n const runSearch = React.useCallback(\n (rawQuery: string) => {\n const nextQuery = rawQuery.trim()\n const requestId = searchRequestIdRef.current + 1\n searchRequestIdRef.current = requestId\n appliedResultKeyRef.current = ""\n setSearchQuery(nextQuery)\n setActiveResultIndex(0)\n\n if (!nextQuery) {\n setSearchResults([])\n setIsSearching(false)\n return\n }\n\n setIsSearching(true)\n void findCsvSearchResults(headers, rows, nextQuery)\n .then((nextResults) => {\n if (searchRequestIdRef.current !== requestId) return\n setSearchResults(nextResults)\n })\n .catch(() => {\n if (searchRequestIdRef.current !== requestId) return\n setSearchResults([])\n })\n .finally(() => {\n if (searchRequestIdRef.current !== requestId) return\n setIsSearching(false)\n })\n },\n [headers, rows]\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 }, CSV_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 setSearchResults([])\n setActiveResultIndex(0)\n setIsSearching(false)\n appliedResultKeyRef.current = ""\n onGridSelectionChange(emptyGridSelection)\n }, [onGridSelectionChange])\n\n const goToRelativeResult = React.useCallback(\n (direction: 1 | -1) => {\n if (!searchResults.length) return\n\n setActiveResultIndex((currentIndex) => {\n return (\n (currentIndex + direction + searchResults.length) %\n searchResults.length\n )\n })\n },\n [searchResults.length]\n )\n\n React.useEffect(() => {\n searchRequestIdRef.current += 1\n setSearchDraft("")\n setSearchQuery("")\n setSearchResults([])\n setActiveResultIndex(0)\n setIsSearching(false)\n appliedResultKeyRef.current = ""\n onGridSelectionChange(emptyGridSelection)\n }, [dataIdentity, onGridSelectionChange])\n\n React.useEffect(() => {\n if (!activeResult) return\n\n if (appliedResultKeyRef.current === activeResultKey) return\n appliedResultKeyRef.current = activeResultKey\n\n const cell: Item = [activeResult.col, activeResult.row]\n onGridSelectionChange(createSingleCellSelection(cell))\n\n const frame = window.requestAnimationFrame(() => {\n gridRef.current?.scrollTo(\n activeResult.col,\n activeResult.row,\n "both",\n 48,\n 48,\n {\n vAlign: "center",\n hAlign: "center",\n }\n )\n })\n\n return () => window.cancelAnimationFrame(frame)\n }, [activeResult, activeResultKey, gridRef, onGridSelectionChange])\n\n return (\n <Popover>\n <ToolbarTooltip label="Search CSV">\n <PopoverTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search CSV"\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 CSV"\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 && searchResults.length) {\n goToRelativeResult(-1)\n } else if (searchResults.length) {\n goToRelativeResult(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 {searchResults.length ? (\n <>\n <span className="text-primary">\n {activeResultIndex + 1}\n </span>\n {` / ${searchResults.length}`}\n </>\n ) : (\n resultLabel\n )}\n </div>\n {activeResult ? (\n <div className="mt-0.5 truncate">\n {activeResult.columnTitle}!\n {cellAddressToA1(activeResult.col, activeResult.row)}\n </div>\n ) : null}\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 || searchResults.length === 0}\n onClick={() => goToRelativeResult(-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 || searchResults.length === 0}\n onClick={() => goToRelativeResult(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 readIsDarkTheme() {\n return (\n typeof document !== "undefined" &&\n document.documentElement.classList.contains("dark")\n )\n}\n\nfunction useIsDarkTheme() {\n const [isDark, setIsDark] = React.useState(readIsDarkTheme)\n\n React.useEffect(() => {\n if (typeof document === "undefined") return\n\n const updateTheme = () => setIsDark(readIsDarkTheme())\n\n updateTheme()\n\n if (typeof MutationObserver === "undefined") return\n\n const observer = new MutationObserver(updateTheme)\n observer.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ["class"],\n })\n\n return () => observer.disconnect()\n }, [])\n\n return isDark\n}\n\nexport function CsvViewer({ className, data, search = false }: CsvViewerProps) {\n const inputRef = React.useRef<HTMLInputElement | null>(null)\n const gridRef = React.useRef<DataEditorRef | null>(null)\n const isDark = useIsDarkTheme()\n const [glide, setGlide] = React.useState<GlideDataGridModule | null>(null)\n const [zoom, setZoom] = React.useState<(typeof ZOOM_OPTIONS)[number]>(1)\n const [gridSelection, setGridSelection] =\n React.useState<GridSelection>(emptyGridSelection)\n const [parsed, setParsed] = React.useState(() =>\n data ? parseDelimitedText(data) : { headers: [], rows: [], error: null }\n )\n const [uploadedFileName, setUploadedFileName] = React.useState<string | null>(\n null\n )\n const [isPending, setIsPending] = React.useState(false)\n const [dataRevision, setDataRevision] = React.useState(0)\n\n const dataIdentity = React.useMemo(\n () =>\n `${dataRevision}:${parsed.headers.join("\\u0001")}:${parsed.rows.length}:${parsed.error ?? ""}`,\n [dataRevision, parsed.error, parsed.headers, parsed.rows.length]\n )\n\n const handleGridSelectionChange = React.useCallback(\n (selection: GridSelection) => {\n setGridSelection(selection)\n },\n []\n )\n\n React.useEffect(() => {\n if (data) {\n setParsed(parseDelimitedText(data))\n setUploadedFileName(null)\n setDataRevision((revision) => revision + 1)\n }\n }, [data])\n\n React.useEffect(() => {\n if (!search) {\n setGridSelection(emptyGridSelection)\n }\n }, [search])\n\n React.useEffect(() => {\n let mounted = true\n\n void import("@glideapps/glide-data-grid").then((module) => {\n if (mounted) {\n setGlide(module)\n }\n })\n\n return () => {\n mounted = false\n }\n }, [])\n\n const columnCount = Math.max(1, parsed.headers.length)\n const scale = React.useCallback(\n (value: number) => Math.round(value * zoom),\n [zoom]\n )\n const searchDisabled =\n Boolean(parsed.error) || parsed.rows.length === 0 || isPending\n\n const theme = React.useMemo<Partial<Theme>>(\n () => ({\n accentColor: isDark ? "#60a5fa" : "#2563eb",\n accentLight: isDark ? "#1d4ed826" : "#dbeafe",\n accentFg: "#ffffff",\n textDark: isDark ? "#e5e5e5" : "#171717",\n textMedium: isDark ? "#a3a3a3" : "#525252",\n textLight: isDark ? "#737373" : "#a3a3a3",\n textBubble: isDark ? "#f5f5f5" : "#171717",\n textHeader: isDark ? "#f5f5f5" : "#171717",\n textGroupHeader: isDark ? "#a3a3a3" : "#525252",\n bgCell: isDark ? "#0a0a0a" : "#ffffff",\n bgCellMedium: isDark ? "#171717" : "#fafafa",\n bgHeader: isDark ? "#171717" : "#fafafa",\n bgHeaderHasFocus: isDark ? "#262626" : "#f5f5f5",\n bgHeaderHovered: isDark ? "#262626" : "#f5f5f5",\n borderColor: isDark ? "#262626" : "#e5e5e5",\n horizontalBorderColor: isDark ? "#262626" : "#e5e5e5",\n cellHorizontalPadding: scale(8),\n cellVerticalPadding: Math.max(2, scale(3)),\n headerIconSize: scale(18),\n baseFontStyle: `${scale(13)}px`,\n headerFontStyle: `600 ${scale(13)}px`,\n markerFontStyle: `${scale(11)}px`,\n fontFamily: \'-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif\',\n editorFontSize: `${scale(13)}px`,\n }),\n [isDark, scale]\n )\n\n const columns = React.useMemo<GridColumn[]>(\n () =>\n Array.from({ length: columnCount }, (_, index) => ({\n id: `column-${index}`,\n title: parsed.headers[index] ?? `Column ${index + 1}`,\n width: scale(index === 0 ? 180 : 160),\n })),\n [columnCount, parsed.headers, scale]\n )\n\n const getCellContent = React.useCallback(\n ([col, row]: Item): GridCell => {\n const value = parsed.rows[row]?.[col] ?? ""\n const textKind = glide?.GridCellKind.Text as GridCellKind.Text\n\n return {\n kind: textKind,\n data: value,\n displayData: value,\n allowOverlay: true,\n readonly: true,\n }\n },\n [glide, parsed.rows]\n )\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n if (!file) return\n\n setIsPending(true)\n try {\n const text = await file.text()\n setParsed(parseDelimitedText(text))\n setUploadedFileName(file.name)\n setDataRevision((revision) => revision + 1)\n } catch (error) {\n setParsed({\n headers: [],\n rows: [],\n error:\n error instanceof Error ? error.message : "Could not read CSV file.",\n })\n setDataRevision((revision) => revision + 1)\n } finally {\n event.target.value = ""\n setIsPending(false)\n }\n }\n\n function stepZoom(direction: -1 | 1) {\n const index = ZOOM_OPTIONS.indexOf(zoom)\n const nextIndex = Math.min(\n ZOOM_OPTIONS.length - 1,\n Math.max(0, index + direction)\n )\n setZoom(ZOOM_OPTIONS[nextIndex])\n }\n\n function handleDownload() {\n const text = Papa.unparse({\n fields: parsed.headers,\n data: parsed.rows,\n })\n\n downloadTextFile(\n text,\n ensureCsvExtension(uploadedFileName ?? "data.csv"),\n "text/csv;charset=utf-8"\n )\n }\n\n return (\n <div\n className={cn(\n "flex h-[560px] w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n <div className="flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2">\n <TooltipProvider>\n <div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1">\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom out"\n disabled={zoom <= ZOOM_OPTIONS[0]}\n onClick={() => stepZoom(-1)}\n >\n <HugeiconsIcon\n icon={MinusSignCircleIcon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={zoom.toString()}\n onValueChange={(value) =>\n setZoom(Number(value) as (typeof ZOOM_OPTIONS)[number])\n }\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(zoom * 100)}%</SelectValue>\n </SelectTrigger>\n <SelectContent align="end" alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((option) => (\n <SelectItem key={option} value={option.toString()}>\n {Math.round(option * 100)}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom in"\n disabled={zoom >= ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]}\n onClick={() => stepZoom(1)}\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </div>\n {search ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <CsvSearchPopover\n headers={parsed.headers}\n rows={parsed.rows}\n gridRef={gridRef}\n dataIdentity={dataIdentity}\n controlsDisabled={searchDisabled}\n onGridSelectionChange={handleGridSelectionChange}\n />\n </>\n ) : null}\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <input\n ref={inputRef}\n type="file"\n accept=".csv,.tsv,text/csv,text/tab-separated-values"\n className="hidden"\n onChange={handleUpload}\n />\n <CsvFileActionsMenu\n downloadDisabled={\n Boolean(parsed.error) ||\n isPending ||\n (parsed.headers.length === 0 && parsed.rows.length === 0)\n }\n isPending={isPending}\n onDownload={handleDownload}\n onUploadClick={() => inputRef.current?.click()}\n />\n </div>\n </TooltipProvider>\n </div>\n <div className="min-h-0 flex-1">\n {parsed.error ? (\n <div className="flex h-full items-center justify-center px-4 text-center text-sm text-destructive">\n {parsed.error}\n </div>\n ) : parsed.rows.length === 0 ? (\n <div className="grid h-full place-items-center bg-muted/30 p-4">\n <div className="max-w-md rounded-lg border bg-background p-4 text-center text-sm shadow-xs">\n <p className="font-medium">Upload a CSV to preview</p>\n <p className="mt-1 text-muted-foreground">\n Pass delimited text with the <code>data</code> prop or upload a\n CSV file.\n </p>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n loading={isPending}\n onClick={() => inputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload CSV\n </Button>\n </div>\n </div>\n ) : !glide ? (\n <div className="grid h-full place-items-center bg-background">\n <Spinner className="size-4" />\n </div>\n ) : (\n <glide.DataEditor\n ref={search ? gridRef : undefined}\n key={zoom}\n columns={columns}\n rows={parsed.rows.length}\n getCellContent={getCellContent}\n rowMarkers="number"\n rowSelectionMode="multi"\n gridSelection={search ? gridSelection : undefined}\n onGridSelectionChange={\n search ? handleGridSelectionChange : undefined\n }\n scrollToActiveCell={search}\n keybindings={{ search: true }}\n smoothScrollX\n smoothScrollY\n getCellsForSelection\n width="100%"\n height="100%"\n theme={theme}\n rowHeight={scale(34)}\n headerHeight={scale(36)}\n />\n )}\n </div>\n </div>\n )\n}\n'export function CsvViewerSource() {return (diff --git a/apps/v4/components/document-splitter-docs.tsx b/apps/v4/components/document-splitter-docs.tsxindex 4a65e9e..24707ca 100644--- a/apps/v4/components/document-splitter-docs.tsx+++ b/apps/v4/components/document-splitter-docs.tsx@@ -1161,7 +1161,6 @@ function WorkbookViewerPane({onIsDarkChange={setIsDark}onUploadClick={() => {}}renderTableHeaderMenu={(props) => <WorkbookTableHeaderMenu {...props} />}- rounded={false}showNightRenderToggleshowUploadButton={false}workbookIdentity={workbookIdentity}diff --git a/apps/v4/components/docx-editor-docs.tsx b/apps/v4/components/docx-editor-docs.tsxindex 66ca677..4e76d08 100644--- a/apps/v4/components/docx-editor-docs.tsx+++ b/apps/v4/components/docx-editor-docs.tsx@@ -84,7 +84,7 @@ export function DocxEditorExample() {}`const docxEditorSourceCode =- '"use client"\n\nimport * as React from "react"\nimport { PreviewCard as PreviewCardPrimitive } from "@base-ui/react/preview-card"\nimport {\n DocxEditorViewer,\n paragraphLetterheadFloatSideAtNodeIndex,\n useDocxBorders,\n useDocxComments,\n useDocxDocumentTheme,\n useDocxEditor,\n useDocxLineSpacing,\n useDocxPageLayout,\n useDocxParagraphStyles,\n useDocxTrackChanges,\n useDocxViewerThumbnails,\n type DocxBorderContext,\n type DocxBorderPreset,\n type DocxCommentCardRenderProps,\n type DocxDocumentTheme,\n type DocxEditorController,\n type DocxTrackedChangeCardRenderProps,\n type ParagraphStyleDefinition,\n} from "@extend-ai/react-docx"\nimport {\n ArrowExpandDiagonal01Icon,\n ArrowExpandDiagonal02Icon,\n BorderAll01Icon,\n BorderBottom01Icon,\n BorderHorizontalIcon,\n BorderInnerIcon,\n BorderLeft01Icon,\n BorderNone01Icon,\n BorderRight01Icon,\n BorderTop01Icon,\n BorderVerticalIcon,\n ColumnsThreeCogIcon,\n Comment01Icon,\n Download01Icon,\n EditOffIcon,\n FileDiffIcon,\n HighlighterIcon,\n ImageAdd01Icon,\n LeftToRightListBulletIcon,\n LeftToRightListNumberIcon,\n LineIcon,\n Link02Icon,\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n Redo02Icon,\n SidebarLeftIcon,\n Sun03Icon,\n TableIcon,\n TextAlignCenterIcon,\n TextAlignJustifyLeftIcon,\n TextAlignLeft01Icon,\n TextAlignRight01Icon,\n TextBoldIcon,\n TextColorIcon,\n TextItalicIcon,\n TextStrikethroughIcon,\n TextSubscriptIcon,\n TextSuperscriptIcon,\n TextUnderlineIcon,\n Undo02Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\n\nimport { cn } from "@/lib/utils"\nimport { Badge } from "@/components/ui/badge"\nimport { Button } from "@/components/ui/button"\nimport { Card } from "@/components/ui/card"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/ui/document-viewer-sidebar"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { Input } from "@/components/ui/input"\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"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst DOCX_EDITOR_DEFAULT_ZOOM_SCALE = 100\nconst ZOOM_OPTIONS = [50, 75, 90, 100, 110, 125, 150, 175, 200] as const\nconst FONT_FAMILIES = [\n "Calibri",\n "Arial",\n "Times New Roman",\n "Georgia",\n "Helvetica",\n "Courier New",\n] as const\nconst FONT_SIZE_OPTIONS = [\n 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48,\n] as const\nconst LINE_SPACING_OPTIONS = [1, 1.15, 1.2, 1.5, 2, 2.5, 3] as const\nconst FALLBACK_PARAGRAPH_STYLE_OPTIONS = [\n { id: "Normal", name: "Body" },\n { id: "Heading1", name: "Heading 1" },\n { id: "Heading2", name: "Heading 2" },\n { id: "Heading3", name: "Heading 3" },\n] as const\nconst HIGHLIGHT_COLORS = [\n { label: "Yellow", value: "yellow", color: "#fff59d" },\n { label: "Green", value: "green", color: "#bbf7d0" },\n { label: "Cyan", value: "cyan", color: "#a5f3fc" },\n { label: "Magenta", value: "magenta", color: "#f5d0fe" },\n { label: "Red", value: "red", color: "#fecaca" },\n { label: "Blue", value: "blue", color: "#bfdbfe" },\n] as const\nconst HIGHLIGHT_PREVIEW_COLORS: Record<string, string> = {\n black: "#111827",\n white: "#ffffff",\n ...Object.fromEntries(\n HIGHLIGHT_COLORS.map((option) => [option.value, option.color])\n ),\n}\nconst DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\nconst DEFAULT_HEADING_PREVIEW_RUN_STYLES: Record<\n 1 | 2 | 3 | 4 | 5 | 6,\n NonNullable<ParagraphStyleDefinition["runStyle"]>\n> = {\n 1: {\n fontFamily: "Calibri Light",\n fontSizePt: 16,\n bold: true,\n color: "#2f5496",\n },\n 2: {\n fontFamily: "Calibri Light",\n fontSizePt: 13,\n bold: true,\n color: "#2f5496",\n },\n 3: {\n fontFamily: "Calibri",\n fontSizePt: 12,\n bold: true,\n color: "#1f3763",\n },\n 4: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n 5: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n 6: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n}\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n}\n\ntype BorderControlOption = {\n id: DocxBorderPreset\n label: string\n contexts?: DocxBorderContext[]\n separatorBefore?: boolean\n}\n\nconst BORDER_CONTROL_OPTIONS: BorderControlOption[] = [\n { id: "bottom", label: "Bottom Border" },\n { id: "top", label: "Top Border" },\n { id: "left", label: "Left Border" },\n { id: "right", label: "Right Border" },\n { id: "none", label: "No Border", separatorBefore: true },\n { id: "all", label: "All Borders" },\n { id: "outside", label: "Outside Borders" },\n { id: "inside", label: "Inside Borders", contexts: ["table"] },\n {\n id: "inside-horizontal",\n label: "Inside Horizontal Border",\n contexts: ["table"],\n },\n {\n id: "inside-vertical",\n label: "Inside Vertical Border",\n contexts: ["table"],\n },\n {\n id: "diagonal-down",\n label: "Diagonal Down Border",\n contexts: ["table"],\n separatorBefore: true,\n },\n { id: "diagonal-up", label: "Diagonal Up Border", contexts: ["table"] },\n { id: "horizontal-line", label: "Horizontal Line", separatorBefore: true },\n]\n\nfunction borderControlOptionIcon(optionId: DocxBorderPreset) {\n switch (optionId) {\n case "bottom":\n return BorderBottom01Icon\n case "top":\n return BorderTop01Icon\n case "left":\n return BorderLeft01Icon\n case "right":\n return BorderRight01Icon\n case "none":\n return BorderNone01Icon\n case "inside":\n return BorderInnerIcon\n case "inside-horizontal":\n return BorderHorizontalIcon\n case "inside-vertical":\n return BorderVerticalIcon\n case "diagonal-down":\n return ArrowExpandDiagonal01Icon\n case "diagonal-up":\n return ArrowExpandDiagonal02Icon\n case "horizontal-line":\n return LineIcon\n default:\n return BorderAll01Icon\n }\n}\n\nasync function loadDocxFile(\n url: string,\n displayFileName: string\n): Promise<File> {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n return new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n}\n\nfunction formatDocumentName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "document.docx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction getNextZoomScale(currentZoomScale: number, direction: 1 | -1) {\n const currentIndex = ZOOM_OPTIONS.indexOf(\n currentZoomScale as (typeof ZOOM_OPTIONS)[number]\n )\n let fallbackIndex = -1\n\n if (direction > 0) {\n fallbackIndex = ZOOM_OPTIONS.findIndex((value) => value > currentZoomScale)\n } else {\n for (let index = ZOOM_OPTIONS.length - 1; index >= 0; index -= 1) {\n if (ZOOM_OPTIONS[index] < currentZoomScale) {\n fallbackIndex = index\n break\n }\n }\n }\n\n const resolvedIndex = currentIndex >= 0 ? currentIndex : fallbackIndex\n if (resolvedIndex < 0) return currentZoomScale\n\n const nextIndex = Math.min(\n Math.max(resolvedIndex + direction, 0),\n ZOOM_OPTIONS.length - 1\n )\n\n return ZOOM_OPTIONS[nextIndex] ?? currentZoomScale\n}\n\nfunction normalizeDocxZoomScale(value: number | undefined): number {\n return typeof value === "number" &&\n ZOOM_OPTIONS.includes(value as (typeof ZOOM_OPTIONS)[number])\n ? value\n : DOCX_EDITOR_DEFAULT_ZOOM_SCALE\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === "string" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes("padding"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\n}\n\nfunction normalizeHexColor(value?: string, fallback = "#111827") {\n if (!value) return fallback\n\n const trimmed = value.trim()\n const threeDigit = /^#([0-9a-f]{3})$/i.exec(trimmed)\n if (threeDigit?.[1]) {\n const [red, green, blue] = threeDigit[1].split("")\n return `#${red}${red}${green}${green}${blue}${blue}`.toLowerCase()\n }\n\n const sixDigit = /^#([0-9a-f]{6})$/i.exec(trimmed)\n if (sixDigit?.[1]) {\n return `#${sixDigit[1].toLowerCase()}`\n }\n\n return fallback\n}\n\nfunction inferParagraphStyleHeadingLevel(value?: string) {\n if (!value) return undefined\n\n const match = value.match(/(?:^|[\\s_-])(?:heading|h)\\s*([1-6])(?:$|[\\s_-])/i)\n const level = match?.[1] ? Number(match[1]) : NaN\n\n return level >= 1 && level <= 6 ? (level as 1 | 2 | 3 | 4 | 5 | 6) : undefined\n}\n\nfunction resolveParagraphStyleHeadingLevel(option?: ParagraphStyleDefinition) {\n if (\n Number.isFinite(option?.headingLevel) &&\n option?.headingLevel &&\n option.headingLevel >= 1 &&\n option.headingLevel <= 6\n ) {\n return option.headingLevel as 1 | 2 | 3 | 4 | 5 | 6\n }\n\n return (\n inferParagraphStyleHeadingLevel(option?.id) ??\n inferParagraphStyleHeadingLevel(option?.name)\n )\n}\n\nfunction resolveParagraphStyleRunPreview(option?: ParagraphStyleDefinition) {\n if (!option) return undefined\n\n const headingLevel = resolveParagraphStyleHeadingLevel(option)\n const headingRunStyle = headingLevel\n ? DEFAULT_HEADING_PREVIEW_RUN_STYLES[headingLevel]\n : undefined\n\n return headingRunStyle\n ? {\n ...headingRunStyle,\n ...(option.runStyle ?? {}),\n }\n : option.runStyle\n}\n\nfunction resolveHighlightPreview(value?: string) {\n if (!value) return undefined\n\n const normalized = value.trim().toLowerCase()\n if (!normalized) return undefined\n\n const hex = normalizeHexColor(normalized, "")\n if (hex) return hex\n\n return HIGHLIGHT_PREVIEW_COLORS[normalized]\n}\n\nfunction themedPreviewColor(\n color: string | undefined,\n documentTheme: DocxDocumentTheme\n) {\n if (documentTheme !== "dark") return color\n if (!color) return "#f3f4f6"\n\n const normalized = color.trim().toLowerCase()\n if (\n normalized === "#000" ||\n normalized === "#000000" ||\n normalized === "#111111" ||\n normalized === "#111827" ||\n normalized === "black" ||\n normalized === "rgb(0,0,0)" ||\n normalized === "rgb(0, 0, 0)"\n ) {\n return "#f3f4f6"\n }\n\n return color\n}\n\nfunction paragraphStylePreviewStyle(\n option: ParagraphStyleDefinition,\n documentTheme: DocxDocumentTheme\n): React.CSSProperties {\n const runStyle = resolveParagraphStyleRunPreview(option)\n const textDecoration = [\n runStyle?.underline ? "underline" : "",\n runStyle?.strike ? "line-through" : "",\n ]\n .filter(Boolean)\n .join(" ")\n\n return {\n textAlign: option.align ?? "left",\n fontFamily: runStyle?.fontFamily,\n fontSize: runStyle?.fontSizePt ? `${runStyle.fontSizePt}pt` : "11pt",\n fontWeight:\n runStyle?.bold !== undefined ? (runStyle.bold ? 700 : 400) : undefined,\n fontStyle: runStyle?.italic ? "italic" : undefined,\n textDecoration: textDecoration || undefined,\n color:\n runStyle?.color !== undefined\n ? themedPreviewColor(normalizeHexColor(runStyle.color), documentTheme)\n : undefined,\n backgroundColor: resolveHighlightPreview(runStyle?.highlight),\n lineHeight: 1,\n whiteSpace: "pre-wrap",\n }\n}\n\nfunction paragraphStylePreviewTriggerId(prefix: string, styleId: string) {\n return `${prefix}-paragraph-style-preview-${styleId.replace(\n /[^a-zA-Z0-9_-]/g,\n "_"\n )}`\n}\n\nfunction parseToolbarSectionColumns(\n sectionPropertiesXml?: string\n): { count: number; gapPx: number } | undefined {\n if (!sectionPropertiesXml) return undefined\n\n const columnsTag = sectionPropertiesXml.match(/<w:cols\\b[^>]*\\/?>/i)?.[0]\n if (!columnsTag) return undefined\n\n const countRaw = columnsTag.match(/\\bw:num="(\\d+)"/i)?.[1]\n const count = countRaw ? Number(countRaw) : 1\n if (!Number.isFinite(count) || count <= 1) return undefined\n\n const gapRaw = columnsTag.match(/\\bw:space="(\\d+)"/i)?.[1]\n const gapTwips = gapRaw ? Number(gapRaw) : 720\n const gapPx = Math.max(0, Math.round((gapTwips * 96) / 1440))\n\n return {\n count: Math.max(2, Math.round(count)),\n gapPx,\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 EditorLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction ToolbarIconButton({\n active,\n children,\n label,\n ...props\n}: React.ComponentProps<typeof Button> & {\n active?: boolean\n label: string\n}) {\n return (\n <ToolbarTooltip label={label}>\n <Button\n type="button"\n variant={active ? "secondary" : "ghost"}\n size="icon-sm"\n aria-label={label}\n data-pressed={active ? "" : undefined}\n {...props}\n >\n {children}\n </Button>\n </ToolbarTooltip>\n )\n}\n\nfunction ToolbarColorInput({\n color,\n disabled,\n icon,\n label,\n onChange,\n}: {\n color: string\n disabled?: boolean\n icon: typeof TextColorIcon\n label: string\n onChange: (color: string) => void\n}) {\n return (\n <ToolbarTooltip label={label}>\n <label\n className={cn(\n "relative inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-lg border border-transparent text-foreground transition-colors hover:bg-accent",\n disabled && "pointer-events-none opacity-64"\n )}\n aria-label={label}\n >\n <HugeiconsIcon icon={icon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: color }}\n />\n <input\n type="color"\n aria-label={label}\n disabled={disabled}\n value={color}\n className="sr-only"\n onChange={(event) => onChange(event.target.value)}\n />\n </label>\n </ToolbarTooltip>\n )\n}\n\nfunction DocxSidebarThumbnail({\n canvasRef,\n displayFileName,\n hasError,\n isActive,\n isLoading,\n pageNumber,\n pixelHeightPx,\n pixelWidthPx,\n previewAspectRatio,\n}: {\n canvasRef: React.RefCallback<HTMLCanvasElement>\n displayFileName: string\n hasError: boolean\n isActive: boolean\n isLoading: boolean\n pageNumber: number\n pixelHeightPx: number\n pixelWidthPx: number\n previewAspectRatio: number\n}) {\n return (\n <FileThumbnail\n file={{\n name: `${displayFileName} page ${pageNumber}`,\n type: DOCX_MIME_TYPE,\n }}\n previewAspectRatio={previewAspectRatio}\n previewClassName="rounded-md bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n isLoading={isLoading}\n hasError={hasError}\n className={cn(\n "w-[92px] rounded-md border-0 shadow-xs ring-0 transition-shadow duration-150",\n isActive && "shadow-sm"\n )}\n />\n )\n}\n\nfunction ParagraphStylePreviewCard({\n documentTheme,\n option,\n}: {\n documentTheme: DocxDocumentTheme\n option: ParagraphStyleDefinition\n}) {\n const surfaceStyle: React.CSSProperties =\n documentTheme === "dark"\n ? {\n backgroundColor: "#111827",\n borderColor: "#374151",\n color: "#f3f4f6",\n }\n : {\n backgroundColor: "#ffffff",\n borderColor: "#d4d4d8",\n color: "#111827",\n }\n const secondaryTextColor = documentTheme === "dark" ? "#9ca3af" : "#6b7280"\n\n return (\n <div className="w-[260px] p-3">\n <p className="text-[10px] font-medium tracking-wide text-muted-foreground uppercase">\n Style Preview\n </p>\n <div className="mt-2 rounded-sm border p-2.5" style={surfaceStyle}>\n <p style={paragraphStylePreviewStyle(option, documentTheme)}>\n {option.name}\n </p>\n <p\n className="mt-1 text-[11px]"\n style={{\n color: secondaryTextColor,\n textAlign: option.align ?? "left",\n }}\n >\n The quick brown fox jumps over the lazy dog.\n </p>\n </div>\n </div>\n )\n}\n\nfunction trackedChangeBadgeVariant(\n kind: DocxTrackedChangeCardRenderProps["change"]["kind"]\n): React.ComponentProps<typeof Badge>["variant"] {\n switch (kind) {\n case "insertion":\n case "move-to":\n return "success"\n case "deletion":\n case "move-from":\n return "error"\n default:\n return "warning"\n }\n}\n\nfunction trackedChangeBadgeLabel({\n change,\n kindLabel,\n}: Pick<DocxTrackedChangeCardRenderProps, "change" | "kindLabel">) {\n switch (change.kind) {\n case "insertion":\n return "Inserted"\n case "deletion":\n return "Removed"\n case "move-from":\n return "Moved from"\n case "move-to":\n return "Moved to"\n default:\n return kindLabel\n }\n}\n\nfunction DocxAnnotationCard({\n anchorText,\n badge,\n badgeVariant = "outline",\n date,\n meta,\n snippet,\n style,\n}: {\n anchorText?: string\n badge: string\n badgeVariant?: React.ComponentProps<typeof Badge>["variant"]\n date?: string\n meta: string\n snippet: string\n style: React.CSSProperties\n}) {\n return (\n <Card\n style={style}\n className="pointer-events-auto box-border gap-2 rounded-lg bg-card/95 p-2 text-card-foreground shadow-sm before:rounded-[7px]"\n >\n <div className="flex min-w-0 items-start justify-between gap-2">\n <div className="min-w-0 text-[11px] leading-tight font-medium text-muted-foreground">\n <div className="truncate">{meta}</div>\n {date ? <div className="mt-0.5 truncate">{date}</div> : null}\n </div>\n <Badge\n variant={badgeVariant}\n size="sm"\n className="max-w-[92px] truncate"\n >\n {badge}\n </Badge>\n </div>\n {anchorText ? (\n <div className="rounded-md bg-muted/60 px-2 py-1 text-[11px] leading-snug text-muted-foreground italic">\n {anchorText}\n </div>\n ) : null}\n <div className="text-xs leading-snug break-words">{snippet}</div>\n </Card>\n )\n}\n\nfunction renderDocxTrackedChangeCard({\n change,\n formattedDate,\n kindLabel,\n snippet,\n style,\n}: DocxTrackedChangeCardRenderProps) {\n return (\n <DocxAnnotationCard\n badge={trackedChangeBadgeLabel({ change, kindLabel })}\n badgeVariant={trackedChangeBadgeVariant(change.kind)}\n date={formattedDate}\n meta={change.author?.trim() || "Unknown author"}\n snippet={snippet}\n style={style}\n />\n )\n}\n\nfunction renderDocxCommentCard({\n comment,\n formattedDate,\n snippet,\n style,\n}: DocxCommentCardRenderProps) {\n const badge = comment.resolved\n ? "Resolved"\n : comment.parentId !== undefined\n ? "Reply"\n : "Comment"\n\n return (\n <DocxAnnotationCard\n anchorText={comment.anchorText}\n badge={badge}\n badgeVariant={comment.resolved ? "secondary" : "info"}\n date={formattedDate}\n meta={comment.author?.trim() || "Unknown author"}\n snippet={snippet}\n style={style}\n />\n )\n}\n\nfunction DocxEditorToolbar({\n activePage,\n controlsDisabled,\n editor,\n isReadOnly,\n onImageUploadClick,\n onIsDarkChange,\n onIsReadOnlyChange,\n onOpenLinkEditor,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showNightRenderToggle,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n editor: DocxEditorController\n isReadOnly: boolean\n onImageUploadClick: () => void\n onIsDarkChange: (checked: boolean) => void\n onIsReadOnlyChange: (checked: boolean) => void\n onOpenLinkEditor: () => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showNightRenderToggle: boolean\n zoomScale: number\n}) {\n const { documentTheme, setDocumentTheme } = useDocxDocumentTheme(editor)\n const { layout: pageLayout } = useDocxPageLayout(editor)\n const { paragraphStyles, selectedParagraphStyleId, setParagraphStyle } =\n useDocxParagraphStyles(editor)\n const { lineSpacing, setLineSpacing } = useDocxLineSpacing(editor)\n const { borderContext, activeBorderPresets, applyBorderPreset } =\n useDocxBorders(editor)\n const { showTrackedChanges, setShowTrackedChanges } =\n useDocxTrackChanges(editor)\n const { showComments, setShowComments } = useDocxComments(editor)\n const selectedRunStyle = editor.selectedRunStyle\n const selectedParagraph = editor.selectedParagraph\n const paragraphStyleOptions: ParagraphStyleDefinition[] =\n paragraphStyles.length > 0\n ? paragraphStyles\n : [...FALLBACK_PARAGRAPH_STYLE_OPTIONS]\n const selectedParagraphStyleValue =\n selectedParagraphStyleId ??\n paragraphStyleOptions.find((option) => "isDefault" in option)?.id ??\n paragraphStyleOptions[0]?.id ??\n "Normal"\n const selectedParagraphStyleOption =\n paragraphStyleOptions.find(\n (option) => option.id === selectedParagraphStyleValue\n ) ??\n paragraphStyleOptions[0] ??\n FALLBACK_PARAGRAPH_STYLE_OPTIONS[0]\n const paragraphStylePreviewHandle = React.useMemo(\n () => PreviewCardPrimitive.createHandle<ParagraphStyleDefinition>(),\n []\n )\n const paragraphStylePreviewIdPrefix = React.useId()\n const [isParagraphStyleMenuOpen, setIsParagraphStyleMenuOpen] =\n React.useState(false)\n const openParagraphStylePreview = React.useCallback(\n (styleId: string) => {\n paragraphStylePreviewHandle.open(\n paragraphStylePreviewTriggerId(paragraphStylePreviewIdPrefix, styleId)\n )\n },\n [paragraphStylePreviewHandle, paragraphStylePreviewIdPrefix]\n )\n const selectedLineSpacingValue = React.useMemo(() => {\n const current = Number.isFinite(lineSpacing.multiple)\n ? lineSpacing.multiple\n : 1\n const nearest = LINE_SPACING_OPTIONS.reduce((closest, candidate) => {\n return Math.abs(candidate - current) < Math.abs(closest - current)\n ? candidate\n : closest\n }, LINE_SPACING_OPTIONS[0])\n return String(nearest)\n }, [lineSpacing.multiple])\n const textColorValue = normalizeHexColor(selectedRunStyle?.color)\n const highlightColor =\n HIGHLIGHT_COLORS.find(\n (option) => option.value === selectedRunStyle?.highlight\n )?.color ?? "#fff59d"\n const activeNodeIndex =\n editor.selection.kind === "paragraph"\n ? editor.selection.nodeIndex\n : editor.selection.tableIndex\n const letterheadColumns =\n editor.selection.kind === "paragraph" &&\n paragraphLetterheadFloatSideAtNodeIndex(\n editor.model.nodes,\n editor.selection.nodeIndex\n )\n ? { count: 2, gapPx: 28 }\n : undefined\n const sections = editor.model.metadata.sections ?? []\n const activeSection = sections\n .filter((section) => section.startNodeIndex <= activeNodeIndex)\n .at(-1)\n const activeColumns =\n letterheadColumns ??\n parseToolbarSectionColumns(activeSection?.sectionPropertiesXml) ??\n parseToolbarSectionColumns(editor.model.metadata.sectionPropertiesXml) ??\n pageLayout.columns\n const activeBorderControlOptions = BORDER_CONTROL_OPTIONS.filter(\n (option) => activeBorderPresets[option.id]\n )\n const borderTriggerLabel =\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].label\n : "Borders"\n const borderTriggerIcon = borderControlOptionIcon(\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].id\n : "all"\n )\n const canEdit = !controlsDisabled && !isReadOnly\n const canZoomIn = zoomScale < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n const canZoomOut = zoomScale > ZOOM_OPTIONS[0]\n\n const preserveTextSelection = React.useCallback(\n (event: React.MouseEvent<HTMLElement> | React.PointerEvent<HTMLElement>) =>\n event.preventDefault(),\n []\n )\n\n return (\n <div className="bg-background">\n <TooltipProvider>\n <div className="flex min-h-11 items-center gap-2 overflow-x-auto overflow-y-hidden border-b px-3">\n <ToolbarIconButton\n label="Toggle pages"\n disabled={controlsDisabled}\n onClick={onToggleSidebar}\n >\n <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />\n </ToolbarIconButton>\n <div className="min-w-28 text-sm whitespace-nowrap text-primary">\n Page {pageCount ? activePage : 1} of {pageCount || "-"}\n </div>\n <div className="min-w-0 flex-1" />\n {showNightRenderToggle ? (\n <>\n <ToolbarIconButton\n label={\n documentTheme === "dark"\n ? "Use light document"\n : "Use dark document"\n }\n disabled={controlsDisabled}\n onClick={() => {\n const nextIsDark = documentTheme !== "dark"\n setDocumentTheme(nextIsDark ? "dark" : "light")\n onIsDarkChange(nextIsDark)\n }}\n >\n <HugeiconsIcon\n icon={documentTheme === "dark" ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </ToolbarIconButton>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <ToolbarIconButton\n label="Show tracked changes"\n active={showTrackedChanges}\n disabled={controlsDisabled}\n onClick={() => setShowTrackedChanges(!showTrackedChanges)}\n >\n <HugeiconsIcon icon={FileDiffIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Show comments"\n active={showComments}\n disabled={controlsDisabled}\n onClick={() => setShowComments(!showComments)}\n >\n <HugeiconsIcon icon={Comment01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label={isReadOnly ? "Switch to edit mode" : "Switch to read-only"}\n active={isReadOnly}\n disabled={controlsDisabled}\n onClick={() => onIsReadOnlyChange(!isReadOnly)}\n >\n <HugeiconsIcon icon={EditOffIcon} className="size-4" />\n </ToolbarIconButton>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <ToolbarIconButton\n label="Import DOCX"\n disabled={editor.isImporting}\n onClick={onUploadClick}\n >\n {editor.isImporting ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n )}\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Download DOCX"\n disabled={controlsDisabled || editor.isImporting}\n onClick={editor.exportDocx}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex min-h-12 flex-wrap items-center gap-2 border-b px-3 py-2">\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Undo"\n disabled={!editor.canUndo || isReadOnly}\n onClick={editor.undo}\n >\n <HugeiconsIcon icon={Undo02Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Redo"\n disabled={!editor.canRedo || isReadOnly}\n onClick={editor.redo}\n >\n <HugeiconsIcon icon={Redo02Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <PreviewCardPrimitive.Root handle={paragraphStylePreviewHandle}>\n {({ payload }) => {\n const previewOption = payload ?? selectedParagraphStyleOption\n\n return (\n <>\n <Select\n value={selectedParagraphStyleValue}\n onOpenChange={(open) => {\n setIsParagraphStyleMenuOpen(open)\n\n if (!open) {\n paragraphStylePreviewHandle.close()\n return\n }\n\n window.requestAnimationFrame(() => {\n openParagraphStylePreview(selectedParagraphStyleValue)\n })\n }}\n onValueChange={(value) => {\n if (value) {\n setParagraphStyle(value)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[136px] min-w-[136px]"\n aria-label="Paragraph style"\n >\n <SelectValue placeholder="Style" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-40 min-w-[210px]"\n >\n {paragraphStyleOptions.map((option) => {\n const previewTriggerId = paragraphStylePreviewTriggerId(\n paragraphStylePreviewIdPrefix,\n option.id\n )\n\n return (\n <SelectItem\n key={option.id}\n value={option.id}\n label={option.name}\n className="relative min-w-[190px]"\n onFocus={() => openParagraphStylePreview(option.id)}\n onPointerEnter={() =>\n openParagraphStylePreview(option.id)\n }\n >\n <span className="block truncate">\n {option.name}\n </span>\n <PreviewCardPrimitive.Trigger\n id={previewTriggerId}\n handle={paragraphStylePreviewHandle}\n payload={option}\n delay={0}\n closeDelay={120}\n render={\n <span\n aria-hidden="true"\n className="pointer-events-none absolute inset-0 block"\n />\n }\n />\n </SelectItem>\n )\n })}\n </SelectContent>\n </Select>\n {isParagraphStyleMenuOpen && previewOption ? (\n <PreviewCardPrimitive.Portal>\n <PreviewCardPrimitive.Positioner\n side="right"\n align="start"\n sideOffset={10}\n alignOffset={-4}\n className="z-40 transition-[top,left,right,bottom,transform] duration-100 ease-out data-instant:transition-none"\n >\n <PreviewCardPrimitive.Popup\n data-slot="paragraph-style-preview-card"\n className="origin-(--transform-origin) rounded-lg border bg-popover text-popover-foreground shadow-lg/5 transition-opacity duration-100 outline-none not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:opacity-0 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]"\n >\n <ParagraphStylePreviewCard\n documentTheme={documentTheme}\n option={previewOption}\n />\n </PreviewCardPrimitive.Popup>\n </PreviewCardPrimitive.Positioner>\n </PreviewCardPrimitive.Portal>\n ) : null}\n </>\n )\n }}\n </PreviewCardPrimitive.Root>\n\n <Select\n value={selectedRunStyle?.fontFamily ?? "Calibri"}\n onValueChange={(value) => {\n if (value) {\n editor.setFontFamily(value)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[156px] min-w-[156px]"\n aria-label="Font family"\n >\n <SelectValue placeholder="Font" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-40"\n >\n {FONT_FAMILIES.map((fontFamily) => (\n <SelectItem key={fontFamily} value={fontFamily}>\n <span style={{ fontFamily }}>{fontFamily}</span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={String(Math.round(selectedRunStyle?.fontSizePt ?? 12))}\n onValueChange={(value) => {\n const nextSize = Number(value)\n if (Number.isFinite(nextSize)) {\n editor.setFontSize(nextSize)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[86px] min-w-[86px]"\n aria-label="Font size"\n >\n <SelectValue placeholder="Size" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-40"\n >\n {FONT_SIZE_OPTIONS.map((size) => (\n <SelectItem key={size} value={String(size)}>\n {size} pt\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={selectedLineSpacingValue}\n onValueChange={(value) => {\n const nextSpacing = Number(value)\n if (Number.isFinite(nextSpacing)) {\n setLineSpacing(nextSpacing)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[94px] min-w-[94px]"\n aria-label="Line spacing"\n >\n <SelectValue placeholder="Spacing" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-40"\n >\n {LINE_SPACING_OPTIONS.map((spacing) => (\n <SelectItem key={spacing} value={String(spacing)}>\n {spacing}x\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Bold"\n active={Boolean(selectedRunStyle?.bold)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleBold}\n >\n <HugeiconsIcon icon={TextBoldIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Italic"\n active={Boolean(selectedRunStyle?.italic)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleItalic}\n >\n <HugeiconsIcon icon={TextItalicIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Underline"\n active={Boolean(selectedRunStyle?.underline)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleUnderline}\n >\n <HugeiconsIcon icon={TextUnderlineIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Strikethrough"\n active={Boolean(selectedRunStyle?.strike)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleStrike}\n >\n <HugeiconsIcon icon={TextStrikethroughIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Superscript"\n active={selectedRunStyle?.verticalAlign === "superscript"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleSuperscript}\n >\n <HugeiconsIcon icon={TextSuperscriptIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Subscript"\n active={selectedRunStyle?.verticalAlign === "subscript"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleSubscript}\n >\n <HugeiconsIcon icon={TextSubscriptIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarColorInput\n label="Text color"\n icon={TextColorIcon}\n color={textColorValue}\n disabled={!canEdit}\n onChange={(color) =>\n editor.setTextColor(normalizeHexColor(color))\n }\n />\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={!canEdit}\n aria-label="Highlight color"\n className="relative"\n >\n <HugeiconsIcon icon={HighlighterIcon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: highlightColor }}\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="z-40 w-44">\n {HIGHLIGHT_COLORS.map((option) => (\n <DropdownMenuCheckboxItem\n key={option.value}\n checked={selectedRunStyle?.highlight === option.value}\n onCheckedChange={() => editor.setHighlight(option.value)}\n >\n <span\n className="size-3 rounded-full border"\n style={{ backgroundColor: option.color }}\n />\n {option.label}\n </DropdownMenuCheckboxItem>\n ))}\n <DropdownMenuSeparator />\n <DropdownMenuCheckboxItem\n checked={!selectedRunStyle?.highlight}\n onCheckedChange={() => editor.setHighlight(undefined)}\n >\n No highlight\n </DropdownMenuCheckboxItem>\n </DropdownMenuContent>\n </DropdownMenu>\n <ToolbarIconButton\n label="Link"\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={onOpenLinkEditor}\n >\n <HugeiconsIcon icon={Link02Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Align left"\n active={\n selectedParagraph?.style?.align === "left" ||\n !selectedParagraph?.style?.align\n }\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("left")}\n >\n <HugeiconsIcon icon={TextAlignLeft01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Align center"\n active={selectedParagraph?.style?.align === "center"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("center")}\n >\n <HugeiconsIcon icon={TextAlignCenterIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Align right"\n active={selectedParagraph?.style?.align === "right"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("right")}\n >\n <HugeiconsIcon icon={TextAlignRight01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Justify"\n active={selectedParagraph?.style?.align === "justify"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("justify")}\n >\n <HugeiconsIcon\n icon={TextAlignJustifyLeftIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Bulleted list"\n active={editor.hasUnorderedList}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.toggleList("unordered")}\n >\n <HugeiconsIcon\n icon={LeftToRightListBulletIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Numbered list"\n active={editor.hasOrderedList}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.toggleList("ordered")}\n >\n <HugeiconsIcon\n icon={LeftToRightListNumberIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="sm"\n disabled={!canEdit}\n className="h-7 gap-1 px-2 shadow-none"\n >\n <HugeiconsIcon icon={borderTriggerIcon} className="size-4" />\n {borderTriggerLabel}\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="z-40 w-56">\n {BORDER_CONTROL_OPTIONS.map((option) => {\n const enabledForContext =\n !option.contexts || option.contexts.includes(borderContext)\n const BorderOptionIcon = borderControlOptionIcon(option.id)\n\n return (\n <React.Fragment key={option.id}>\n {option.separatorBefore ? <DropdownMenuSeparator /> : null}\n <DropdownMenuCheckboxItem\n checked={activeBorderPresets[option.id]}\n disabled={!enabledForContext}\n onCheckedChange={() => {\n if (enabledForContext) {\n applyBorderPreset(option.id)\n }\n }}\n >\n <HugeiconsIcon\n icon={BorderOptionIcon}\n className="size-4 text-muted-foreground"\n />\n {option.label}\n </DropdownMenuCheckboxItem>\n </React.Fragment>\n )\n })}\n </DropdownMenuContent>\n </DropdownMenu>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Insert image"\n disabled={!canEdit}\n onClick={onImageUploadClick}\n >\n <HugeiconsIcon icon={ImageAdd01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Insert table"\n disabled={!canEdit}\n onClick={editor.insertTable}\n >\n <HugeiconsIcon icon={TableIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarTooltip label="Section columns">\n <div className="flex h-7 shrink-0 items-center gap-1 rounded-lg px-2 text-xs text-muted-foreground">\n <HugeiconsIcon icon={ColumnsThreeCogIcon} className="size-4" />\n {activeColumns ? `${activeColumns.count} cols` : "1 col"}\n </div>\n </ToolbarTooltip>\n </div>\n\n <div className="ml-auto flex flex-none items-center gap-1">\n <ToolbarIconButton\n label="Zoom out"\n disabled={controlsDisabled || !canZoomOut}\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, -1)\n )\n }\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />\n </ToolbarIconButton>\n <Select\n value={zoomScale.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={controlsDisabled}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(zoomScale)}%</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="end"\n alignItemWithTrigger={false}\n className="z-40"\n >\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarIconButton\n label="Zoom in"\n disabled={controlsDisabled || !canZoomIn}\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, 1)\n )\n }\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nexport function DocxEditorPreview({\n className,\n defaultZoomScale = DOCX_EDITOR_DEFAULT_ZOOM_SCALE,\n fileName,\n isDark,\n onIsDarkChange,\n src,\n}: {\n className?: string\n defaultZoomScale?: number\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n src?: string\n}) {\n return (\n <DocxEditorContent\n className={className}\n defaultZoomScale={defaultZoomScale}\n effectiveIsDark={isDark}\n fileName={fileName}\n setIsDark={onIsDarkChange}\n shouldRenderNightMode\n url={src}\n />\n )\n}\n\nfunction DocxEditorContent({\n className,\n defaultZoomScale,\n effectiveIsDark,\n fileName,\n setIsDark,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n defaultZoomScale?: number\n effectiveIsDark: boolean\n fileName?: string\n setIsDark: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const imageInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [activePage, setActivePage] = React.useState(1)\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const resolvedDefaultZoomScale = normalizeDocxZoomScale(defaultZoomScale)\n const [zoomScale, setZoomScale] = React.useState<number>(\n resolvedDefaultZoomScale\n )\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\n const [isReadOnly, setIsReadOnly] = React.useState(false)\n const [linkEditorOpen, setLinkEditorOpen] = React.useState(false)\n const [linkDraft, setLinkDraft] = React.useState("")\n const viewerBackgroundColor =\n "color-mix(in oklab, var(--muted) 40%, transparent)"\n const displayFileName = React.useMemo(\n () =>\n uploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),\n [fileName, uploadedDocxFile?.file.name, url]\n )\n const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>\n effectiveIsDark ? "dark" : "light"\n )\n const editorOptions = React.useMemo(\n () => ({\n initialDocumentTheme,\n initialFileName: displayFileName,\n }),\n [displayFileName, initialDocumentTheme]\n )\n const editor = useDocxEditor(editorOptions)\n const { importDocxFile, setDocumentTheme, status } = editor\n const [reportedPageCount, setReportedPageCount] = React.useState(0)\n const thumbnailEditor = React.useMemo<DocxEditorController>(\n () => ({\n ...editor,\n totalPages: Math.max(editor.totalPages, reportedPageCount),\n }),\n [editor, reportedPageCount]\n )\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n []\n )\n const { thumbnails } = useDocxViewerThumbnails(\n thumbnailEditor,\n thumbnailOptions\n )\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <EditorLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const hasDocument = Boolean(url || uploadedDocxFile)\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, reportedPageCount || editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n const thumbnailSidebarOpen = Boolean(\n sidebarOpen && (pageCount || isLoadingDocument)\n )\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(resolvedDefaultZoomScale)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [resolvedDefaultZoomScale, url])\n\n React.useEffect(() => {\n setDocumentTheme(effectiveIsDark ? "dark" : "light")\n }, [effectiveIsDark, setDocumentTheme])\n\n React.useEffect(() => {\n if (\n status.startsWith("Failed to load file") ||\n status === "Only .docx files are supported"\n ) {\n setLoadError(status)\n setIsLoadingDocument(false)\n }\n }, [status])\n\n React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n if (!uploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n setReportedPageCount(0)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n setReportedPageCount(0)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url ? await loadDocxFile(url, displayFileName) : null)\n if (!docxFile) return\n await importDocxFile(docxFile)\n\n if (isCurrent) {\n setIsLoadingDocument(false)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }\n } catch (error) {\n if (isCurrent) {\n setLoadError(\n error instanceof Error ? error.message : "Unknown DOCX load error"\n )\n setIsLoadingDocument(false)\n }\n }\n }\n\n void load()\n\n return () => {\n isCurrent = false\n }\n }, [displayFileName, importDocxFile, uploadedDocxFile, url])\n\n React.useEffect(() => {\n if (url) {\n setUploadedDocxFile(null)\n }\n }, [url])\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n let closestPage = 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>(\n \'[data-docx-page-wrapper="true"][data-index]\'\n )\n .forEach((page) => {\n const pageIndex = Number(page.dataset.index)\n if (!Number.isFinite(pageIndex)) return\n\n const pageRect = page.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = pageIndex + 1\n }\n })\n\n setActivePage((currentPage) =>\n currentPage === closestPage ? currentPage : closestPage\n )\n }, [pageCount])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n let frameId = 0\n const handleScroll = () => {\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener("scroll", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n viewport.removeEventListener("scroll", handleScroll)\n }\n }, [pageCount, updateActivePageFromViewport])\n\n const scrollToPage = React.useCallback((pageNumber: number) => {\n const viewport = viewportRef.current\n const targetPageIndex = pageNumber - 1\n const page = viewport?.querySelector<HTMLElement>(\n `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`\n )\n\n setActivePage(pageNumber)\n\n if (!viewport || !page) return\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n }, [])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n setZoomScale(resolvedDefaultZoomScale)\n setActivePage(1)\n setReportedPageCount(0)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n async function handleImageUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n await editor.insertImageFile(file)\n }\n\n function openLinkEditor() {\n setLinkDraft(editor.selectedLink ?? "")\n setLinkEditorOpen(true)\n }\n\n function applyLink() {\n editor.setLink(linkDraft.trim() || undefined)\n setLinkEditorOpen(false)\n }\n\n return (\n <div\n className={cn(\n "flex h-[720px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n <input\n ref={imageInputRef}\n type="file"\n accept="image/*"\n className="hidden"\n onChange={handleImageUpload}\n />\n <DocxEditorToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n editor={editor}\n isReadOnly={isReadOnly}\n onImageUploadClick={() => imageInputRef.current?.click()}\n onIsDarkChange={setIsDark}\n onIsReadOnlyChange={setIsReadOnly}\n onOpenLinkEditor={openLinkEditor}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showNightRenderToggle={shouldRenderNightMode}\n zoomScale={zoomScale}\n />\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {linkEditorOpen ? (\n <div className="absolute top-3 left-1/2 z-50 flex w-[min(420px,calc(100%-2rem))] -translate-x-1/2 items-center gap-2 rounded-lg border bg-background p-2 shadow-lg">\n <Input\n value={linkDraft}\n onChange={(event) => setLinkDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === "Enter") {\n event.preventDefault()\n applyLink()\n }\n if (event.key === "Escape") {\n setLinkEditorOpen(false)\n }\n }}\n placeholder="https://example.com"\n aria-label="Link URL"\n />\n <Button type="button" size="sm" onClick={applyLink}>\n Apply\n </Button>\n <Button\n type="button"\n size="sm"\n variant="ghost"\n onClick={() => {\n editor.setLink(undefined)\n setLinkEditorOpen(false)\n }}\n >\n Clear\n </Button>\n </div>\n ) : null}\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={thumbnailSidebarOpen}\n >\n <ScrollArea\n className="h-full"\n scrollFade\n viewportClassName="overscroll-contain"\n >\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </>\n ) : (\n <div className="flex flex-col items-center gap-3">\n {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (\n <Button\n key={thumbnail.pageIndex}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent text-foreground",\n thumbnail.pageNumber !== activePage &&\n "text-muted-foreground"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => scrollToPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n !thumbnail.isMounted &&\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n ))}\n </div>\n )}\n </div>\n </ScrollArea>\n </DocumentViewerThumbnailSidebar>\n <ScrollArea\n className="min-h-0 flex-1"\n style={{ backgroundColor: viewerBackgroundColor }}\n viewportClassName="overscroll-contain p-4"\n viewportRef={viewportRef}\n >\n {!url && !uploadedDocxFile ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm shadow-xs">\n <div className="font-medium">Upload a DOCX to edit</div>\n <div className="mt-1 text-muted-foreground">\n Pass a DOCX URL with the <code>src</code> prop or upload a\n file.\n </div>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload DOCX\n </Button>\n </div>\n </div>\n ) : loadError ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm text-destructive shadow-xs">\n <div className="font-medium">Unable to edit DOCX</div>\n <div className="mt-1 text-muted-foreground">{loadError}</div>\n </div>\n </div>\n ) : isLoadingDocument ? (\n loadingState\n ) : (\n <div className="mx-auto flex min-h-full justify-center">\n <div\n className={cn(\n "origin-top",\n editor.documentTheme === "dark" && "docx-night-reader-shell"\n )}\n style={{ zoom: zoomScale / 100 }}\n >\n <DocxEditorViewer\n editor={editor}\n mode={isReadOnly ? "read-only" : "edit"}\n showTrackedChanges={editor.showTrackedChanges}\n renderTrackedChangeCard={renderDocxTrackedChangeCard}\n showComments={editor.showComments}\n renderCommentCard={renderDocxCommentCard}\n loadingState={loadingState}\n pageBackgroundColor={\n editor.documentTheme === "dark" ? "#0a0a0a" : undefined\n }\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={{ enabled: false }}\n deferInitialPaginationPaint={false}\n onPageCountChange={handlePageCountChange}\n />\n </div>\n </div>\n )}\n </ScrollArea>\n </div>\n </div>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport { PreviewCard as PreviewCardPrimitive } from "@base-ui/react/preview-card"\nimport {\n DocxEditorViewer,\n paragraphLetterheadFloatSideAtNodeIndex,\n useDocxBorders,\n useDocxComments,\n useDocxDocumentTheme,\n useDocxEditor,\n useDocxLineSpacing,\n useDocxPageLayout,\n useDocxParagraphStyles,\n useDocxTrackChanges,\n useDocxViewerThumbnails,\n type DocxBorderContext,\n type DocxBorderPreset,\n type DocxCommentCardRenderProps,\n type DocxDocumentTheme,\n type DocxEditorController,\n type DocxTrackedChangeCardRenderProps,\n type ParagraphStyleDefinition,\n} from "@extend-ai/react-docx"\nimport {\n ArrowExpandDiagonal01Icon,\n ArrowExpandDiagonal02Icon,\n BorderAll01Icon,\n BorderBottom01Icon,\n BorderHorizontalIcon,\n BorderInnerIcon,\n BorderLeft01Icon,\n BorderNone01Icon,\n BorderRight01Icon,\n BorderTop01Icon,\n BorderVerticalIcon,\n ColumnsThreeCogIcon,\n Comment01Icon,\n Download01Icon,\n EditOffIcon,\n FileDiffIcon,\n HighlighterIcon,\n ImageAdd01Icon,\n LeftToRightListBulletIcon,\n LeftToRightListNumberIcon,\n LineIcon,\n Link02Icon,\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n Redo02Icon,\n SidebarLeftIcon,\n Sun03Icon,\n TableIcon,\n TextAlignCenterIcon,\n TextAlignJustifyLeftIcon,\n TextAlignLeft01Icon,\n TextAlignRight01Icon,\n TextBoldIcon,\n TextColorIcon,\n TextItalicIcon,\n TextStrikethroughIcon,\n TextSubscriptIcon,\n TextSuperscriptIcon,\n TextUnderlineIcon,\n Undo02Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\n\nimport { cn } from "@/lib/utils"\nimport { Badge } from "@/components/ui/badge"\nimport { Button } from "@/components/ui/button"\nimport { Card } from "@/components/ui/card"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/ui/document-viewer-sidebar"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { Input } from "@/components/ui/input"\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"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst DOCX_EDITOR_DEFAULT_ZOOM_SCALE = 100\nconst ZOOM_OPTIONS = [50, 75, 90, 100, 110, 125, 150, 175, 200] as const\nconst FONT_FAMILIES = [\n "Calibri",\n "Arial",\n "Times New Roman",\n "Georgia",\n "Helvetica",\n "Courier New",\n] as const\nconst FONT_SIZE_OPTIONS = [\n 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48,\n] as const\nconst LINE_SPACING_OPTIONS = [1, 1.15, 1.2, 1.5, 2, 2.5, 3] as const\nconst FALLBACK_PARAGRAPH_STYLE_OPTIONS = [\n { id: "Normal", name: "Body" },\n { id: "Heading1", name: "Heading 1" },\n { id: "Heading2", name: "Heading 2" },\n { id: "Heading3", name: "Heading 3" },\n] as const\nconst HIGHLIGHT_COLORS = [\n { label: "Yellow", value: "yellow", color: "#fff59d" },\n { label: "Green", value: "green", color: "#bbf7d0" },\n { label: "Cyan", value: "cyan", color: "#a5f3fc" },\n { label: "Magenta", value: "magenta", color: "#f5d0fe" },\n { label: "Red", value: "red", color: "#fecaca" },\n { label: "Blue", value: "blue", color: "#bfdbfe" },\n] as const\nconst HIGHLIGHT_PREVIEW_COLORS: Record<string, string> = {\n black: "#111827",\n white: "#ffffff",\n ...Object.fromEntries(\n HIGHLIGHT_COLORS.map((option) => [option.value, option.color])\n ),\n}\nconst DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\nconst DEFAULT_HEADING_PREVIEW_RUN_STYLES: Record<\n 1 | 2 | 3 | 4 | 5 | 6,\n NonNullable<ParagraphStyleDefinition["runStyle"]>\n> = {\n 1: {\n fontFamily: "Calibri Light",\n fontSizePt: 16,\n bold: true,\n color: "#2f5496",\n },\n 2: {\n fontFamily: "Calibri Light",\n fontSizePt: 13,\n bold: true,\n color: "#2f5496",\n },\n 3: {\n fontFamily: "Calibri",\n fontSizePt: 12,\n bold: true,\n color: "#1f3763",\n },\n 4: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n 5: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n 6: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n}\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n}\n\ntype BorderControlOption = {\n id: DocxBorderPreset\n label: string\n contexts?: DocxBorderContext[]\n separatorBefore?: boolean\n}\n\nconst BORDER_CONTROL_OPTIONS: BorderControlOption[] = [\n { id: "bottom", label: "Bottom Border" },\n { id: "top", label: "Top Border" },\n { id: "left", label: "Left Border" },\n { id: "right", label: "Right Border" },\n { id: "none", label: "No Border", separatorBefore: true },\n { id: "all", label: "All Borders" },\n { id: "outside", label: "Outside Borders" },\n { id: "inside", label: "Inside Borders", contexts: ["table"] },\n {\n id: "inside-horizontal",\n label: "Inside Horizontal Border",\n contexts: ["table"],\n },\n {\n id: "inside-vertical",\n label: "Inside Vertical Border",\n contexts: ["table"],\n },\n {\n id: "diagonal-down",\n label: "Diagonal Down Border",\n contexts: ["table"],\n separatorBefore: true,\n },\n { id: "diagonal-up", label: "Diagonal Up Border", contexts: ["table"] },\n { id: "horizontal-line", label: "Horizontal Line", separatorBefore: true },\n]\n\nfunction borderControlOptionIcon(optionId: DocxBorderPreset) {\n switch (optionId) {\n case "bottom":\n return BorderBottom01Icon\n case "top":\n return BorderTop01Icon\n case "left":\n return BorderLeft01Icon\n case "right":\n return BorderRight01Icon\n case "none":\n return BorderNone01Icon\n case "inside":\n return BorderInnerIcon\n case "inside-horizontal":\n return BorderHorizontalIcon\n case "inside-vertical":\n return BorderVerticalIcon\n case "diagonal-down":\n return ArrowExpandDiagonal01Icon\n case "diagonal-up":\n return ArrowExpandDiagonal02Icon\n case "horizontal-line":\n return LineIcon\n default:\n return BorderAll01Icon\n }\n}\n\nasync function loadDocxFile(\n url: string,\n displayFileName: string\n): Promise<File> {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n return new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n}\n\nfunction formatDocumentName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "document.docx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction getNextZoomScale(currentZoomScale: number, direction: 1 | -1) {\n const currentIndex = ZOOM_OPTIONS.indexOf(\n currentZoomScale as (typeof ZOOM_OPTIONS)[number]\n )\n let fallbackIndex = -1\n\n if (direction > 0) {\n fallbackIndex = ZOOM_OPTIONS.findIndex((value) => value > currentZoomScale)\n } else {\n for (let index = ZOOM_OPTIONS.length - 1; index >= 0; index -= 1) {\n if (ZOOM_OPTIONS[index] < currentZoomScale) {\n fallbackIndex = index\n break\n }\n }\n }\n\n const resolvedIndex = currentIndex >= 0 ? currentIndex : fallbackIndex\n if (resolvedIndex < 0) return currentZoomScale\n\n const nextIndex = Math.min(\n Math.max(resolvedIndex + direction, 0),\n ZOOM_OPTIONS.length - 1\n )\n\n return ZOOM_OPTIONS[nextIndex] ?? currentZoomScale\n}\n\nfunction normalizeDocxZoomScale(value: number | undefined): number {\n return typeof value === "number" &&\n ZOOM_OPTIONS.includes(value as (typeof ZOOM_OPTIONS)[number])\n ? value\n : DOCX_EDITOR_DEFAULT_ZOOM_SCALE\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === "string" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes("padding"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\n}\n\nfunction normalizeHexColor(value?: string, fallback = "#111827") {\n if (!value) return fallback\n\n const trimmed = value.trim()\n const threeDigit = /^#([0-9a-f]{3})$/i.exec(trimmed)\n if (threeDigit?.[1]) {\n const [red, green, blue] = threeDigit[1].split("")\n return `#${red}${red}${green}${green}${blue}${blue}`.toLowerCase()\n }\n\n const sixDigit = /^#([0-9a-f]{6})$/i.exec(trimmed)\n if (sixDigit?.[1]) {\n return `#${sixDigit[1].toLowerCase()}`\n }\n\n return fallback\n}\n\nfunction inferParagraphStyleHeadingLevel(value?: string) {\n if (!value) return undefined\n\n const match = value.match(/(?:^|[\\s_-])(?:heading|h)\\s*([1-6])(?:$|[\\s_-])/i)\n const level = match?.[1] ? Number(match[1]) : NaN\n\n return level >= 1 && level <= 6 ? (level as 1 | 2 | 3 | 4 | 5 | 6) : undefined\n}\n\nfunction resolveParagraphStyleHeadingLevel(option?: ParagraphStyleDefinition) {\n if (\n Number.isFinite(option?.headingLevel) &&\n option?.headingLevel &&\n option.headingLevel >= 1 &&\n option.headingLevel <= 6\n ) {\n return option.headingLevel as 1 | 2 | 3 | 4 | 5 | 6\n }\n\n return (\n inferParagraphStyleHeadingLevel(option?.id) ??\n inferParagraphStyleHeadingLevel(option?.name)\n )\n}\n\nfunction resolveParagraphStyleRunPreview(option?: ParagraphStyleDefinition) {\n if (!option) return undefined\n\n const headingLevel = resolveParagraphStyleHeadingLevel(option)\n const headingRunStyle = headingLevel\n ? DEFAULT_HEADING_PREVIEW_RUN_STYLES[headingLevel]\n : undefined\n\n return headingRunStyle\n ? {\n ...headingRunStyle,\n ...(option.runStyle ?? {}),\n }\n : option.runStyle\n}\n\nfunction resolveHighlightPreview(value?: string) {\n if (!value) return undefined\n\n const normalized = value.trim().toLowerCase()\n if (!normalized) return undefined\n\n const hex = normalizeHexColor(normalized, "")\n if (hex) return hex\n\n return HIGHLIGHT_PREVIEW_COLORS[normalized]\n}\n\nfunction themedPreviewColor(\n color: string | undefined,\n documentTheme: DocxDocumentTheme\n) {\n if (documentTheme !== "dark") return color\n if (!color) return "#f3f4f6"\n\n const normalized = color.trim().toLowerCase()\n if (\n normalized === "#000" ||\n normalized === "#000000" ||\n normalized === "#111111" ||\n normalized === "#111827" ||\n normalized === "black" ||\n normalized === "rgb(0,0,0)" ||\n normalized === "rgb(0, 0, 0)"\n ) {\n return "#f3f4f6"\n }\n\n return color\n}\n\nfunction paragraphStylePreviewStyle(\n option: ParagraphStyleDefinition,\n documentTheme: DocxDocumentTheme\n): React.CSSProperties {\n const runStyle = resolveParagraphStyleRunPreview(option)\n const textDecoration = [\n runStyle?.underline ? "underline" : "",\n runStyle?.strike ? "line-through" : "",\n ]\n .filter(Boolean)\n .join(" ")\n\n return {\n textAlign: option.align ?? "left",\n fontFamily: runStyle?.fontFamily,\n fontSize: runStyle?.fontSizePt ? `${runStyle.fontSizePt}pt` : "11pt",\n fontWeight:\n runStyle?.bold !== undefined ? (runStyle.bold ? 700 : 400) : undefined,\n fontStyle: runStyle?.italic ? "italic" : undefined,\n textDecoration: textDecoration || undefined,\n color:\n runStyle?.color !== undefined\n ? themedPreviewColor(normalizeHexColor(runStyle.color), documentTheme)\n : undefined,\n backgroundColor: resolveHighlightPreview(runStyle?.highlight),\n lineHeight: 1,\n whiteSpace: "pre-wrap",\n }\n}\n\nfunction paragraphStylePreviewTriggerId(prefix: string, styleId: string) {\n return `${prefix}-paragraph-style-preview-${styleId.replace(\n /[^a-zA-Z0-9_-]/g,\n "_"\n )}`\n}\n\nfunction parseToolbarSectionColumns(\n sectionPropertiesXml?: string\n): { count: number; gapPx: number } | undefined {\n if (!sectionPropertiesXml) return undefined\n\n const columnsTag = sectionPropertiesXml.match(/<w:cols\\b[^>]*\\/?>/i)?.[0]\n if (!columnsTag) return undefined\n\n const countRaw = columnsTag.match(/\\bw:num="(\\d+)"/i)?.[1]\n const count = countRaw ? Number(countRaw) : 1\n if (!Number.isFinite(count) || count <= 1) return undefined\n\n const gapRaw = columnsTag.match(/\\bw:space="(\\d+)"/i)?.[1]\n const gapTwips = gapRaw ? Number(gapRaw) : 720\n const gapPx = Math.max(0, Math.round((gapTwips * 96) / 1440))\n\n return {\n count: Math.max(2, Math.round(count)),\n gapPx,\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 EditorLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction ToolbarIconButton({\n active,\n children,\n label,\n ...props\n}: React.ComponentProps<typeof Button> & {\n active?: boolean\n label: string\n}) {\n return (\n <ToolbarTooltip label={label}>\n <Button\n type="button"\n variant={active ? "secondary" : "ghost"}\n size="icon-sm"\n aria-label={label}\n data-pressed={active ? "" : undefined}\n {...props}\n >\n {children}\n </Button>\n </ToolbarTooltip>\n )\n}\n\nfunction ToolbarColorInput({\n color,\n disabled,\n icon,\n label,\n onChange,\n}: {\n color: string\n disabled?: boolean\n icon: typeof TextColorIcon\n label: string\n onChange: (color: string) => void\n}) {\n return (\n <ToolbarTooltip label={label}>\n <label\n className={cn(\n "relative inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-lg border border-transparent text-foreground transition-colors hover:bg-accent",\n disabled && "pointer-events-none opacity-64"\n )}\n aria-label={label}\n >\n <HugeiconsIcon icon={icon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: color }}\n />\n <input\n type="color"\n aria-label={label}\n disabled={disabled}\n value={color}\n className="sr-only"\n onChange={(event) => onChange(event.target.value)}\n />\n </label>\n </ToolbarTooltip>\n )\n}\n\nfunction DocxSidebarThumbnail({\n canvasRef,\n displayFileName,\n hasError,\n isActive,\n isLoading,\n pageNumber,\n pixelHeightPx,\n pixelWidthPx,\n previewAspectRatio,\n}: {\n canvasRef: React.RefCallback<HTMLCanvasElement>\n displayFileName: string\n hasError: boolean\n isActive: boolean\n isLoading: boolean\n pageNumber: number\n pixelHeightPx: number\n pixelWidthPx: number\n previewAspectRatio: number\n}) {\n return (\n <FileThumbnail\n file={{\n name: `${displayFileName} page ${pageNumber}`,\n type: DOCX_MIME_TYPE,\n }}\n previewAspectRatio={previewAspectRatio}\n previewClassName="rounded-md bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n isLoading={isLoading}\n hasError={hasError}\n className={cn(\n "w-[92px] rounded-md border-0 shadow-xs ring-0 transition-shadow duration-150",\n isActive && "shadow-sm"\n )}\n />\n )\n}\n\nfunction ParagraphStylePreviewCard({\n documentTheme,\n option,\n}: {\n documentTheme: DocxDocumentTheme\n option: ParagraphStyleDefinition\n}) {\n const surfaceStyle: React.CSSProperties =\n documentTheme === "dark"\n ? {\n backgroundColor: "#111827",\n borderColor: "#374151",\n color: "#f3f4f6",\n }\n : {\n backgroundColor: "#ffffff",\n borderColor: "#d4d4d8",\n color: "#111827",\n }\n const secondaryTextColor = documentTheme === "dark" ? "#9ca3af" : "#6b7280"\n\n return (\n <div className="w-[260px] p-3">\n <p className="text-[10px] font-medium tracking-wide text-muted-foreground uppercase">\n Style Preview\n </p>\n <div className="mt-2 rounded-sm border p-2.5" style={surfaceStyle}>\n <p style={paragraphStylePreviewStyle(option, documentTheme)}>\n {option.name}\n </p>\n <p\n className="mt-1 text-[11px]"\n style={{\n color: secondaryTextColor,\n textAlign: option.align ?? "left",\n }}\n >\n The quick brown fox jumps over the lazy dog.\n </p>\n </div>\n </div>\n )\n}\n\nfunction trackedChangeBadgeVariant(\n kind: DocxTrackedChangeCardRenderProps["change"]["kind"]\n): React.ComponentProps<typeof Badge>["variant"] {\n switch (kind) {\n case "insertion":\n case "move-to":\n return "success"\n case "deletion":\n case "move-from":\n return "error"\n default:\n return "warning"\n }\n}\n\nfunction trackedChangeBadgeLabel({\n change,\n kindLabel,\n}: Pick<DocxTrackedChangeCardRenderProps, "change" | "kindLabel">) {\n switch (change.kind) {\n case "insertion":\n return "Inserted"\n case "deletion":\n return "Removed"\n case "move-from":\n return "Moved from"\n case "move-to":\n return "Moved to"\n default:\n return kindLabel\n }\n}\n\nfunction DocxAnnotationCard({\n anchorText,\n badge,\n badgeVariant = "outline",\n date,\n meta,\n snippet,\n style,\n}: {\n anchorText?: string\n badge: string\n badgeVariant?: React.ComponentProps<typeof Badge>["variant"]\n date?: string\n meta: string\n snippet: string\n style: React.CSSProperties\n}) {\n return (\n <Card\n style={style}\n className="pointer-events-auto box-border gap-2 rounded-lg bg-card/95 p-2 text-card-foreground shadow-sm before:rounded-[7px]"\n >\n <div className="flex min-w-0 items-start justify-between gap-2">\n <div className="min-w-0 text-[11px] leading-tight font-medium text-muted-foreground">\n <div className="truncate">{meta}</div>\n {date ? <div className="mt-0.5 truncate">{date}</div> : null}\n </div>\n <Badge\n variant={badgeVariant}\n size="sm"\n className="max-w-[92px] truncate"\n >\n {badge}\n </Badge>\n </div>\n {anchorText ? (\n <div className="rounded-md bg-muted/60 px-2 py-1 text-[11px] leading-snug text-muted-foreground italic">\n {anchorText}\n </div>\n ) : null}\n <div className="text-xs leading-snug break-words">{snippet}</div>\n </Card>\n )\n}\n\nfunction renderDocxTrackedChangeCard({\n change,\n formattedDate,\n kindLabel,\n snippet,\n style,\n}: DocxTrackedChangeCardRenderProps) {\n return (\n <DocxAnnotationCard\n badge={trackedChangeBadgeLabel({ change, kindLabel })}\n badgeVariant={trackedChangeBadgeVariant(change.kind)}\n date={formattedDate}\n meta={change.author?.trim() || "Unknown author"}\n snippet={snippet}\n style={style}\n />\n )\n}\n\nfunction renderDocxCommentCard({\n comment,\n formattedDate,\n snippet,\n style,\n}: DocxCommentCardRenderProps) {\n const badge = comment.resolved\n ? "Resolved"\n : comment.parentId !== undefined\n ? "Reply"\n : "Comment"\n\n return (\n <DocxAnnotationCard\n anchorText={comment.anchorText}\n badge={badge}\n badgeVariant={comment.resolved ? "secondary" : "info"}\n date={formattedDate}\n meta={comment.author?.trim() || "Unknown author"}\n snippet={snippet}\n style={style}\n />\n )\n}\n\nfunction DocxEditorToolbar({\n activePage,\n controlsDisabled,\n editor,\n isReadOnly,\n onImageUploadClick,\n onIsDarkChange,\n onIsReadOnlyChange,\n onOpenLinkEditor,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showNightRenderToggle,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n editor: DocxEditorController\n isReadOnly: boolean\n onImageUploadClick: () => void\n onIsDarkChange: (checked: boolean) => void\n onIsReadOnlyChange: (checked: boolean) => void\n onOpenLinkEditor: () => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showNightRenderToggle: boolean\n zoomScale: number\n}) {\n const { documentTheme, setDocumentTheme } = useDocxDocumentTheme(editor)\n const { layout: pageLayout } = useDocxPageLayout(editor)\n const { paragraphStyles, selectedParagraphStyleId, setParagraphStyle } =\n useDocxParagraphStyles(editor)\n const { lineSpacing, setLineSpacing } = useDocxLineSpacing(editor)\n const { borderContext, activeBorderPresets, applyBorderPreset } =\n useDocxBorders(editor)\n const { showTrackedChanges, setShowTrackedChanges } =\n useDocxTrackChanges(editor)\n const { showComments, setShowComments } = useDocxComments(editor)\n const selectedRunStyle = editor.selectedRunStyle\n const selectedParagraph = editor.selectedParagraph\n const paragraphStyleOptions: ParagraphStyleDefinition[] =\n paragraphStyles.length > 0\n ? paragraphStyles\n : [...FALLBACK_PARAGRAPH_STYLE_OPTIONS]\n const selectedParagraphStyleValue =\n selectedParagraphStyleId ??\n paragraphStyleOptions.find((option) => "isDefault" in option)?.id ??\n paragraphStyleOptions[0]?.id ??\n "Normal"\n const selectedParagraphStyleOption =\n paragraphStyleOptions.find(\n (option) => option.id === selectedParagraphStyleValue\n ) ??\n paragraphStyleOptions[0] ??\n FALLBACK_PARAGRAPH_STYLE_OPTIONS[0]\n const paragraphStylePreviewHandle = React.useMemo(\n () => PreviewCardPrimitive.createHandle<ParagraphStyleDefinition>(),\n []\n )\n const paragraphStylePreviewIdPrefix = React.useId()\n const [isParagraphStyleMenuOpen, setIsParagraphStyleMenuOpen] =\n React.useState(false)\n const openParagraphStylePreview = React.useCallback(\n (styleId: string) => {\n paragraphStylePreviewHandle.open(\n paragraphStylePreviewTriggerId(paragraphStylePreviewIdPrefix, styleId)\n )\n },\n [paragraphStylePreviewHandle, paragraphStylePreviewIdPrefix]\n )\n const selectedLineSpacingValue = React.useMemo(() => {\n const current = Number.isFinite(lineSpacing.multiple)\n ? lineSpacing.multiple\n : 1\n const nearest = LINE_SPACING_OPTIONS.reduce((closest, candidate) => {\n return Math.abs(candidate - current) < Math.abs(closest - current)\n ? candidate\n : closest\n }, LINE_SPACING_OPTIONS[0])\n return String(nearest)\n }, [lineSpacing.multiple])\n const textColorValue = normalizeHexColor(selectedRunStyle?.color)\n const highlightColor =\n HIGHLIGHT_COLORS.find(\n (option) => option.value === selectedRunStyle?.highlight\n )?.color ?? "#fff59d"\n const activeNodeIndex =\n editor.selection.kind === "paragraph"\n ? editor.selection.nodeIndex\n : editor.selection.tableIndex\n const letterheadColumns =\n editor.selection.kind === "paragraph" &&\n paragraphLetterheadFloatSideAtNodeIndex(\n editor.model.nodes,\n editor.selection.nodeIndex\n )\n ? { count: 2, gapPx: 28 }\n : undefined\n const sections = editor.model.metadata.sections ?? []\n const activeSection = sections\n .filter((section) => section.startNodeIndex <= activeNodeIndex)\n .at(-1)\n const activeColumns =\n letterheadColumns ??\n parseToolbarSectionColumns(activeSection?.sectionPropertiesXml) ??\n parseToolbarSectionColumns(editor.model.metadata.sectionPropertiesXml) ??\n pageLayout.columns\n const activeBorderControlOptions = BORDER_CONTROL_OPTIONS.filter(\n (option) => activeBorderPresets[option.id]\n )\n const borderTriggerLabel =\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].label\n : "Borders"\n const borderTriggerIcon = borderControlOptionIcon(\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].id\n : "all"\n )\n const canEdit = !controlsDisabled && !isReadOnly\n const canZoomIn = zoomScale < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n const canZoomOut = zoomScale > ZOOM_OPTIONS[0]\n\n const preserveTextSelection = React.useCallback(\n (event: React.MouseEvent<HTMLElement> | React.PointerEvent<HTMLElement>) =>\n event.preventDefault(),\n []\n )\n\n return (\n <div className="bg-background">\n <TooltipProvider>\n <div className="flex min-h-11 items-center gap-2 overflow-x-auto overflow-y-hidden border-b px-3">\n <ToolbarIconButton\n label="Toggle pages"\n disabled={controlsDisabled}\n onClick={onToggleSidebar}\n >\n <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />\n </ToolbarIconButton>\n <div className="min-w-28 text-sm whitespace-nowrap text-primary">\n Page {pageCount ? activePage : 1} of {pageCount || "-"}\n </div>\n <div className="min-w-0 flex-1" />\n {showNightRenderToggle ? (\n <>\n <ToolbarIconButton\n label={\n documentTheme === "dark"\n ? "Use light document"\n : "Use dark document"\n }\n disabled={controlsDisabled}\n onClick={() => {\n const nextIsDark = documentTheme !== "dark"\n setDocumentTheme(nextIsDark ? "dark" : "light")\n onIsDarkChange(nextIsDark)\n }}\n >\n <HugeiconsIcon\n icon={documentTheme === "dark" ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </ToolbarIconButton>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <ToolbarIconButton\n label="Show tracked changes"\n active={showTrackedChanges}\n disabled={controlsDisabled}\n onClick={() => setShowTrackedChanges(!showTrackedChanges)}\n >\n <HugeiconsIcon icon={FileDiffIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Show comments"\n active={showComments}\n disabled={controlsDisabled}\n onClick={() => setShowComments(!showComments)}\n >\n <HugeiconsIcon icon={Comment01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label={isReadOnly ? "Switch to edit mode" : "Switch to read-only"}\n active={isReadOnly}\n disabled={controlsDisabled}\n onClick={() => onIsReadOnlyChange(!isReadOnly)}\n >\n <HugeiconsIcon icon={EditOffIcon} className="size-4" />\n </ToolbarIconButton>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <ToolbarIconButton\n label="Import DOCX"\n disabled={editor.isImporting}\n onClick={onUploadClick}\n >\n {editor.isImporting ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n )}\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Download DOCX"\n disabled={controlsDisabled || editor.isImporting}\n onClick={editor.exportDocx}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex min-h-12 flex-wrap items-center gap-2 border-b px-3 py-2">\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Undo"\n disabled={!editor.canUndo || isReadOnly}\n onClick={editor.undo}\n >\n <HugeiconsIcon icon={Undo02Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Redo"\n disabled={!editor.canRedo || isReadOnly}\n onClick={editor.redo}\n >\n <HugeiconsIcon icon={Redo02Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <PreviewCardPrimitive.Root handle={paragraphStylePreviewHandle}>\n {({ payload }) => {\n const previewOption = payload ?? selectedParagraphStyleOption\n\n return (\n <>\n <Select\n value={selectedParagraphStyleValue}\n onOpenChange={(open) => {\n setIsParagraphStyleMenuOpen(open)\n\n if (!open) {\n paragraphStylePreviewHandle.close()\n return\n }\n\n window.requestAnimationFrame(() => {\n openParagraphStylePreview(selectedParagraphStyleValue)\n })\n }}\n onValueChange={(value) => {\n if (value) {\n setParagraphStyle(value)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[136px] min-w-[136px]"\n aria-label="Paragraph style"\n >\n <SelectValue placeholder="Style" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-40 min-w-[210px]"\n >\n {paragraphStyleOptions.map((option) => {\n const previewTriggerId = paragraphStylePreviewTriggerId(\n paragraphStylePreviewIdPrefix,\n option.id\n )\n\n return (\n <SelectItem\n key={option.id}\n value={option.id}\n label={option.name}\n className="relative min-w-[190px]"\n onFocus={() => openParagraphStylePreview(option.id)}\n onPointerEnter={() =>\n openParagraphStylePreview(option.id)\n }\n >\n <span className="block truncate">\n {option.name}\n </span>\n <PreviewCardPrimitive.Trigger\n id={previewTriggerId}\n handle={paragraphStylePreviewHandle}\n payload={option}\n delay={0}\n closeDelay={120}\n render={\n <span\n aria-hidden="true"\n className="pointer-events-none absolute inset-0 block"\n />\n }\n />\n </SelectItem>\n )\n })}\n </SelectContent>\n </Select>\n {isParagraphStyleMenuOpen && previewOption ? (\n <PreviewCardPrimitive.Portal>\n <PreviewCardPrimitive.Positioner\n side="right"\n align="start"\n sideOffset={10}\n alignOffset={-4}\n className="z-40 transition-[top,left,right,bottom,transform] duration-100 ease-out data-instant:transition-none"\n >\n <PreviewCardPrimitive.Popup\n data-slot="paragraph-style-preview-card"\n className="origin-(--transform-origin) rounded-lg border bg-popover text-popover-foreground shadow-lg/5 transition-opacity duration-100 outline-none not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:opacity-0 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]"\n >\n <ParagraphStylePreviewCard\n documentTheme={documentTheme}\n option={previewOption}\n />\n </PreviewCardPrimitive.Popup>\n </PreviewCardPrimitive.Positioner>\n </PreviewCardPrimitive.Portal>\n ) : null}\n </>\n )\n }}\n </PreviewCardPrimitive.Root>\n\n <Select\n value={selectedRunStyle?.fontFamily ?? "Calibri"}\n onValueChange={(value) => {\n if (value) {\n editor.setFontFamily(value)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[156px] min-w-[156px]"\n aria-label="Font family"\n >\n <SelectValue placeholder="Font" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-40"\n >\n {FONT_FAMILIES.map((fontFamily) => (\n <SelectItem key={fontFamily} value={fontFamily}>\n <span style={{ fontFamily }}>{fontFamily}</span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={String(Math.round(selectedRunStyle?.fontSizePt ?? 12))}\n onValueChange={(value) => {\n const nextSize = Number(value)\n if (Number.isFinite(nextSize)) {\n editor.setFontSize(nextSize)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[86px] min-w-[86px]"\n aria-label="Font size"\n >\n <SelectValue placeholder="Size" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-40"\n >\n {FONT_SIZE_OPTIONS.map((size) => (\n <SelectItem key={size} value={String(size)}>\n {size} pt\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={selectedLineSpacingValue}\n onValueChange={(value) => {\n const nextSpacing = Number(value)\n if (Number.isFinite(nextSpacing)) {\n setLineSpacing(nextSpacing)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[94px] min-w-[94px]"\n aria-label="Line spacing"\n >\n <SelectValue placeholder="Spacing" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-40"\n >\n {LINE_SPACING_OPTIONS.map((spacing) => (\n <SelectItem key={spacing} value={String(spacing)}>\n {spacing}x\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Bold"\n active={Boolean(selectedRunStyle?.bold)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleBold}\n >\n <HugeiconsIcon icon={TextBoldIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Italic"\n active={Boolean(selectedRunStyle?.italic)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleItalic}\n >\n <HugeiconsIcon icon={TextItalicIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Underline"\n active={Boolean(selectedRunStyle?.underline)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleUnderline}\n >\n <HugeiconsIcon icon={TextUnderlineIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Strikethrough"\n active={Boolean(selectedRunStyle?.strike)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleStrike}\n >\n <HugeiconsIcon icon={TextStrikethroughIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Superscript"\n active={selectedRunStyle?.verticalAlign === "superscript"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleSuperscript}\n >\n <HugeiconsIcon icon={TextSuperscriptIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Subscript"\n active={selectedRunStyle?.verticalAlign === "subscript"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleSubscript}\n >\n <HugeiconsIcon icon={TextSubscriptIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarColorInput\n label="Text color"\n icon={TextColorIcon}\n color={textColorValue}\n disabled={!canEdit}\n onChange={(color) =>\n editor.setTextColor(normalizeHexColor(color))\n }\n />\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={!canEdit}\n aria-label="Highlight color"\n className="relative"\n >\n <HugeiconsIcon icon={HighlighterIcon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: highlightColor }}\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="z-40 w-44">\n {HIGHLIGHT_COLORS.map((option) => (\n <DropdownMenuCheckboxItem\n key={option.value}\n checked={selectedRunStyle?.highlight === option.value}\n onCheckedChange={() => editor.setHighlight(option.value)}\n >\n <span\n className="size-3 rounded-full border"\n style={{ backgroundColor: option.color }}\n />\n {option.label}\n </DropdownMenuCheckboxItem>\n ))}\n <DropdownMenuSeparator />\n <DropdownMenuCheckboxItem\n checked={!selectedRunStyle?.highlight}\n onCheckedChange={() => editor.setHighlight(undefined)}\n >\n No highlight\n </DropdownMenuCheckboxItem>\n </DropdownMenuContent>\n </DropdownMenu>\n <ToolbarIconButton\n label="Link"\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={onOpenLinkEditor}\n >\n <HugeiconsIcon icon={Link02Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Align left"\n active={\n selectedParagraph?.style?.align === "left" ||\n !selectedParagraph?.style?.align\n }\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("left")}\n >\n <HugeiconsIcon icon={TextAlignLeft01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Align center"\n active={selectedParagraph?.style?.align === "center"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("center")}\n >\n <HugeiconsIcon icon={TextAlignCenterIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Align right"\n active={selectedParagraph?.style?.align === "right"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("right")}\n >\n <HugeiconsIcon icon={TextAlignRight01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Justify"\n active={selectedParagraph?.style?.align === "justify"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("justify")}\n >\n <HugeiconsIcon\n icon={TextAlignJustifyLeftIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Bulleted list"\n active={editor.hasUnorderedList}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.toggleList("unordered")}\n >\n <HugeiconsIcon\n icon={LeftToRightListBulletIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Numbered list"\n active={editor.hasOrderedList}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.toggleList("ordered")}\n >\n <HugeiconsIcon\n icon={LeftToRightListNumberIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="sm"\n disabled={!canEdit}\n className="h-7 gap-1 px-2 shadow-none"\n >\n <HugeiconsIcon icon={borderTriggerIcon} className="size-4" />\n {borderTriggerLabel}\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="z-40 w-56">\n {BORDER_CONTROL_OPTIONS.map((option) => {\n const enabledForContext =\n !option.contexts || option.contexts.includes(borderContext)\n const BorderOptionIcon = borderControlOptionIcon(option.id)\n\n return (\n <React.Fragment key={option.id}>\n {option.separatorBefore ? <DropdownMenuSeparator /> : null}\n <DropdownMenuCheckboxItem\n checked={activeBorderPresets[option.id]}\n disabled={!enabledForContext}\n onCheckedChange={() => {\n if (enabledForContext) {\n applyBorderPreset(option.id)\n }\n }}\n >\n <HugeiconsIcon\n icon={BorderOptionIcon}\n className="size-4 text-muted-foreground"\n />\n {option.label}\n </DropdownMenuCheckboxItem>\n </React.Fragment>\n )\n })}\n </DropdownMenuContent>\n </DropdownMenu>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Insert image"\n disabled={!canEdit}\n onClick={onImageUploadClick}\n >\n <HugeiconsIcon icon={ImageAdd01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Insert table"\n disabled={!canEdit}\n onClick={editor.insertTable}\n >\n <HugeiconsIcon icon={TableIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarTooltip label="Section columns">\n <div className="flex h-7 shrink-0 items-center gap-1 rounded-lg px-2 text-xs text-muted-foreground">\n <HugeiconsIcon icon={ColumnsThreeCogIcon} className="size-4" />\n {activeColumns ? `${activeColumns.count} cols` : "1 col"}\n </div>\n </ToolbarTooltip>\n </div>\n\n <div className="ml-auto flex flex-none items-center gap-1">\n <ToolbarIconButton\n label="Zoom out"\n disabled={controlsDisabled || !canZoomOut}\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, -1)\n )\n }\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />\n </ToolbarIconButton>\n <Select\n value={zoomScale.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={controlsDisabled}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(zoomScale)}%</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="end"\n alignItemWithTrigger={false}\n className="z-40"\n >\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarIconButton\n label="Zoom in"\n disabled={controlsDisabled || !canZoomIn}\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, 1)\n )\n }\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nexport function DocxEditorPreview({\n className,\n defaultZoomScale = DOCX_EDITOR_DEFAULT_ZOOM_SCALE,\n fileName,\n isDark,\n onIsDarkChange,\n src,\n}: {\n className?: string\n defaultZoomScale?: number\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n src?: string\n}) {\n return (\n <DocxEditorContent\n className={className}\n defaultZoomScale={defaultZoomScale}\n effectiveIsDark={isDark}\n fileName={fileName}\n setIsDark={onIsDarkChange}\n shouldRenderNightMode\n url={src}\n />\n )\n}\n\nfunction DocxEditorContent({\n className,\n defaultZoomScale,\n effectiveIsDark,\n fileName,\n setIsDark,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n defaultZoomScale?: number\n effectiveIsDark: boolean\n fileName?: string\n setIsDark: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const imageInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewportElement, setViewportElement] =\n React.useState<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [activePage, setActivePage] = React.useState(1)\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const resolvedDefaultZoomScale = normalizeDocxZoomScale(defaultZoomScale)\n const [zoomScale, setZoomScale] = React.useState<number>(\n resolvedDefaultZoomScale\n )\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\n const [isReadOnly, setIsReadOnly] = React.useState(false)\n const [linkEditorOpen, setLinkEditorOpen] = React.useState(false)\n const [linkDraft, setLinkDraft] = React.useState("")\n const viewerBackgroundColor =\n "color-mix(in oklab, var(--muted) 40%, transparent)"\n const displayFileName = React.useMemo(\n () =>\n uploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),\n [fileName, uploadedDocxFile?.file.name, url]\n )\n const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>\n effectiveIsDark ? "dark" : "light"\n )\n const editorOptions = React.useMemo(\n () => ({\n initialDocumentTheme,\n initialFileName: displayFileName,\n }),\n [displayFileName, initialDocumentTheme]\n )\n const editor = useDocxEditor(editorOptions)\n const { layout: pageLayout } = useDocxPageLayout(editor)\n const { importDocxFile, setDocumentTheme, status } = editor\n const [reportedPageCount, setReportedPageCount] = React.useState(0)\n const thumbnailEditor = React.useMemo<DocxEditorController>(\n () => ({\n ...editor,\n totalPages: Math.max(editor.totalPages, reportedPageCount),\n }),\n [editor, reportedPageCount]\n )\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n []\n )\n const { thumbnails } = useDocxViewerThumbnails(\n thumbnailEditor,\n thumbnailOptions\n )\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <EditorLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const hasDocument = Boolean(url || uploadedDocxFile)\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, reportedPageCount || editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n const thumbnailSidebarOpen = Boolean(\n sidebarOpen && (pageCount || isLoadingDocument)\n )\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n const setViewportRef = React.useCallback((element: HTMLDivElement | null) => {\n viewportRef.current = element\n setViewportElement(element)\n }, [])\n const pageVirtualization = React.useMemo(\n () => ({\n enabled: true,\n overscan: 1,\n scrollElement: viewportElement,\n zoomScale: zoomScale / 100,\n }),\n [viewportElement, zoomScale]\n )\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(resolvedDefaultZoomScale)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [resolvedDefaultZoomScale, url])\n\n React.useEffect(() => {\n setDocumentTheme(effectiveIsDark ? "dark" : "light")\n }, [effectiveIsDark, setDocumentTheme])\n\n React.useEffect(() => {\n if (\n status.startsWith("Failed to load file") ||\n status === "Only .docx files are supported"\n ) {\n setLoadError(status)\n setIsLoadingDocument(false)\n }\n }, [status])\n\n React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n if (!uploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n setReportedPageCount(0)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n setReportedPageCount(0)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url ? await loadDocxFile(url, displayFileName) : null)\n if (!docxFile) return\n await importDocxFile(docxFile)\n\n if (isCurrent) {\n setIsLoadingDocument(false)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }\n } catch (error) {\n if (isCurrent) {\n setLoadError(\n error instanceof Error ? error.message : "Unknown DOCX load error"\n )\n setIsLoadingDocument(false)\n }\n }\n }\n\n void load()\n\n return () => {\n isCurrent = false\n }\n }, [displayFileName, importDocxFile, uploadedDocxFile, url])\n\n React.useEffect(() => {\n if (url) {\n setUploadedDocxFile(null)\n }\n }, [url])\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n let closestPage = 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>(\n \'[data-docx-page-wrapper="true"][data-index]\'\n )\n .forEach((page) => {\n const pageIndex = Number(page.dataset.index)\n if (!Number.isFinite(pageIndex)) return\n\n const pageRect = page.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = pageIndex + 1\n }\n })\n\n setActivePage((currentPage) =>\n currentPage === closestPage ? currentPage : closestPage\n )\n }, [pageCount])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n let frameId = 0\n const handleScroll = () => {\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener("scroll", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n viewport.removeEventListener("scroll", handleScroll)\n }\n }, [pageCount, updateActivePageFromViewport])\n\n const scrollToPage = React.useCallback(\n (pageNumber: number) => {\n const viewport = viewportRef.current\n const targetPageIndex = pageNumber - 1\n const page = viewport?.querySelector<HTMLElement>(\n `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`\n )\n\n setActivePage(pageNumber)\n\n if (!viewport) return\n\n if (!page) {\n const pageStridePx =\n (pageLayout.pageHeightPx + pageLayout.viewportDefaults.pageGapPx) *\n (zoomScale / 100)\n\n viewport.scrollTo({\n top: Math.max(0, targetPageIndex * pageStridePx - 24),\n behavior: "auto",\n })\n return\n }\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n },\n [pageLayout.pageHeightPx, pageLayout.viewportDefaults.pageGapPx, zoomScale]\n )\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n setZoomScale(resolvedDefaultZoomScale)\n setActivePage(1)\n setReportedPageCount(0)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n async function handleImageUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n await editor.insertImageFile(file)\n }\n\n function openLinkEditor() {\n setLinkDraft(editor.selectedLink ?? "")\n setLinkEditorOpen(true)\n }\n\n function applyLink() {\n editor.setLink(linkDraft.trim() || undefined)\n setLinkEditorOpen(false)\n }\n\n return (\n <div\n className={cn(\n "flex h-[720px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n <input\n ref={imageInputRef}\n type="file"\n accept="image/*"\n className="hidden"\n onChange={handleImageUpload}\n />\n <DocxEditorToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n editor={editor}\n isReadOnly={isReadOnly}\n onImageUploadClick={() => imageInputRef.current?.click()}\n onIsDarkChange={setIsDark}\n onIsReadOnlyChange={setIsReadOnly}\n onOpenLinkEditor={openLinkEditor}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showNightRenderToggle={shouldRenderNightMode}\n zoomScale={zoomScale}\n />\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {linkEditorOpen ? (\n <div className="absolute top-3 left-1/2 z-50 flex w-[min(420px,calc(100%-2rem))] -translate-x-1/2 items-center gap-2 rounded-lg border bg-background p-2 shadow-lg">\n <Input\n value={linkDraft}\n onChange={(event) => setLinkDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === "Enter") {\n event.preventDefault()\n applyLink()\n }\n if (event.key === "Escape") {\n setLinkEditorOpen(false)\n }\n }}\n placeholder="https://example.com"\n aria-label="Link URL"\n />\n <Button type="button" size="sm" onClick={applyLink}>\n Apply\n </Button>\n <Button\n type="button"\n size="sm"\n variant="ghost"\n onClick={() => {\n editor.setLink(undefined)\n setLinkEditorOpen(false)\n }}\n >\n Clear\n </Button>\n </div>\n ) : null}\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={thumbnailSidebarOpen}\n >\n <ScrollArea\n className="h-full"\n scrollFade\n viewportClassName="overscroll-contain"\n >\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </>\n ) : (\n <div className="flex flex-col items-center gap-3">\n {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (\n <Button\n key={thumbnail.pageIndex}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent text-foreground",\n thumbnail.pageNumber !== activePage &&\n "text-muted-foreground"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => scrollToPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n !thumbnail.isMounted &&\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n ))}\n </div>\n )}\n </div>\n </ScrollArea>\n </DocumentViewerThumbnailSidebar>\n <ScrollArea\n className="min-h-0 flex-1"\n style={{ backgroundColor: viewerBackgroundColor }}\n viewportClassName="overscroll-contain p-4"\n viewportRef={setViewportRef}\n >\n {!url && !uploadedDocxFile ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm shadow-xs">\n <div className="font-medium">Upload a DOCX to edit</div>\n <div className="mt-1 text-muted-foreground">\n Pass a DOCX URL with the <code>src</code> prop or upload a\n file.\n </div>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload DOCX\n </Button>\n </div>\n </div>\n ) : loadError ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm text-destructive shadow-xs">\n <div className="font-medium">Unable to edit DOCX</div>\n <div className="mt-1 text-muted-foreground">{loadError}</div>\n </div>\n </div>\n ) : isLoadingDocument ? (\n loadingState\n ) : (\n <div className="mx-auto flex min-h-full justify-center">\n <div\n className={cn(\n "origin-top",\n editor.documentTheme === "dark" && "docx-night-reader-shell"\n )}\n style={{ zoom: zoomScale / 100 }}\n >\n <DocxEditorViewer\n editor={editor}\n mode={isReadOnly ? "read-only" : "edit"}\n showTrackedChanges={editor.showTrackedChanges}\n renderTrackedChangeCard={renderDocxTrackedChangeCard}\n showComments={editor.showComments}\n renderCommentCard={renderDocxCommentCard}\n loadingState={loadingState}\n pageBackgroundColor={\n editor.documentTheme === "dark" ? "#0a0a0a" : undefined\n }\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={pageVirtualization}\n deferInitialPaginationPaint={false}\n onPageCountChange={handlePageCountChange}\n />\n </div>\n </div>\n )}\n </ScrollArea>\n </div>\n </div>\n )\n}\n'export function DocxEditorSource() {return (diff --git a/apps/v4/components/docx-viewer-docs.tsx b/apps/v4/components/docx-viewer-docs.tsxindex 8bbbfcf..a884a2c 100644--- a/apps/v4/components/docx-viewer-docs.tsx+++ b/apps/v4/components/docx-viewer-docs.tsx@@ -65,7 +65,7 @@ export function DocxViewerExample() {}`const docxViewerSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n DocxEditorViewer,\n useDocxEditor,\n useDocxViewerThumbnails,\n type DocxDocumentTheme,\n type DocxEditorController,\n} from "@extend-ai/react-docx"\nimport {\n Download01Icon,\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n SidebarLeftIcon,\n Sun03Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/ui/document-viewer-sidebar"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { Input } from "@/components/ui/input"\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"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst ZOOM_OPTIONS = [10, 25, 50, 75, 100, 125, 150, 175, 200, 400] as const\nconst DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n}\n\nasync function loadDocxFile(\n url: string,\n displayFileName: string\n): Promise<File> {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n return new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n}\n\nfunction formatDocumentName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "document.docx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction ensureDocxExtension(fileName: string) {\n return fileName.toLowerCase().endsWith(".docx")\n ? fileName\n : `${fileName}.docx`\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 downloadDocxFile({\n file,\n fileName,\n url,\n}: {\n file?: File\n fileName: string\n url?: string\n}) {\n if (file) {\n downloadBlob(file, ensureDocxExtension(fileName))\n return\n }\n\n if (!url) return\n\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to download DOCX (${response.status})`)\n }\n\n downloadBlob(await response.blob(), ensureDocxExtension(fileName))\n}\n\nfunction getNextZoomScale(currentZoomScale: number, direction: 1 | -1) {\n const currentIndex = ZOOM_OPTIONS.indexOf(\n currentZoomScale as (typeof ZOOM_OPTIONS)[number]\n )\n let fallbackIndex = -1\n\n if (direction > 0) {\n fallbackIndex = ZOOM_OPTIONS.findIndex((value) => value > currentZoomScale)\n } else {\n for (let index = ZOOM_OPTIONS.length - 1; index >= 0; index -= 1) {\n if (ZOOM_OPTIONS[index] < currentZoomScale) {\n fallbackIndex = index\n break\n }\n }\n }\n\n const resolvedIndex = currentIndex >= 0 ? currentIndex : fallbackIndex\n if (resolvedIndex < 0) return currentZoomScale\n\n const nextIndex = Math.min(\n Math.max(resolvedIndex + direction, 0),\n ZOOM_OPTIONS.length - 1\n )\n\n return ZOOM_OPTIONS[nextIndex] ?? currentZoomScale\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === "string" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes("padding"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\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 ViewerLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction DocxPageNumberControl({\n activePage,\n controlsDisabled,\n onPageChange,\n pageCount,\n}: {\n activePage: number\n controlsDisabled: boolean\n onPageChange: (pageNumber: number) => void\n pageCount: number\n}) {\n const inputRef = React.useRef<HTMLInputElement>(null)\n const displayPage = pageCount ? 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?.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 if (parsedPage < 1 || parsedPage > pageCount) return\n\n onPageChange(parsedPage)\n },\n [onPageChange, pageCount]\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 || !pageCount}\n onClick={() => setIsEditing(true)}\n >\n {displayPage}\n </Button>\n )}\n <span>of {pageCount || "-"}</span>\n </div>\n )\n}\n\nfunction DocxToolbar({\n activePage,\n controlsDisabled,\n isDark,\n isPreparingDownload,\n onDownload,\n onIsDarkChange,\n onPageChange,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showDownloadButton = true,\n showNightRenderToggle,\n showUploadButton = true,\n toolbarActions,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n isDark: boolean\n isPreparingDownload: boolean\n onDownload: () => void\n onIsDarkChange: (checked: boolean) => void\n onPageChange: (pageNumber: number) => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showDownloadButton?: boolean\n showNightRenderToggle: boolean\n showUploadButton?: boolean\n toolbarActions?: React.ReactNode\n zoomScale: number\n}) {\n const canZoomIn = zoomScale < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n const canZoomOut = zoomScale > ZOOM_OPTIONS[0]\n\n return (\n <div className="flex min-h-12 flex-wrap items-center justify-between gap-2 border-b bg-background px-3 py-2">\n <TooltipProvider>\n <div className="flex min-w-0 flex-wrap items-center gap-2">\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={onToggleSidebar}\n >\n <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <DocxPageNumberControl\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n onPageChange={onPageChange}\n pageCount={pageCount}\n />\n </div>\n <div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1">\n {showNightRenderToggle ? (\n <ToolbarTooltip\n label={isDark ? "Use light document" : "Use dark document"}\n >\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled}\n aria-label={isDark ? "Use light document" : "Use dark document"}\n onClick={() => onIsDarkChange(!isDark)}\n >\n <HugeiconsIcon\n icon={isDark ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n ) : null}\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\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 disabled={controlsDisabled || !canZoomOut}\n aria-label="Zoom out"\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, -1)\n )\n }\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <Select\n value={zoomScale.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={controlsDisabled}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(zoomScale)}%</SelectValue>\n </SelectTrigger>\n <SelectContent align="end" alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\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 disabled={controlsDisabled || !canZoomIn}\n aria-label="Zoom in"\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, 1)\n )\n }\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </div>\n {showDownloadButton ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <ToolbarTooltip label="Download DOCX">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Download DOCX"\n disabled={controlsDisabled || isPreparingDownload}\n onClick={onDownload}\n >\n {isPreparingDownload ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n )}\n </Button>\n </ToolbarTooltip>\n </>\n ) : null}\n {showUploadButton ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <ToolbarTooltip label="Upload DOCX">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Upload DOCX"\n onClick={onUploadClick}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </>\n ) : null}\n {toolbarActions ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {toolbarActions}\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nfunction DocxSidebarThumbnail({\n canvasRef,\n displayFileName,\n hasError,\n isActive,\n isLoading,\n pageNumber,\n pixelHeightPx,\n pixelWidthPx,\n previewAspectRatio,\n}: {\n canvasRef: React.RefCallback<HTMLCanvasElement>\n displayFileName: string\n hasError: boolean\n isActive: boolean\n isLoading: boolean\n pageNumber: number\n pixelHeightPx: number\n pixelWidthPx: number\n previewAspectRatio: number\n}) {\n return (\n <FileThumbnail\n file={{\n name: `${displayFileName} page ${pageNumber}`,\n type: DOCX_MIME_TYPE,\n }}\n previewAspectRatio={previewAspectRatio}\n previewClassName="rounded-md bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n isLoading={isLoading}\n hasError={hasError}\n className={cn(\n "w-[92px] rounded-md border-0 shadow-xs ring-0 transition-shadow duration-150",\n isActive && "shadow-sm"\n )}\n />\n )\n}\n\nexport function DocxViewerPreview({\n className,\n defaultThumbnailSidebarOpen = false,\n fileName,\n isDark,\n onIsDarkChange,\n rounded = false,\n showDownload = true,\n showToolbar = true,\n showUpload = true,\n src,\n toolbarActions,\n}: {\n className?: string\n defaultThumbnailSidebarOpen?: boolean\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n rounded?: boolean\n showDownload?: boolean\n showToolbar?: boolean\n showUpload?: boolean\n src?: string\n toolbarActions?: React.ReactNode\n}) {\n return (\n <DocxViewerContent\n className={className}\n defaultThumbnailSidebarOpen={defaultThumbnailSidebarOpen}\n effectiveIsDark={isDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={onIsDarkChange}\n shouldRenderNightMode\n showDownload={showDownload}\n showToolbar={showToolbar}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n url={src}\n />\n )\n}\n\nfunction DocxViewerContent({\n className,\n defaultThumbnailSidebarOpen,\n effectiveIsDark,\n fileName,\n rounded,\n setNightRenderEnabled,\n shouldRenderNightMode,\n showDownload,\n showToolbar = true,\n showUpload,\n toolbarActions,\n url,\n}: {\n className?: string\n defaultThumbnailSidebarOpen: boolean\n effectiveIsDark: boolean\n fileName?: string\n rounded: boolean\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n showDownload: boolean\n showToolbar?: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewportElement, setViewportElement] =\n React.useState<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [activePage, setActivePage] = React.useState(1)\n const [sidebarOpen, setSidebarOpen] = React.useState(\n defaultThumbnailSidebarOpen\n )\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const viewerBackgroundColor =\n "color-mix(in oklab, var(--muted) 40%, transparent)"\n const displayFileName = React.useMemo(\n () =>\n uploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),\n [fileName, uploadedDocxFile?.file.name, url]\n )\n const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>\n effectiveIsDark ? "dark" : "light"\n )\n const editorOptions = React.useMemo(\n () => ({\n initialDocumentTheme,\n initialFileName: displayFileName,\n }),\n [displayFileName, initialDocumentTheme]\n )\n const editor = useDocxEditor(editorOptions)\n const { importDocxFile, setDocumentTheme, status } = editor\n const [reportedPageCount, setReportedPageCount] = React.useState(0)\n const thumbnailEditor = React.useMemo<DocxEditorController>(\n () => ({\n ...editor,\n totalPages: Math.max(editor.totalPages, reportedPageCount),\n }),\n [editor, reportedPageCount]\n )\n const thumbnailOptions = React.useMemo(\n () => ({\n // Thumbnails paint from mounted page DOM, so they can only render\n // while the sidebar is showing them; skip the work when it is closed.\n disabled: !sidebarOpen,\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n [sidebarOpen]\n )\n const { thumbnails } = useDocxViewerThumbnails(\n thumbnailEditor,\n thumbnailOptions\n )\n const [zoomScale, setZoomScale] = React.useState(100)\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\n const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <ViewerLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const hasDocument = Boolean(url || uploadedDocxFile)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, reportedPageCount || editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n const setViewportRef = React.useCallback(\n (element: HTMLDivElement | null) => {\n viewportRef.current = element\n setViewportElement(element)\n },\n []\n )\n const pageVirtualization = React.useMemo(\n () => ({\n // Sidebar thumbnails can only paint from mounted page DOM,\n // so every page must mount while the sidebar is open;\n // otherwise let the viewer virtualize off-screen pages.\n enabled: !sidebarOpen,\n scrollElement: viewportElement,\n zoomScale: zoomScale / 100,\n }),\n [sidebarOpen, viewportElement, zoomScale]\n )\n const handleDownload = React.useCallback(async () => {\n if (isPreparingDownload) return\n if (!uploadedDocxFile && !url) return\n\n setIsPreparingDownload(true)\n\n try {\n await downloadDocxFile({\n file: uploadedDocxFile?.file,\n fileName: displayFileName,\n url,\n })\n } catch (error) {\n console.error(error)\n } finally {\n setIsPreparingDownload(false)\n }\n }, [displayFileName, isPreparingDownload, uploadedDocxFile, url])\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(100)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [url])\n\n React.useEffect(() => {\n setDocumentTheme(effectiveIsDark ? "dark" : "light")\n }, [effectiveIsDark, setDocumentTheme])\n\n React.useEffect(() => {\n if (\n status.startsWith("Failed to load file") ||\n status === "Only .docx files are supported"\n ) {\n setLoadError(status)\n setIsLoadingDocument(false)\n }\n }, [status])\n\n // Imports mutate the shared editor instance; concurrent calls (effect\n // re-runs, StrictMode double-invoke) race inside the parser and surface as\n // bogus "Invalid DOCX ZIP" errors, so every import is chained through here.\n const importQueueRef = React.useRef<Promise<void>>(Promise.resolve())\n\n React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n // Superseded while queued — let the newest import run instead.\n if (!isCurrent) return\n if (!uploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n setReportedPageCount(0)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n setReportedPageCount(0)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url ? await loadDocxFile(url, displayFileName) : null)\n if (!docxFile) return\n await importDocxFile(docxFile)\n\n if (isCurrent) {\n setIsLoadingDocument(false)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }\n } catch (error) {\n if (isCurrent) {\n setLoadError(\n error instanceof Error ? error.message : "Unknown DOCX load error"\n )\n setIsLoadingDocument(false)\n }\n }\n }\n\n importQueueRef.current = importQueueRef.current.then(load)\n\n return () => {\n isCurrent = false\n }\n }, [displayFileName, importDocxFile, uploadedDocxFile, url])\n\n React.useEffect(() => {\n if (url) {\n setUploadedDocxFile(null)\n }\n }, [url])\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n let closestPage = 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>(\n \'[data-docx-page-wrapper="true"][data-index]\'\n )\n .forEach((page) => {\n const pageIndex = Number(page.dataset.index)\n if (!Number.isFinite(pageIndex)) return\n\n const pageRect = page.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = pageIndex + 1\n }\n })\n\n setActivePage((currentPage) =>\n currentPage === closestPage ? currentPage : closestPage\n )\n }, [pageCount])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n let frameId = 0\n const handleScroll = () => {\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener("scroll", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n viewport.removeEventListener("scroll", handleScroll)\n }\n }, [pageCount, updateActivePageFromViewport])\n\n const scrollToPage = React.useCallback((pageNumber: number) => {\n const viewport = viewportRef.current\n const targetPageIndex = pageNumber - 1\n const page = viewport?.querySelector<HTMLElement>(\n `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`\n )\n\n setActivePage(pageNumber)\n\n if (!viewport || !page) return\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n }, [])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n setZoomScale(100)\n setActivePage(1)\n setReportedPageCount(0)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n {showToolbar ? (\n <DocxToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n isDark={effectiveIsDark}\n isPreparingDownload={isPreparingDownload}\n onDownload={handleDownload}\n onIsDarkChange={setNightRenderEnabled}\n onPageChange={scrollToPage}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showDownloadButton={showDownload}\n showNightRenderToggle={shouldRenderNightMode}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n zoomScale={zoomScale}\n />\n ) : null}\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}\n >\n <ScrollArea className="h-full" scrollFade>\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </>\n ) : (\n <div className="flex flex-col items-center gap-3">\n {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (\n <Button\n key={thumbnail.pageIndex}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none transition-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent text-foreground",\n thumbnail.pageNumber !== activePage &&\n "text-muted-foreground"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => scrollToPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n !thumbnail.isMounted &&\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n ))}\n </div>\n )}\n </div>\n </ScrollArea>\n </DocumentViewerThumbnailSidebar>\n <ScrollArea\n className={cn("min-h-0 flex-1", rounded && "rounded-b-lg")}\n style={{ backgroundColor: viewerBackgroundColor }}\n viewportClassName="p-4"\n viewportRef={setViewportRef}\n >\n {!url && !uploadedDocxFile ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm shadow-xs">\n <div className="font-medium">Upload a DOCX to preview</div>\n <div className="mt-1 text-muted-foreground">\n Pass a DOCX URL with the <code>src</code> prop or upload a\n file.\n </div>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload DOCX\n </Button>\n </div>\n </div>\n ) : loadError ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm text-destructive shadow-xs">\n <div className="font-medium">Unable to display DOCX</div>\n <div className="mt-1 text-muted-foreground">{loadError}</div>\n </div>\n </div>\n ) : isLoadingDocument ? (\n loadingState\n ) : (\n <div className="mx-auto flex min-h-full justify-center">\n <div\n className={cn(\n "origin-top",\n effectiveIsDark && "docx-night-reader-shell"\n )}\n style={{ zoom: zoomScale / 100 }}\n >\n <DocxEditorViewer\n editor={editor}\n mode="read-only"\n loadingState={loadingState}\n pageBackgroundColor={effectiveIsDark ? "#0a0a0a" : undefined}\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={pageVirtualization}\n deferInitialPaginationPaint={false}\n onPageCountChange={handlePageCountChange}\n />\n </div>\n </div>\n )}\n </ScrollArea>\n </div>\n </div>\n )\n}\n'+ "\"use client\"\n\nimport * as React from \"react\"\nimport {\n DocxEditorViewer,\n useDocxComments,\n useDocxEditor,\n useDocxPageLayout,\n useDocxTrackChanges,\n useDocxViewerThumbnails,\n type DocxDocumentTheme,\n type DocxEditorController,\n type DocxPageThumbnailItem,\n} from \"@extend-ai/react-docx\"\nimport { useVirtualizer } from \"@tanstack/react-virtual\"\nimport {\n Comment01Icon,\n Download01Icon,\n MinusSignCircleIcon,\n Moon02Icon,\n MoreHorizontalIcon,\n PlusSignCircleIcon,\n SidebarLeftIcon,\n Upload01Icon,\n} from \"@hugeicons/core-free-icons\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from \"@/components/ui/document-viewer-sidebar\"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from \"@/components/ui/dropdown-menu\"\nimport { FileThumbnail } from \"@/components/ui/file-thumbnail\"\nimport { Input } from \"@/components/ui/input\"\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\"\n\nconst DOCX_MIME_TYPE =\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\"\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst DOCX_THUMBNAIL_LIST_PADDING = 16\nconst DOCX_THUMBNAIL_ROW_ESTIMATE = 172\nconst DEFAULT_ZOOM = 50\nconst ZOOM_OPTIONS = [10, 25, 50, 75, 100, 125, 150, 175, 200, 400] as const\nconst DOCX_PADDING_WARNING_TEXT = \"a style property during rerender\"\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n}\n\nasync function loadDocxFile(\n url: string,\n displayFileName: string\n): Promise<File> {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n return new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n}\n\nfunction formatDocumentName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split(\"?\")[0] ?? \"\"\n const rawName = pathname.split(\"/\").pop() ?? \"document.docx\"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction ensureDocxExtension(fileName: string) {\n return fileName.toLowerCase().endsWith(\".docx\")\n ? fileName\n : `${fileName}.docx`\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 downloadDocxFile({\n file,\n fileName,\n url,\n}: {\n file?: File\n fileName: string\n url?: string\n}) {\n if (file) {\n downloadBlob(file, ensureDocxExtension(fileName))\n return\n }\n\n if (!url) return\n\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to download DOCX (${response.status})`)\n }\n\n downloadBlob(await response.blob(), ensureDocxExtension(fileName))\n}\n\nfunction getNextZoomScale(currentZoomScale: number, direction: 1 | -1) {\n const currentIndex = ZOOM_OPTIONS.indexOf(\n currentZoomScale as (typeof ZOOM_OPTIONS)[number]\n )\n let fallbackIndex = -1\n\n if (direction > 0) {\n fallbackIndex = ZOOM_OPTIONS.findIndex((value) => value > currentZoomScale)\n } else {\n for (let index = ZOOM_OPTIONS.length - 1; index >= 0; index -= 1) {\n if (ZOOM_OPTIONS[index] < currentZoomScale) {\n fallbackIndex = index\n break\n }\n }\n }\n\n const resolvedIndex = currentIndex >= 0 ? currentIndex : fallbackIndex\n if (resolvedIndex < 0) return currentZoomScale\n\n const nextIndex = Math.min(\n Math.max(resolvedIndex + direction, 0),\n ZOOM_OPTIONS.length - 1\n )\n\n return ZOOM_OPTIONS[nextIndex] ?? currentZoomScale\n}\n\nfunction normalizeDocxZoomScale(value: number | undefined): number {\n return typeof value === \"number\" &&\n ZOOM_OPTIONS.includes(value as (typeof ZOOM_OPTIONS)[number])\n ? value\n : DEFAULT_ZOOM\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === \"string\" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes(\"padding\"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\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 ViewerLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className=\"grid h-full min-h-52 place-items-center bg-transparent\">\n {showSpinner ? <Spinner className=\"size-4\" /> : null}\n </div>\n )\n}\n\nfunction DocxFileActionsMenu({\n controlsDisabled,\n downloadDisabled,\n isPreparingDownload,\n isDark,\n onDownload,\n onIsDarkChange,\n onShowDocumentMarkupChange,\n onUploadClick,\n showDocumentMarkup,\n showDownloadButton,\n showNightRenderToggle,\n showUploadButton,\n}: {\n controlsDisabled: boolean\n downloadDisabled: boolean\n isPreparingDownload: boolean\n isDark: boolean\n onDownload: () => void\n onIsDarkChange: (checked: boolean) => void\n onShowDocumentMarkupChange: (checked: boolean) => void\n onUploadClick: () => void\n showDocumentMarkup: boolean\n showDownloadButton: boolean\n showNightRenderToggle: boolean\n showUploadButton: boolean\n}) {\n const showFileActions = showDownloadButton || showUploadButton\n\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Open DOCX actions\"\n >\n <HugeiconsIcon icon={MoreHorizontalIcon} className=\"size-4\" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\" className=\"w-52\">\n {showNightRenderToggle ? (\n <>\n <DropdownMenuCheckboxItem\n checked={isDark}\n disabled={controlsDisabled}\n variant=\"switch\"\n onCheckedChange={(checked) => onIsDarkChange(checked === true)}\n >\n <span className=\"flex min-w-0 items-center gap-2\">\n <HugeiconsIcon icon={Moon02Icon} className=\"size-4\" />\n Dark mode\n </span>\n </DropdownMenuCheckboxItem>\n <DropdownMenuSeparator />\n </>\n ) : null}\n <DropdownMenuCheckboxItem\n checked={showDocumentMarkup}\n disabled={controlsDisabled}\n variant=\"switch\"\n onCheckedChange={(checked) =>\n onShowDocumentMarkupChange(checked === true)\n }\n >\n <span className=\"flex min-w-0 items-center gap-2\">\n <HugeiconsIcon icon={Comment01Icon} className=\"size-4\" />\n Comments/edits\n </span>\n </DropdownMenuCheckboxItem>\n {showFileActions ? <DropdownMenuSeparator /> : null}\n {showDownloadButton ? (\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 {showUploadButton ? (\n <DropdownMenuItem onClick={onUploadClick}>\n <HugeiconsIcon icon={Upload01Icon} className=\"size-4\" />\n Upload\n </DropdownMenuItem>\n ) : null}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction DocxPageNumberControl({\n activePage,\n controlsDisabled,\n onPageChange,\n pageCount,\n}: {\n activePage: number\n controlsDisabled: boolean\n onPageChange: (pageNumber: number) => void\n pageCount: number\n}) {\n const inputRef = React.useRef<HTMLInputElement>(null)\n const displayPage = pageCount ? 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?.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 if (parsedPage < 1 || parsedPage > pageCount) return\n\n onPageChange(parsedPage)\n },\n [onPageChange, pageCount]\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 || !pageCount}\n onClick={() => setIsEditing(true)}\n >\n {displayPage}\n </Button>\n )}\n <span>of {pageCount || \"-\"}</span>\n </div>\n )\n}\n\nfunction DocxToolbar({\n activePage,\n controlsDisabled,\n isDark,\n isPreparingDownload,\n onDownload,\n onIsDarkChange,\n onPageChange,\n onShowDocumentMarkupChange,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showDocumentMarkup,\n showDownloadButton = true,\n showNightRenderToggle,\n showUploadButton = true,\n toolbarActions,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n isDark: boolean\n isPreparingDownload: boolean\n onDownload: () => void\n onIsDarkChange: (checked: boolean) => void\n onPageChange: (pageNumber: number) => void\n onShowDocumentMarkupChange: (checked: boolean) => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showDocumentMarkup: boolean\n showDownloadButton?: boolean\n showNightRenderToggle: boolean\n showUploadButton?: boolean\n toolbarActions?: React.ReactNode\n zoomScale: number\n}) {\n const canZoomIn = zoomScale < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n const canZoomOut = zoomScale > ZOOM_OPTIONS[0]\n\n return (\n <div className=\"flex min-h-12 flex-wrap items-center justify-between gap-2 border-b bg-background px-3 py-2\">\n <TooltipProvider>\n <div className=\"flex min-w-0 flex-wrap items-center gap-2\">\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={onToggleSidebar}\n >\n <HugeiconsIcon icon={SidebarLeftIcon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n <DocxPageNumberControl\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n onPageChange={onPageChange}\n pageCount={pageCount}\n />\n </div>\n <div className=\"ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1\">\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 disabled={controlsDisabled || !canZoomOut}\n aria-label=\"Zoom out\"\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, -1)\n )\n }\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n <Select\n value={zoomScale.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={controlsDisabled}\n modal={false}\n >\n <SelectTrigger\n size=\"sm\"\n className=\"w-[84px] min-w-[84px]\"\n aria-label=\"Zoom level\"\n >\n <SelectValue>{Math.round(zoomScale)}%</SelectValue>\n </SelectTrigger>\n <SelectContent align=\"end\" alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\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 disabled={controlsDisabled || !canZoomIn}\n aria-label=\"Zoom in\"\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, 1)\n )\n }\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n </div>\n {toolbarActions ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n {toolbarActions}\n </>\n ) : null}\n <Separator orientation=\"vertical\" className=\"mx-1 h-4 self-center\" />\n <DocxFileActionsMenu\n controlsDisabled={controlsDisabled}\n downloadDisabled={controlsDisabled || isPreparingDownload}\n isPreparingDownload={isPreparingDownload}\n isDark={isDark}\n onDownload={onDownload}\n onIsDarkChange={onIsDarkChange}\n onShowDocumentMarkupChange={onShowDocumentMarkupChange}\n onUploadClick={onUploadClick}\n showDocumentMarkup={showDocumentMarkup}\n showDownloadButton={showDownloadButton}\n showNightRenderToggle={showNightRenderToggle}\n showUploadButton={showUploadButton}\n />\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nfunction DocxSidebarThumbnail({\n canvasRef,\n displayFileName,\n hasError,\n isActive,\n isLoading,\n pageNumber,\n pixelHeightPx,\n pixelWidthPx,\n previewAspectRatio,\n}: {\n canvasRef: React.RefCallback<HTMLCanvasElement>\n displayFileName: string\n hasError: boolean\n isActive: boolean\n isLoading: boolean\n pageNumber: number\n pixelHeightPx: number\n pixelWidthPx: number\n previewAspectRatio: number\n}) {\n return (\n <FileThumbnail\n file={{\n name: `${displayFileName} page ${pageNumber}`,\n type: DOCX_MIME_TYPE,\n }}\n previewAspectRatio={previewAspectRatio}\n previewClassName=\"rounded-md bg-white\"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className=\"!size-full bg-white object-cover object-top\"\n />\n }\n isLoading={isLoading}\n hasError={hasError}\n className={cn(\n \"w-[92px] rounded-md border-0 shadow-xs ring-0 transition-shadow duration-150\",\n isActive && \"shadow-sm\"\n )}\n />\n )\n}\n\nfunction DocxThumbnailSidebarList({\n activePage,\n displayFileName,\n isLoadingDocument,\n onSelectPage,\n pageCount,\n sidebarOpen,\n thumbnails,\n}: {\n activePage: number\n displayFileName: string\n isLoadingDocument: boolean\n onSelectPage: (pageNumber: number) => void\n pageCount: number\n sidebarOpen: boolean\n thumbnails: DocxPageThumbnailItem[]\n}) {\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const visibleThumbnails = React.useMemo(\n () => thumbnails.slice(0, pageCount || 0),\n [pageCount, thumbnails]\n )\n const virtualizer = useVirtualizer({\n count: visibleThumbnails.length,\n estimateSize: () => DOCX_THUMBNAIL_ROW_ESTIMATE,\n getItemKey: (index) => visibleThumbnails[index]?.pageIndex ?? index,\n getScrollElement: () => viewportRef.current,\n overscan: 3,\n })\n\n React.useEffect(() => {\n if (!sidebarOpen || activePage < 1 || !visibleThumbnails.length) return\n\n virtualizer.scrollToIndex(\n Math.min(activePage - 1, visibleThumbnails.length - 1),\n { align: \"auto\" }\n )\n }, [activePage, sidebarOpen, virtualizer, visibleThumbnails.length])\n\n return (\n <ScrollArea className=\"h-full\" scrollFade viewportRef={viewportRef}>\n {isLoadingDocument ? (\n <div className=\"p-4\">\n <div className=\"mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs\">\n <div className=\"h-full animate-pulse bg-muted\" />\n </div>\n <div className=\"mx-auto mt-3 h-3 w-10 rounded-full bg-muted\" />\n </div>\n ) : visibleThumbnails.length ? (\n <div\n className=\"relative\"\n style={{\n height: virtualizer.getTotalSize() + DOCX_THUMBNAIL_LIST_PADDING * 2,\n }}\n >\n {virtualizer.getVirtualItems().map((virtualRow) => {\n const thumbnail = visibleThumbnails[virtualRow.index]\n if (!thumbnail) return null\n\n return (\n <div\n key={virtualRow.key}\n ref={virtualizer.measureElement}\n data-index={virtualRow.index}\n className=\"absolute top-0 right-3 left-3 pb-3 [contain:layout_paint]\"\n style={{\n transform: `translateY(${\n virtualRow.start + DOCX_THUMBNAIL_LIST_PADDING\n }px)`,\n }}\n >\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className={cn(\n \"!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none transition-none hover:bg-sidebar-accent\",\n thumbnail.pageNumber === activePage &&\n \"bg-sidebar-accent text-foreground\",\n thumbnail.pageNumber !== activePage &&\n \"text-muted-foreground\"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => onSelectPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === \"error\"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n thumbnail.status !== \"ready\" &&\n thumbnail.status !== \"error\"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n </div>\n )\n })}\n </div>\n ) : null}\n </ScrollArea>\n )\n}\n\nexport function DocxViewerPreview({\n className,\n defaultZoom = DEFAULT_ZOOM,\n fileName,\n isDark,\n onIsDarkChange,\n showDownload = true,\n showToolbar = true,\n showUpload = true,\n src,\n toolbarActions,\n}: {\n className?: string\n defaultZoom?: number\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n showDownload?: boolean\n showToolbar?: boolean\n showUpload?: boolean\n src?: string\n toolbarActions?: React.ReactNode\n}) {\n return (\n <DocxViewerContent\n className={className}\n defaultZoom={defaultZoom}\n effectiveIsDark={isDark}\n fileName={fileName}\n setNightRenderEnabled={onIsDarkChange}\n shouldRenderNightMode\n showDownload={showDownload}\n showToolbar={showToolbar}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n url={src}\n />\n )\n}\n\nfunction DocxViewerContent({\n className,\n defaultZoom,\n effectiveIsDark,\n fileName,\n setNightRenderEnabled,\n shouldRenderNightMode,\n showDownload,\n showToolbar = true,\n showUpload,\n toolbarActions,\n url,\n}: {\n className?: string\n defaultZoom?: number\n effectiveIsDark: boolean\n fileName?: string\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n showDownload: boolean\n showToolbar?: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewportElement, setViewportElement] =\n React.useState<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [activePage, setActivePage] = React.useState(1)\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const resolvedDefaultZoomScale = normalizeDocxZoomScale(defaultZoom)\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const viewerBackgroundColor =\n \"color-mix(in oklab, var(--muted) 40%, transparent)\"\n const displayFileName = React.useMemo(\n () =>\n uploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? \"document.docx\")),\n [fileName, uploadedDocxFile?.file.name, url]\n )\n const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>\n effectiveIsDark ? \"dark\" : \"light\"\n )\n const editorOptions = React.useMemo(\n () => ({\n initialDocumentTheme,\n initialFileName: displayFileName,\n }),\n [displayFileName, initialDocumentTheme]\n )\n const editor = useDocxEditor(editorOptions)\n const { layout: pageLayout } = useDocxPageLayout(editor)\n const { importDocxFile, setDocumentTheme, status } = editor\n const { showComments, setShowComments } = useDocxComments(editor)\n const { showTrackedChanges, setShowTrackedChanges } =\n useDocxTrackChanges(editor)\n const [reportedPageCount, setReportedPageCount] = React.useState(0)\n const thumbnailEditor = React.useMemo<DocxEditorController>(\n () => ({\n ...editor,\n totalPages: Math.max(editor.totalPages, reportedPageCount),\n }),\n [editor, reportedPageCount]\n )\n const thumbnailOptions = React.useMemo(\n () => ({\n // Detached thumbnail rendering handles offscreen pages; keep the raster\n // queue dormant while the sidebar is closed.\n disabled: !sidebarOpen,\n pixelRatio: 1,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n [sidebarOpen]\n )\n const { thumbnails } = useDocxViewerThumbnails(\n thumbnailEditor,\n thumbnailOptions\n )\n const [zoomScale, setZoomScale] = React.useState<number>(\n resolvedDefaultZoomScale\n )\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\n const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <ViewerLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const hasDocument = Boolean(url || uploadedDocxFile)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, reportedPageCount || editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n const showDocumentMarkup = showComments || showTrackedChanges\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n const setViewportRef = React.useCallback((element: HTMLDivElement | null) => {\n viewportRef.current = element\n setViewportElement(element)\n }, [])\n const pageVirtualization = React.useMemo(\n () => ({\n enabled: true,\n overscan: 1,\n scrollElement: viewportElement,\n zoomScale: zoomScale / 100,\n }),\n [viewportElement, zoomScale]\n )\n const handleDownload = React.useCallback(async () => {\n if (isPreparingDownload) return\n if (!uploadedDocxFile && !url) return\n\n setIsPreparingDownload(true)\n\n try {\n await downloadDocxFile({\n file: uploadedDocxFile?.file,\n fileName: displayFileName,\n url,\n })\n } catch (error) {\n console.error(error)\n } finally {\n setIsPreparingDownload(false)\n }\n }, [displayFileName, isPreparingDownload, uploadedDocxFile, url])\n const handleShowDocumentMarkupChange = React.useCallback(\n (checked: boolean) => {\n setShowComments(checked)\n setShowTrackedChanges(checked)\n },\n [setShowComments, setShowTrackedChanges]\n )\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(resolvedDefaultZoomScale)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [resolvedDefaultZoomScale, url])\n\n React.useEffect(() => {\n setDocumentTheme(effectiveIsDark ? \"dark\" : \"light\")\n }, [effectiveIsDark, setDocumentTheme])\n\n React.useEffect(() => {\n if (\n status.startsWith(\"Failed to load file\") ||\n status === \"Only .docx files are supported\"\n ) {\n setLoadError(status)\n setIsLoadingDocument(false)\n }\n }, [status])\n\n // Imports mutate the shared editor instance; concurrent calls (effect\n // re-runs, StrictMode double-invoke) race inside the parser and surface as\n // bogus \"Invalid DOCX ZIP\" errors, so every import is chained through here.\n const importQueueRef = React.useRef<Promise<void>>(Promise.resolve())\n\n React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n // Superseded while queued — let the newest import run instead.\n if (!isCurrent) return\n if (!uploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n setReportedPageCount(0)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n setReportedPageCount(0)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url ? await loadDocxFile(url, displayFileName) : null)\n if (!docxFile) return\n await importDocxFile(docxFile)\n\n if (isCurrent) {\n setIsLoadingDocument(false)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }\n } catch (error) {\n if (isCurrent) {\n setLoadError(\n error instanceof Error ? error.message : \"Unknown DOCX load error\"\n )\n setIsLoadingDocument(false)\n }\n }\n }\n\n importQueueRef.current = importQueueRef.current.then(load)\n\n return () => {\n isCurrent = false\n }\n }, [displayFileName, importDocxFile, uploadedDocxFile, url])\n\n React.useEffect(() => {\n if (url) {\n setUploadedDocxFile(null)\n }\n }, [url])\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n let closestPage = 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>(\n '[data-docx-page-wrapper=\"true\"][data-index]'\n )\n .forEach((page) => {\n const pageIndex = Number(page.dataset.index)\n if (!Number.isFinite(pageIndex)) return\n\n const pageRect = page.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = pageIndex + 1\n }\n })\n\n setActivePage((currentPage) =>\n currentPage === closestPage ? currentPage : closestPage\n )\n }, [pageCount])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n let frameId = 0\n const handleScroll = () => {\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener(\"scroll\", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n viewport.removeEventListener(\"scroll\", handleScroll)\n }\n }, [pageCount, updateActivePageFromViewport])\n\n const scrollToPage = React.useCallback(\n (pageNumber: number) => {\n const viewport = viewportRef.current\n const targetPageIndex = pageNumber - 1\n const page = viewport?.querySelector<HTMLElement>(\n `[data-docx-page-wrapper=\"true\"][data-index=\"${targetPageIndex}\"]`\n )\n\n setActivePage(pageNumber)\n\n if (!viewport) return\n\n if (!page) {\n const pageStridePx =\n (pageLayout.pageHeightPx + pageLayout.viewportDefaults.pageGapPx) *\n (zoomScale / 100)\n\n viewport.scrollTo({\n top: Math.max(0, targetPageIndex * pageStridePx - 24),\n behavior: \"auto\",\n })\n return\n }\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: \"auto\",\n })\n },\n [pageLayout.pageHeightPx, pageLayout.viewportDefaults.pageGapPx, zoomScale]\n )\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = \"\"\n\n if (!file) return\n\n setZoomScale(resolvedDefaultZoomScale)\n setActivePage(1)\n setReportedPageCount(0)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n return (\n <div\n className={cn(\n \"flex h-[640px] min-h-0 flex-col overflow-hidden bg-background\",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document\"\n className=\"hidden\"\n onChange={handleUpload}\n />\n {showToolbar ? (\n <DocxToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n isDark={effectiveIsDark}\n isPreparingDownload={isPreparingDownload}\n onDownload={handleDownload}\n onIsDarkChange={setNightRenderEnabled}\n onPageChange={scrollToPage}\n onShowDocumentMarkupChange={handleShowDocumentMarkupChange}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showDocumentMarkup={showDocumentMarkup}\n showDownloadButton={showDownload}\n showNightRenderToggle={shouldRenderNightMode}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n zoomScale={zoomScale}\n />\n ) : null}\n <div\n ref={viewerShellRef}\n className=\"relative flex min-h-0 flex-1 overflow-hidden bg-muted/30\"\n >\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}\n >\n <DocxThumbnailSidebarList\n activePage={activePage}\n displayFileName={displayFileName}\n isLoadingDocument={isLoadingDocument}\n onSelectPage={scrollToPage}\n pageCount={pageCount}\n sidebarOpen={sidebarOpen}\n thumbnails={thumbnails}\n />\n </DocumentViewerThumbnailSidebar>\n <ScrollArea\n className=\"min-h-0 flex-1\"\n style={{ backgroundColor: viewerBackgroundColor }}\n viewportClassName=\"px-4 py-6\"\n viewportRef={setViewportRef}\n >\n {!url && !uploadedDocxFile ? (\n <div className=\"grid h-full min-h-96 place-items-center p-6 text-center\">\n <div className=\"max-w-md rounded-lg border bg-background p-4 text-sm shadow-xs\">\n <div className=\"font-medium\">Upload a DOCX to preview</div>\n <div className=\"mt-1 text-muted-foreground\">\n Pass a DOCX URL with the <code>src</code> prop or upload a\n file.\n </div>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n className=\"mt-4\"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className=\"size-4\" />\n Upload DOCX\n </Button>\n </div>\n </div>\n ) : loadError ? (\n <div className=\"grid h-full min-h-96 place-items-center p-6 text-center\">\n <div className=\"max-w-md rounded-lg border bg-background p-4 text-sm text-destructive shadow-xs\">\n <div className=\"font-medium\">Unable to display DOCX</div>\n <div className=\"mt-1 text-muted-foreground\">{loadError}</div>\n </div>\n </div>\n ) : isLoadingDocument ? (\n loadingState\n ) : (\n <div className=\"mx-auto flex min-h-full justify-center\">\n <div\n className={cn(\n \"origin-top\",\n effectiveIsDark && \"docx-night-reader-shell\"\n )}\n style={{ zoom: zoomScale / 100 }}\n >\n <DocxEditorViewer\n editor={editor}\n mode=\"read-only\"\n showTrackedChanges={showTrackedChanges}\n showComments={showComments}\n loadingState={loadingState}\n pageBackgroundColor={effectiveIsDark ? \"#0a0a0a\" : undefined}\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={pageVirtualization}\n deferInitialPaginationPaint={false}\n onPageCountChange={handlePageCountChange}\n />\n </div>\n </div>\n )}\n </ScrollArea>\n </div>\n </div>\n )\n}\n"export function DocxViewerSource() {return (diff --git a/apps/v4/components/e-signature-docs.tsx b/apps/v4/components/e-signature-docs.tsxindex 1591e1c..e6c4b91 100644--- a/apps/v4/components/e-signature-docs.tsx+++ b/apps/v4/components/e-signature-docs.tsx@@ -703,8 +703,6 @@ export function ESignatureBlock({<PDFViewersrc={PDF_URL}defaultZoom={defaultViewerZoom}- pageWidth={PAGE_WIDTH}- pageHeight={PAGE_HEIGHT}pageClassName={() =>cn("touch-none select-none", isDrawing && "cursor-crosshair")}@@ -908,7 +906,7 @@ export function ESignatureExample() {}`const eSignatureSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n Download01Icon,\n FilePenIcon,\n Pen01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport type SignaturePad from "signature_pad"\n\nimport { cn } from "@/lib/utils"\nimport { PDFViewer } from "@/components/ui/pdf-viewer"\nimport { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"\nimport { Button } from "@/components/ui/button"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogPanel,\n DialogTitle,\n} from "@/components/ui/dialog"\nimport { ScrollArea } from "@/components/ui/scroll-area"\n\ntype BoundingBox = {\n x: number\n y: number\n width: number\n height: number\n}\n\ntype SignatureField = {\n id: string\n label: string\n page: number\n bbox: BoundingBox\n imageDataUrl?: string\n}\n\nconst PAGE_WIDTH = 612\nconst PAGE_HEIGHT = 792\nconst DEFAULT_ZOOM = 1\nconst SIGNATURE_PAD_PADDING = 8\nconst SIGNATURE_PAD_BACKGROUND_COLOR = "#ffffff"\nconst SIGNATURE_PAD_PEN_COLOR = "#000000"\nconst DEFAULT_SIGNATURE_ASPECT_RATIO = 3\n\nconst INITIAL_FIELD: SignatureField = {\n id: "signature-1",\n label: "Signature",\n page: 1,\n bbox: { x: 300, y: 504, width: 250, height: 58 },\n}\n\nfunction bboxToStyle(bbox: BoundingBox): React.CSSProperties {\n return {\n left: `${(bbox.x / PAGE_WIDTH) * 100}%`,\n top: `${(bbox.y / PAGE_HEIGHT) * 100}%`,\n width: `${(bbox.width / PAGE_WIDTH) * 100}%`,\n height: `${(bbox.height / PAGE_HEIGHT) * 100}%`,\n }\n}\n\nfunction getSignatureAspectRatio(bbox?: BoundingBox): number {\n if (!bbox || bbox.width <= 0 || bbox.height <= 0) {\n return DEFAULT_SIGNATURE_ASPECT_RATIO\n }\n\n return bbox.width / bbox.height\n}\n\nfunction getSignatureGuideSize({\n containerWidth,\n containerHeight,\n aspectRatio,\n}: {\n containerWidth: number\n containerHeight: number\n aspectRatio: number\n}): { width: number; height: number } {\n const maxWidth = Math.max(containerWidth - SIGNATURE_PAD_PADDING * 2, 1)\n const maxHeight = Math.max(containerHeight - SIGNATURE_PAD_PADDING * 2, 1)\n\n if (maxWidth / maxHeight > aspectRatio) {\n const height = maxHeight\n return {\n width: height * aspectRatio,\n height,\n }\n }\n\n const width = maxWidth\n return {\n width,\n height: width / aspectRatio,\n }\n}\n\nfunction getSignatureDataUrl(canvas: HTMLCanvasElement): string {\n return canvas.toDataURL("image/png")\n}\n\nfunction SignatureDialog({\n open,\n fieldBbox,\n initialValue,\n onOpenChange,\n onConfirm,\n}: {\n open: boolean\n fieldBbox: BoundingBox\n initialValue?: string\n onOpenChange: (open: boolean) => void\n onConfirm: (value: string) => void\n}) {\n const canvasContainerRef = React.useRef<HTMLDivElement>(null)\n const canvasRef = React.useRef<HTMLCanvasElement>(null)\n const signaturePadRef = React.useRef<SignaturePad | null>(null)\n const [isReady, setIsReady] = React.useState(false)\n const [hasSignature, setHasSignature] = React.useState(false)\n const [guideSize, setGuideSize] = React.useState<{\n width: number\n height: number\n } | null>(null)\n const signatureAspectRatio = React.useMemo(\n () => getSignatureAspectRatio(fieldBbox),\n [fieldBbox]\n )\n\n React.useEffect(() => {\n if (!open) {\n setGuideSize(null)\n return\n }\n\n let frameId = 0\n let resizeObserver: ResizeObserver | null = null\n\n const updateGuideSize = (container?: HTMLDivElement | null) => {\n const currentContainer = container ?? canvasContainerRef.current\n if (\n !currentContainer ||\n currentContainer.clientWidth <= 0 ||\n currentContainer.clientHeight <= 0\n ) {\n return false\n }\n\n const nextSize = getSignatureGuideSize({\n containerWidth: currentContainer.clientWidth,\n containerHeight: currentContainer.clientHeight,\n aspectRatio: signatureAspectRatio,\n })\n\n setGuideSize((previousSize) => {\n if (\n previousSize &&\n Math.abs(previousSize.width - nextSize.width) < 0.5 &&\n Math.abs(previousSize.height - nextSize.height) < 0.5\n ) {\n return previousSize\n }\n\n return nextSize\n })\n\n return true\n }\n\n const connect = () => {\n const container = canvasContainerRef.current\n if (!updateGuideSize(container)) {\n frameId = window.requestAnimationFrame(connect)\n return\n }\n\n if (container) {\n resizeObserver = new ResizeObserver(() => {\n updateGuideSize(container)\n })\n resizeObserver.observe(container)\n }\n }\n\n connect()\n\n return () => {\n window.cancelAnimationFrame(frameId)\n resizeObserver?.disconnect()\n }\n }, [open, signatureAspectRatio])\n\n React.useEffect(() => {\n if (!open || !guideSize || guideSize.width <= 1 || guideSize.height <= 1) {\n signaturePadRef.current?.off()\n signaturePadRef.current = null\n setIsReady(false)\n if (!open) {\n setHasSignature(false)\n }\n return\n }\n\n let cancelled = false\n let resizeObserver: ResizeObserver | null = null\n\n const syncCanvasSize = (canvas: HTMLCanvasElement) => {\n const width = Math.max(canvas.offsetWidth, 1)\n const height = Math.max(canvas.offsetHeight, 1)\n const ratio = Math.max(window.devicePixelRatio || 1, 1)\n\n canvas.style.width = `${width}px`\n canvas.style.height = `${height}px`\n canvas.width = Math.floor(width * ratio)\n canvas.height = Math.floor(height * ratio)\n const context = canvas.getContext("2d")\n context?.setTransform(1, 0, 0, 1, 0, 0)\n context?.scale(ratio, ratio)\n\n return { width, height, ratio }\n }\n\n const initialize = async () => {\n const canvas = canvasRef.current\n if (!canvas) return\n\n const { default: SignaturePadConstructor } = await import("signature_pad")\n if (cancelled) return\n\n const signaturePad = new SignaturePadConstructor(canvas, {\n minWidth: 1,\n maxWidth: 2,\n penColor: SIGNATURE_PAD_PEN_COLOR,\n })\n\n signaturePadRef.current = signaturePad\n\n const loadSignature = async (dataUrl?: string) => {\n const size = syncCanvasSize(canvas)\n\n if (dataUrl) {\n await signaturePad.fromDataURL(dataUrl, size)\n setHasSignature(true)\n return\n }\n\n signaturePad.clear()\n setHasSignature(false)\n }\n\n await loadSignature(initialValue)\n if (cancelled) return\n\n signaturePad.addEventListener("endStroke", () => {\n setHasSignature(true)\n })\n\n resizeObserver = new ResizeObserver(() => {\n const currentCanvas = canvasRef.current\n const currentSignaturePad = signaturePadRef.current\n if (!currentCanvas || !currentSignaturePad) return\n\n const previousSignature = currentSignaturePad.isEmpty()\n ? undefined\n : currentSignaturePad.toDataURL("image/png")\n void loadSignature(previousSignature)\n })\n resizeObserver.observe(canvas)\n setIsReady(true)\n }\n\n const animationFrame = window.requestAnimationFrame(() => {\n void initialize()\n })\n\n return () => {\n cancelled = true\n window.cancelAnimationFrame(animationFrame)\n resizeObserver?.disconnect()\n signaturePadRef.current?.off()\n signaturePadRef.current = null\n setIsReady(false)\n }\n }, [open, guideSize, initialValue])\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className="max-w-xl">\n <DialogHeader>\n <DialogTitle>Add signature</DialogTitle>\n <DialogDescription>\n Draw a signature to place it into the selected PDF field.\n </DialogDescription>\n </DialogHeader>\n <DialogPanel>\n <div className="rounded-xl border bg-white p-3 text-slate-950 shadow-xs dark:bg-white dark:text-slate-950">\n <div\n ref={canvasContainerRef}\n className="flex h-56 w-full items-center justify-center overflow-hidden rounded-lg bg-white p-2 dark:bg-white"\n >\n <div\n className={cn(\n "relative overflow-hidden rounded-[3px] border border-dashed border-blue-500/70 bg-white",\n isReady ? "cursor-crosshair" : "cursor-wait"\n )}\n style={{\n width: guideSize ? `${guideSize.width}px` : undefined,\n height: guideSize ? `${guideSize.height}px` : undefined,\n opacity: guideSize ? 1 : 0,\n backgroundColor: SIGNATURE_PAD_BACKGROUND_COLOR,\n }}\n >\n <canvas\n ref={canvasRef}\n className={cn(\n "absolute inset-0 size-full touch-none",\n !isReady && "pointer-events-none"\n )}\n style={{\n backgroundColor: SIGNATURE_PAD_BACKGROUND_COLOR,\n touchAction: "none",\n }}\n />\n </div>\n </div>\n </div>\n </DialogPanel>\n <DialogFooter className="sm:justify-between">\n <Button\n type="button"\n variant="outline"\n disabled={!isReady}\n onClick={() => {\n signaturePadRef.current?.clear()\n setHasSignature(false)\n }}\n >\n Clear\n </Button>\n <div className="flex flex-col-reverse gap-2 sm:flex-row">\n <Button\n type="button"\n variant="outline"\n onClick={() => onOpenChange(false)}\n >\n Cancel\n </Button>\n <Button\n type="button"\n disabled={!isReady || !hasSignature}\n onClick={() => {\n const canvas = canvasRef.current\n if (!canvas) return\n\n onConfirm(getSignatureDataUrl(canvas))\n onOpenChange(false)\n }}\n >\n Confirm\n </Button>\n </div>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\nfunction SignatureFieldOverlay({\n field,\n onOpen,\n}: {\n field: SignatureField\n onOpen: () => void\n}) {\n return (\n <button\n type="button"\n className={cn(\n "absolute z-20 overflow-hidden rounded-[3px] border border-blue-500/70 transition-colors focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",\n field.imageDataUrl\n ? "bg-transparent shadow-none hover:bg-blue-500/5"\n : "bg-blue-500/10 hover:bg-blue-500/15"\n )}\n style={bboxToStyle(field.bbox)}\n onClick={onOpen}\n >\n {field.imageDataUrl ? (\n <img\n src={field.imageDataUrl}\n alt=""\n className="size-full object-fill"\n draggable={false}\n />\n ) : (\n <span className="flex size-full items-center justify-center gap-1.5 px-2 text-[11px] font-medium text-blue-700 dark:text-blue-300">\n <HugeiconsIcon icon={Pen01Icon} className="size-3.5" />\n Signature\n </span>\n )}\n </button>\n )\n}\n\nasync function downloadSignedPdf({\n file,\n field,\n}: {\n file: string\n field: SignatureField\n}) {\n const { PDFDocument } = await import("pdf-lib")\n const existingPdfBytes = await fetch(file).then((response) =>\n response.arrayBuffer()\n )\n const pdfDocument = await PDFDocument.load(existingPdfBytes)\n const page = pdfDocument.getPage(field.page - 1)\n\n if (field.imageDataUrl) {\n const signatureImage = await pdfDocument.embedPng(field.imageDataUrl)\n const { width: pageWidth, height: pageHeight } = page.getSize()\n const scaleX = pageWidth / PAGE_WIDTH\n const scaleY = pageHeight / PAGE_HEIGHT\n const fieldWidth = field.bbox.width * scaleX\n const fieldHeight = field.bbox.height * scaleY\n const fieldX = field.bbox.x * scaleX\n const fieldY = pageHeight - (field.bbox.y + field.bbox.height) * scaleY\n\n page.drawImage(signatureImage, {\n x: fieldX,\n y: fieldY,\n width: fieldWidth,\n height: fieldHeight,\n })\n }\n\n const bytes = await pdfDocument.save()\n const blob = new Blob([new Uint8Array(bytes)], { type: "application/pdf" })\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n anchor.href = url\n anchor.download = "signed-document.pdf"\n anchor.click()\n URL.revokeObjectURL(url)\n}\n\nfunction SignatureFieldsPanel({\n field,\n className,\n canExport,\n isDownloading,\n onSign,\n onClear,\n onDownload,\n}: {\n field: SignatureField\n className?: string\n canExport: boolean\n isDownloading: boolean\n onSign: () => void\n onClear: () => void\n onDownload: () => void\n}) {\n return (\n <aside className={cn("flex min-h-0 flex-col bg-background", className)}>\n <ScrollArea className="min-h-0 flex-1" scrollFade>\n <div className="space-y-4 p-4">\n <div className="space-y-1">\n <h3 className="text-sm font-medium">Signature fields</h3>\n <p className="text-xs text-muted-foreground">\n Review fields, collect signatures, and export a signed PDF.\n </p>\n </div>\n <div className="rounded-lg border bg-background p-3">\n <div className="flex items-start gap-3">\n <div className="grid size-9 shrink-0 place-items-center rounded-md bg-blue-500/10 text-blue-600 dark:text-blue-300">\n <HugeiconsIcon icon={FilePenIcon} className="size-4" />\n </div>\n <div className="min-w-0 flex-1">\n <div className="flex items-center justify-between gap-2">\n <div className="text-sm font-medium">{field.label}</div>\n <div\n className={cn(\n "rounded-full px-2 py-0.5 text-xs",\n field.imageDataUrl\n ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-300"\n : "bg-muted text-muted-foreground"\n )}\n >\n {field.imageDataUrl ? "Signed" : "Unsigned"}\n </div>\n </div>\n <div className="mt-2 text-xs text-muted-foreground">\n {Math.round(field.bbox.width)} x{" "}\n {Math.round(field.bbox.height)} on page {field.page}\n </div>\n <div className="mt-3 flex gap-2">\n <Button\n type="button"\n size="sm"\n variant={field.imageDataUrl ? "outline" : "default"}\n className="flex-1"\n onClick={onSign}\n >\n <HugeiconsIcon icon={Pen01Icon} className="size-4" />\n {field.imageDataUrl ? "Edit" : "Sign"}\n </Button>\n {field.imageDataUrl ? (\n <Button\n type="button"\n size="sm"\n variant="outline"\n onClick={onClear}\n >\n Clear\n </Button>\n ) : null}\n </div>\n </div>\n </div>\n </div>\n <Button\n type="button"\n className="w-full"\n disabled={!canExport || isDownloading}\n onClick={onDownload}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n {isDownloading ? "Exporting..." : "Export signed PDF"}\n </Button>\n </div>\n </ScrollArea>\n </aside>\n )\n}\n\nexport function ESignatureBlock({ file }: { file?: string }) {\n const [field, setField] = React.useState<SignatureField>(INITIAL_FIELD)\n const [dialogOpen, setDialogOpen] = React.useState(false)\n const [isDownloading, setIsDownloading] = React.useState(false)\n\n const handleDownload = React.useCallback(async () => {\n if (!file || !field.imageDataUrl) return\n\n setIsDownloading(true)\n try {\n await downloadSignedPdf({ file, field })\n } finally {\n setIsDownloading(false)\n }\n }, [field, file])\n\n return (\n <>\n <PdfBlockResizableShell\n autoSaveId="pdf-block-e-signature"\n left={\n <PDFViewer\n src={file}\n defaultZoom={DEFAULT_ZOOM}\n pageWidth={PAGE_WIDTH}\n pageHeight={PAGE_HEIGHT}\n toolbarActions={\n <Button\n type="button"\n size="sm"\n variant="outline"\n disabled={!file || !field.imageDataUrl || isDownloading}\n onClick={handleDownload}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n Download\n </Button>\n }\n renderPageOverlay={({ pageNumber }) =>\n pageNumber === field.page ? (\n <SignatureFieldOverlay\n field={field}\n onOpen={() => setDialogOpen(true)}\n />\n ) : null\n }\n />\n }\n right={\n <SignatureFieldsPanel\n field={field}\n canExport={Boolean(file && field.imageDataUrl)}\n isDownloading={isDownloading}\n onSign={() => setDialogOpen(true)}\n onClear={() =>\n setField((previousField) => ({\n ...previousField,\n imageDataUrl: undefined,\n }))\n }\n onDownload={handleDownload}\n />\n }\n />\n <SignatureDialog\n open={dialogOpen}\n fieldBbox={field.bbox}\n initialValue={field.imageDataUrl}\n onOpenChange={setDialogOpen}\n onConfirm={(imageDataUrl) => {\n setField((previousField) => ({ ...previousField, imageDataUrl }))\n }}\n />\n </>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport {\n Download01Icon,\n FilePenIcon,\n Pen01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport type SignaturePad from "signature_pad"\n\nimport { cn } from "@/lib/utils"\nimport { PDFViewer } from "@/components/ui/pdf-viewer"\nimport { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"\nimport { Button } from "@/components/ui/button"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogPanel,\n DialogTitle,\n} from "@/components/ui/dialog"\nimport { ScrollArea } from "@/components/ui/scroll-area"\n\ntype BoundingBox = {\n x: number\n y: number\n width: number\n height: number\n}\n\ntype SignatureField = {\n id: string\n label: string\n page: number\n bbox: BoundingBox\n imageDataUrl?: string\n}\n\nconst PAGE_WIDTH = 612\nconst PAGE_HEIGHT = 792\nconst DEFAULT_ZOOM = 1\nconst SIGNATURE_PAD_PADDING = 8\nconst SIGNATURE_PAD_BACKGROUND_COLOR = "#ffffff"\nconst SIGNATURE_PAD_PEN_COLOR = "#000000"\nconst DEFAULT_SIGNATURE_ASPECT_RATIO = 3\n\nconst INITIAL_FIELD: SignatureField = {\n id: "signature-1",\n label: "Signature",\n page: 1,\n bbox: { x: 300, y: 504, width: 250, height: 58 },\n}\n\nfunction bboxToStyle(bbox: BoundingBox): React.CSSProperties {\n return {\n left: `${(bbox.x / PAGE_WIDTH) * 100}%`,\n top: `${(bbox.y / PAGE_HEIGHT) * 100}%`,\n width: `${(bbox.width / PAGE_WIDTH) * 100}%`,\n height: `${(bbox.height / PAGE_HEIGHT) * 100}%`,\n }\n}\n\nfunction getSignatureAspectRatio(bbox?: BoundingBox): number {\n if (!bbox || bbox.width <= 0 || bbox.height <= 0) {\n return DEFAULT_SIGNATURE_ASPECT_RATIO\n }\n\n return bbox.width / bbox.height\n}\n\nfunction getSignatureGuideSize({\n containerWidth,\n containerHeight,\n aspectRatio,\n}: {\n containerWidth: number\n containerHeight: number\n aspectRatio: number\n}): { width: number; height: number } {\n const maxWidth = Math.max(containerWidth - SIGNATURE_PAD_PADDING * 2, 1)\n const maxHeight = Math.max(containerHeight - SIGNATURE_PAD_PADDING * 2, 1)\n\n if (maxWidth / maxHeight > aspectRatio) {\n const height = maxHeight\n return {\n width: height * aspectRatio,\n height,\n }\n }\n\n const width = maxWidth\n return {\n width,\n height: width / aspectRatio,\n }\n}\n\nfunction getSignatureDataUrl(canvas: HTMLCanvasElement): string {\n return canvas.toDataURL("image/png")\n}\n\nfunction SignatureDialog({\n open,\n fieldBbox,\n initialValue,\n onOpenChange,\n onConfirm,\n}: {\n open: boolean\n fieldBbox: BoundingBox\n initialValue?: string\n onOpenChange: (open: boolean) => void\n onConfirm: (value: string) => void\n}) {\n const canvasContainerRef = React.useRef<HTMLDivElement>(null)\n const canvasRef = React.useRef<HTMLCanvasElement>(null)\n const signaturePadRef = React.useRef<SignaturePad | null>(null)\n const [isReady, setIsReady] = React.useState(false)\n const [hasSignature, setHasSignature] = React.useState(false)\n const [guideSize, setGuideSize] = React.useState<{\n width: number\n height: number\n } | null>(null)\n const signatureAspectRatio = React.useMemo(\n () => getSignatureAspectRatio(fieldBbox),\n [fieldBbox]\n )\n\n React.useEffect(() => {\n if (!open) {\n setGuideSize(null)\n return\n }\n\n let frameId = 0\n let resizeObserver: ResizeObserver | null = null\n\n const updateGuideSize = (container?: HTMLDivElement | null) => {\n const currentContainer = container ?? canvasContainerRef.current\n if (\n !currentContainer ||\n currentContainer.clientWidth <= 0 ||\n currentContainer.clientHeight <= 0\n ) {\n return false\n }\n\n const nextSize = getSignatureGuideSize({\n containerWidth: currentContainer.clientWidth,\n containerHeight: currentContainer.clientHeight,\n aspectRatio: signatureAspectRatio,\n })\n\n setGuideSize((previousSize) => {\n if (\n previousSize &&\n Math.abs(previousSize.width - nextSize.width) < 0.5 &&\n Math.abs(previousSize.height - nextSize.height) < 0.5\n ) {\n return previousSize\n }\n\n return nextSize\n })\n\n return true\n }\n\n const connect = () => {\n const container = canvasContainerRef.current\n if (!updateGuideSize(container)) {\n frameId = window.requestAnimationFrame(connect)\n return\n }\n\n if (container) {\n resizeObserver = new ResizeObserver(() => {\n updateGuideSize(container)\n })\n resizeObserver.observe(container)\n }\n }\n\n connect()\n\n return () => {\n window.cancelAnimationFrame(frameId)\n resizeObserver?.disconnect()\n }\n }, [open, signatureAspectRatio])\n\n React.useEffect(() => {\n if (!open || !guideSize || guideSize.width <= 1 || guideSize.height <= 1) {\n signaturePadRef.current?.off()\n signaturePadRef.current = null\n setIsReady(false)\n if (!open) {\n setHasSignature(false)\n }\n return\n }\n\n let cancelled = false\n let resizeObserver: ResizeObserver | null = null\n\n const syncCanvasSize = (canvas: HTMLCanvasElement) => {\n const width = Math.max(canvas.offsetWidth, 1)\n const height = Math.max(canvas.offsetHeight, 1)\n const ratio = Math.max(window.devicePixelRatio || 1, 1)\n\n canvas.style.width = `${width}px`\n canvas.style.height = `${height}px`\n canvas.width = Math.floor(width * ratio)\n canvas.height = Math.floor(height * ratio)\n const context = canvas.getContext("2d")\n context?.setTransform(1, 0, 0, 1, 0, 0)\n context?.scale(ratio, ratio)\n\n return { width, height, ratio }\n }\n\n const initialize = async () => {\n const canvas = canvasRef.current\n if (!canvas) return\n\n const { default: SignaturePadConstructor } = await import("signature_pad")\n if (cancelled) return\n\n const signaturePad = new SignaturePadConstructor(canvas, {\n minWidth: 1,\n maxWidth: 2,\n penColor: SIGNATURE_PAD_PEN_COLOR,\n })\n\n signaturePadRef.current = signaturePad\n\n const loadSignature = async (dataUrl?: string) => {\n const size = syncCanvasSize(canvas)\n\n if (dataUrl) {\n await signaturePad.fromDataURL(dataUrl, size)\n setHasSignature(true)\n return\n }\n\n signaturePad.clear()\n setHasSignature(false)\n }\n\n await loadSignature(initialValue)\n if (cancelled) return\n\n signaturePad.addEventListener("endStroke", () => {\n setHasSignature(true)\n })\n\n resizeObserver = new ResizeObserver(() => {\n const currentCanvas = canvasRef.current\n const currentSignaturePad = signaturePadRef.current\n if (!currentCanvas || !currentSignaturePad) return\n\n const previousSignature = currentSignaturePad.isEmpty()\n ? undefined\n : currentSignaturePad.toDataURL("image/png")\n void loadSignature(previousSignature)\n })\n resizeObserver.observe(canvas)\n setIsReady(true)\n }\n\n const animationFrame = window.requestAnimationFrame(() => {\n void initialize()\n })\n\n return () => {\n cancelled = true\n window.cancelAnimationFrame(animationFrame)\n resizeObserver?.disconnect()\n signaturePadRef.current?.off()\n signaturePadRef.current = null\n setIsReady(false)\n }\n }, [open, guideSize, initialValue])\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className="max-w-xl">\n <DialogHeader>\n <DialogTitle>Add signature</DialogTitle>\n <DialogDescription>\n Draw a signature to place it into the selected PDF field.\n </DialogDescription>\n </DialogHeader>\n <DialogPanel>\n <div className="rounded-xl border bg-white p-3 text-slate-950 shadow-xs dark:bg-white dark:text-slate-950">\n <div\n ref={canvasContainerRef}\n className="flex h-56 w-full items-center justify-center overflow-hidden rounded-lg bg-white p-2 dark:bg-white"\n >\n <div\n className={cn(\n "relative overflow-hidden rounded-[3px] border border-dashed border-blue-500/70 bg-white",\n isReady ? "cursor-crosshair" : "cursor-wait"\n )}\n style={{\n width: guideSize ? `${guideSize.width}px` : undefined,\n height: guideSize ? `${guideSize.height}px` : undefined,\n opacity: guideSize ? 1 : 0,\n backgroundColor: SIGNATURE_PAD_BACKGROUND_COLOR,\n }}\n >\n <canvas\n ref={canvasRef}\n className={cn(\n "absolute inset-0 size-full touch-none",\n !isReady && "pointer-events-none"\n )}\n style={{\n backgroundColor: SIGNATURE_PAD_BACKGROUND_COLOR,\n touchAction: "none",\n }}\n />\n </div>\n </div>\n </div>\n </DialogPanel>\n <DialogFooter className="sm:justify-between">\n <Button\n type="button"\n variant="outline"\n disabled={!isReady}\n onClick={() => {\n signaturePadRef.current?.clear()\n setHasSignature(false)\n }}\n >\n Clear\n </Button>\n <div className="flex flex-col-reverse gap-2 sm:flex-row">\n <Button\n type="button"\n variant="outline"\n onClick={() => onOpenChange(false)}\n >\n Cancel\n </Button>\n <Button\n type="button"\n disabled={!isReady || !hasSignature}\n onClick={() => {\n const canvas = canvasRef.current\n if (!canvas) return\n\n onConfirm(getSignatureDataUrl(canvas))\n onOpenChange(false)\n }}\n >\n Confirm\n </Button>\n </div>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\nfunction SignatureFieldOverlay({\n field,\n onOpen,\n}: {\n field: SignatureField\n onOpen: () => void\n}) {\n return (\n <button\n type="button"\n className={cn(\n "absolute z-20 overflow-hidden rounded-[3px] border border-blue-500/70 transition-colors focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",\n field.imageDataUrl\n ? "bg-transparent shadow-none hover:bg-blue-500/5"\n : "bg-blue-500/10 hover:bg-blue-500/15"\n )}\n style={bboxToStyle(field.bbox)}\n onClick={onOpen}\n >\n {field.imageDataUrl ? (\n <img\n src={field.imageDataUrl}\n alt=""\n className="size-full object-fill"\n draggable={false}\n />\n ) : (\n <span className="flex size-full items-center justify-center gap-1.5 px-2 text-[11px] font-medium text-blue-700 dark:text-blue-300">\n <HugeiconsIcon icon={Pen01Icon} className="size-3.5" />\n Signature\n </span>\n )}\n </button>\n )\n}\n\nasync function downloadSignedPdf({\n file,\n field,\n}: {\n file: string\n field: SignatureField\n}) {\n const { PDFDocument } = await import("pdf-lib")\n const existingPdfBytes = await fetch(file).then((response) =>\n response.arrayBuffer()\n )\n const pdfDocument = await PDFDocument.load(existingPdfBytes)\n const page = pdfDocument.getPage(field.page - 1)\n\n if (field.imageDataUrl) {\n const signatureImage = await pdfDocument.embedPng(field.imageDataUrl)\n const { width: pageWidth, height: pageHeight } = page.getSize()\n const scaleX = pageWidth / PAGE_WIDTH\n const scaleY = pageHeight / PAGE_HEIGHT\n const fieldWidth = field.bbox.width * scaleX\n const fieldHeight = field.bbox.height * scaleY\n const fieldX = field.bbox.x * scaleX\n const fieldY = pageHeight - (field.bbox.y + field.bbox.height) * scaleY\n\n page.drawImage(signatureImage, {\n x: fieldX,\n y: fieldY,\n width: fieldWidth,\n height: fieldHeight,\n })\n }\n\n const bytes = await pdfDocument.save()\n const blob = new Blob([new Uint8Array(bytes)], { type: "application/pdf" })\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n anchor.href = url\n anchor.download = "signed-document.pdf"\n anchor.click()\n URL.revokeObjectURL(url)\n}\n\nfunction SignatureFieldsPanel({\n field,\n className,\n canExport,\n isDownloading,\n onSign,\n onClear,\n onDownload,\n}: {\n field: SignatureField\n className?: string\n canExport: boolean\n isDownloading: boolean\n onSign: () => void\n onClear: () => void\n onDownload: () => void\n}) {\n return (\n <aside className={cn("flex min-h-0 flex-col bg-background", className)}>\n <ScrollArea className="min-h-0 flex-1" scrollFade>\n <div className="space-y-4 p-4">\n <div className="space-y-1">\n <h3 className="text-sm font-medium">Signature fields</h3>\n <p className="text-xs text-muted-foreground">\n Review fields, collect signatures, and export a signed PDF.\n </p>\n </div>\n <div className="rounded-lg border bg-background p-3">\n <div className="flex items-start gap-3">\n <div className="grid size-9 shrink-0 place-items-center rounded-md bg-blue-500/10 text-blue-600 dark:text-blue-300">\n <HugeiconsIcon icon={FilePenIcon} className="size-4" />\n </div>\n <div className="min-w-0 flex-1">\n <div className="flex items-center justify-between gap-2">\n <div className="text-sm font-medium">{field.label}</div>\n <div\n className={cn(\n "rounded-full px-2 py-0.5 text-xs",\n field.imageDataUrl\n ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-300"\n : "bg-muted text-muted-foreground"\n )}\n >\n {field.imageDataUrl ? "Signed" : "Unsigned"}\n </div>\n </div>\n <div className="mt-2 text-xs text-muted-foreground">\n {Math.round(field.bbox.width)} x{" "}\n {Math.round(field.bbox.height)} on page {field.page}\n </div>\n <div className="mt-3 flex gap-2">\n <Button\n type="button"\n size="sm"\n variant={field.imageDataUrl ? "outline" : "default"}\n className="flex-1"\n onClick={onSign}\n >\n <HugeiconsIcon icon={Pen01Icon} className="size-4" />\n {field.imageDataUrl ? "Edit" : "Sign"}\n </Button>\n {field.imageDataUrl ? (\n <Button\n type="button"\n size="sm"\n variant="outline"\n onClick={onClear}\n >\n Clear\n </Button>\n ) : null}\n </div>\n </div>\n </div>\n </div>\n <Button\n type="button"\n className="w-full"\n disabled={!canExport || isDownloading}\n onClick={onDownload}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n {isDownloading ? "Exporting..." : "Export signed PDF"}\n </Button>\n </div>\n </ScrollArea>\n </aside>\n )\n}\n\nexport function ESignatureBlock({ file }: { file?: string }) {\n const [field, setField] = React.useState<SignatureField>(INITIAL_FIELD)\n const [dialogOpen, setDialogOpen] = React.useState(false)\n const [isDownloading, setIsDownloading] = React.useState(false)\n\n const handleDownload = React.useCallback(async () => {\n if (!file || !field.imageDataUrl) return\n\n setIsDownloading(true)\n try {\n await downloadSignedPdf({ file, field })\n } finally {\n setIsDownloading(false)\n }\n }, [field, file])\n\n return (\n <>\n <PdfBlockResizableShell\n autoSaveId="pdf-block-e-signature"\n left={\n <PDFViewer\n src={file}\n defaultZoom={DEFAULT_ZOOM}\n toolbarActions={\n <Button\n type="button"\n size="sm"\n variant="outline"\n disabled={!file || !field.imageDataUrl || isDownloading}\n onClick={handleDownload}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n Download\n </Button>\n }\n renderPageOverlay={({ pageNumber }) =>\n pageNumber === field.page ? (\n <SignatureFieldOverlay\n field={field}\n onOpen={() => setDialogOpen(true)}\n />\n ) : null\n }\n />\n }\n right={\n <SignatureFieldsPanel\n field={field}\n canExport={Boolean(file && field.imageDataUrl)}\n isDownloading={isDownloading}\n onSign={() => setDialogOpen(true)}\n onClear={() =>\n setField((previousField) => ({\n ...previousField,\n imageDataUrl: undefined,\n }))\n }\n onDownload={handleDownload}\n />\n }\n />\n <SignatureDialog\n open={dialogOpen}\n fieldBbox={field.bbox}\n initialValue={field.imageDataUrl}\n onOpenChange={setDialogOpen}\n onConfirm={(imageDataUrl) => {\n setField((previousField) => ({ ...previousField, imageDataUrl }))\n }}\n />\n </>\n )\n}\n'export function ESignatureSource() {return (diff --git a/apps/v4/components/file-system-source-code.tsx b/apps/v4/components/file-system-source-code.tsxindex d42bc32..5af21e4 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 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 file={url}\n className={cn(\n "h-full",\n isDialog && "min-h-0 overflow-hidden rounded-2xl"\n )}\n downloadFileName={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 className="h-full min-h-0"\n rounded={isDialog}\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 className="h-full min-h-0"\n rounded={isDialog}\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 <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'export function FileSystemSourceCode() {return (diff --git a/apps/v4/components/pdf-viewer-source-code.tsx b/apps/v4/components/pdf-viewer-source-code.tsxindex f8b2814..985fb4f 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 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 { 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 /** Retained for API compatibility; page sizes come from the document. */\n pageWidth?: number\n /** Retained for API compatibility; page sizes come from the document. */\n pageHeight?: number\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)\"\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 <PDFViewerUploadControl onUploadFile={onUploadFile} />\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 PDFViewerUploadControl({\n onUploadFile,\n}: {\n onUploadFile: (file: File) => void\n}) {\n const inputRef = React.useRef<HTMLInputElement>(null)\n\n return (\n <>\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 <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Upload PDF\"\n onClick={() => inputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className=\"size-4\" />\n </Button>\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=\"absolute right-0 left-0 flex justify-center\"\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-none select-none hover:bg-sidebar-accent\",\n isActive || isSelected\n ? \"bg-sidebar-accent text-foreground\"\n : \"text-muted-foreground\"\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=\"px-4\"\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 {showDownload ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n <ToolbarTooltip label=\"Download PDF\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Download PDF\"\n disabled={downloadDisabled}\n onClick={handleDownload}\n >\n {isPreparingDownload ? (\n <Spinner className=\"size-4\" />\n ) : (\n <HugeiconsIcon\n icon={Download01Icon}\n className=\"size-4\"\n />\n )}\n </Button>\n </ToolbarTooltip>\n </>\n ) : null}\n {showUpload ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n <ToolbarTooltip label=\"Upload PDF\">\n <PDFViewerUploadControl onUploadFile={handleUpload} />\n </ToolbarTooltip>\n </>\n ) : null}\n {toolbarActions ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n {toolbarActions}\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 pageWidth: _pageWidth,\n pageHeight: _pageHeight,\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\n sidebarInline\n sidebarOpen={false}\n />\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 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)"\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="absolute right-0 left-0 flex justify-center"\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-none select-none hover:bg-sidebar-accent",\n isActive || isSelected\n ? "bg-sidebar-accent text-foreground"\n : "text-muted-foreground"\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="px-4"\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'export function PdfViewerSourceCode() {return (diff --git a/apps/v4/components/ui/csv-viewer.tsx b/apps/v4/components/ui/csv-viewer.tsxindex 66edead..1b12f0f 100644--- a/apps/v4/components/ui/csv-viewer.tsx+++ b/apps/v4/components/ui/csv-viewer.tsx@@ -21,7 +21,9 @@ import "@glideapps/glide-data-grid/dist/index.css"import {ArrowLeft01Icon,ArrowRight01Icon,+ Download01Icon,MinusSignCircleIcon,+ MoreHorizontalIcon,PlusSignCircleIcon,Search01Icon,Upload01Icon,@@ -31,6 +33,12 @@ import Papa from "papaparse"import { cn } from "@/lib/utils"import { Button } from "@/components/ui/button"+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu"import { Input } from "@/components/ui/input"import {Popover,@@ -238,6 +246,68 @@ function parseDelimitedText(text: string): {}}+function ensureCsvExtension(fileName: string) {+ const lowerFileName = fileName.toLowerCase()+ return lowerFileName.endsWith(".csv") || lowerFileName.endsWith(".tsv")+ ? fileName+ : `${fileName}.csv`+}++function downloadTextFile(text: string, fileName: string, type: string) {+ const url = URL.createObjectURL(new Blob([text], { type }))+ const anchor = document.createElement("a")++ anchor.href = url+ anchor.download = fileName+ anchor.rel = "noopener"+ document.body.append(anchor)+ anchor.click()+ anchor.remove()+ window.setTimeout(() => URL.revokeObjectURL(url), 0)+}++function CsvFileActionsMenu({+ downloadDisabled,+ isPending,+ onDownload,+ onUploadClick,+}: {+ downloadDisabled: boolean+ isPending: boolean+ onDownload: () => void+ onUploadClick: () => void+}) {+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Open CSV actions"+ disabled={isPending}+ >+ <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-40">+ <DropdownMenuItem disabled={downloadDisabled} onClick={onDownload}>+ <HugeiconsIcon icon={Download01Icon} className="size-4" />+ Download+ </DropdownMenuItem>+ <DropdownMenuItem disabled={isPending} onClick={onUploadClick}>+ {isPending ? (+ <Spinner className="size-4" />+ ) : (+ <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ )}+ Upload+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )+}+function ToolbarTooltip({label,children,@@ -442,7 +512,9 @@ function CsvSearchPopover({<div className="truncate">{searchResults.length ? (<>- <span className="text-primary">{activeResultIndex + 1}</span>+ <span className="text-primary">+ {activeResultIndex + 1}+ </span>{` / ${searchResults.length}`}</>) : (@@ -451,7 +523,8 @@ function CsvSearchPopover({</div>{activeResult ? (<div className="mt-0.5 truncate">- {activeResult.columnTitle}!{cellAddressToA1(activeResult.col, activeResult.row)}+ {activeResult.columnTitle}!+ {cellAddressToA1(activeResult.col, activeResult.row)}</div>) : null}</div>@@ -536,6 +609,9 @@ export function CsvViewer({ className, data, search = false }: CsvViewerProps) {const [parsed, setParsed] = React.useState(() =>data ? parseDelimitedText(data) : { headers: [], rows: [], error: null })+ const [uploadedFileName, setUploadedFileName] = React.useState<string | null>(+ null+ )const [isPending, setIsPending] = React.useState(false)const [dataRevision, setDataRevision] = React.useState(0)@@ -555,6 +631,7 @@ export function CsvViewer({ className, data, search = false }: CsvViewerProps) {React.useEffect(() => {if (data) {setParsed(parseDelimitedText(data))+ setUploadedFileName(null)setDataRevision((revision) => revision + 1)}}, [data])@@ -651,6 +728,7 @@ export function CsvViewer({ className, data, search = false }: CsvViewerProps) {try {const text = await file.text()setParsed(parseDelimitedText(text))+ setUploadedFileName(file.name)setDataRevision((revision) => revision + 1)} catch (error) {setParsed({@@ -675,6 +753,19 @@ export function CsvViewer({ className, data, search = false }: CsvViewerProps) {setZoom(ZOOM_OPTIONS[nextIndex])}+ function handleDownload() {+ const text = Papa.unparse({+ fields: parsed.headers,+ data: parsed.rows,+ })++ downloadTextFile(+ text,+ ensureCsvExtension(uploadedFileName ?? "data.csv"),+ "text/csv;charset=utf-8"+ )+ }+return (<divclassName={cn(@@ -761,17 +852,16 @@ export function CsvViewer({ className, data, search = false }: CsvViewerProps) {className="hidden"onChange={handleUpload}/>- <ToolbarTooltip label="Upload CSV">- <Button- variant="ghost"- size="icon-sm"- aria-label="Upload CSV"- loading={isPending}- onClick={() => inputRef.current?.click()}- >- <HugeiconsIcon icon={Upload01Icon} className="size-4" />- </Button>- </ToolbarTooltip>+ <CsvFileActionsMenu+ downloadDisabled={+ Boolean(parsed.error) ||+ isPending ||+ (parsed.headers.length === 0 && parsed.rows.length === 0)+ }+ isPending={isPending}+ onDownload={handleDownload}+ onUploadClick={() => inputRef.current?.click()}+ /></div></TooltipProvider></div>diff --git a/apps/v4/components/ui/docx-editor.tsx b/apps/v4/components/ui/docx-editor.tsxindex a057124..83c2950 100644--- a/apps/v4/components/ui/docx-editor.tsx+++ b/apps/v4/components/ui/docx-editor.tsx@@ -1625,6 +1625,8 @@ function DocxEditorContent({const fileInputRef = React.useRef<HTMLInputElement>(null)const imageInputRef = React.useRef<HTMLInputElement>(null)const viewportRef = React.useRef<HTMLDivElement | null>(null)+ const [viewportElement, setViewportElement] =+ React.useState<HTMLDivElement | null>(null)const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()const [uploadedDocxFile, setUploadedDocxFile] =React.useState<UploadedDocxFile | null>(null)@@ -1658,6 +1660,7 @@ function DocxEditorContent({[displayFileName, initialDocumentTheme])const editor = useDocxEditor(editorOptions)+ const { layout: pageLayout } = useDocxPageLayout(editor)const { importDocxFile, setDocumentTheme, status } = editorconst [reportedPageCount, setReportedPageCount] = React.useState(0)const thumbnailEditor = React.useMemo<DocxEditorController>(@@ -1702,6 +1705,19 @@ function DocxEditorContent({const handlePageCountChange = React.useCallback((nextPageCount: number) => {setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))}, [])+ const setViewportRef = React.useCallback((element: HTMLDivElement | null) => {+ viewportRef.current = element+ setViewportElement(element)+ }, [])+ const pageVirtualization = React.useMemo(+ () => ({+ enabled: true,+ overscan: 1,+ scrollElement: viewportElement,+ zoomScale: zoomScale / 100,+ }),+ [viewportElement, zoomScale]+ )useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)@@ -1826,26 +1842,41 @@ function DocxEditorContent({}}, [pageCount, updateActivePageFromViewport])- const scrollToPage = React.useCallback((pageNumber: number) => {- const viewport = viewportRef.current- const targetPageIndex = pageNumber - 1- const page = viewport?.querySelector<HTMLElement>(- `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`- )+ const scrollToPage = React.useCallback(+ (pageNumber: number) => {+ const viewport = viewportRef.current+ const targetPageIndex = pageNumber - 1+ const page = viewport?.querySelector<HTMLElement>(+ `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`+ )- setActivePage(pageNumber)+ setActivePage(pageNumber)- if (!viewport || !page) return+ if (!viewport) return- viewport.scrollTo({- top:- page.getBoundingClientRect().top -- viewport.getBoundingClientRect().top +- viewport.scrollTop -- 24,- behavior: "auto",- })- }, [])+ if (!page) {+ const pageStridePx =+ (pageLayout.pageHeightPx + pageLayout.viewportDefaults.pageGapPx) *+ (zoomScale / 100)++ viewport.scrollTo({+ top: Math.max(0, targetPageIndex * pageStridePx - 24),+ behavior: "auto",+ })+ return+ }++ viewport.scrollTo({+ top:+ page.getBoundingClientRect().top -+ viewport.getBoundingClientRect().top ++ viewport.scrollTop -+ 24,+ behavior: "auto",+ })+ },+ [pageLayout.pageHeightPx, pageLayout.viewportDefaults.pageGapPx, zoomScale]+ )async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {const file = event.target.files?.[0]@@ -2017,7 +2048,7 @@ function DocxEditorContent({className="min-h-0 flex-1"style={{ backgroundColor: viewerBackgroundColor }}viewportClassName="overscroll-contain p-4"- viewportRef={viewportRef}+ viewportRef={setViewportRef}>{!url && !uploadedDocxFile ? (<div className="grid h-full min-h-96 place-items-center p-6 text-center">@@ -2069,7 +2100,7 @@ function DocxEditorContent({editor.documentTheme === "dark" ? "#0a0a0a" : undefined}pageGapBackgroundColor={viewerBackgroundColor}- pageVirtualization={{ enabled: false }}+ pageVirtualization={pageVirtualization}deferInitialPaginationPaint={false}onPageCountChange={handlePageCountChange}/>diff --git a/apps/v4/components/ui/docx-viewer.tsx b/apps/v4/components/ui/docx-viewer.tsxindex 7a835af..4737f94 100644--- a/apps/v4/components/ui/docx-viewer.tsx+++ b/apps/v4/components/ui/docx-viewer.tsx@@ -3,18 +3,24 @@import * as React from "react"import {DocxEditorViewer,+ useDocxComments,useDocxEditor,+ useDocxPageLayout,+ useDocxTrackChanges,useDocxViewerThumbnails,type DocxDocumentTheme,type DocxEditorController,+ type DocxPageThumbnailItem,} from "@extend-ai/react-docx"+import { useVirtualizer } from "@tanstack/react-virtual"import {+ Comment01Icon,Download01Icon,MinusSignCircleIcon,Moon02Icon,+ MoreHorizontalIcon,PlusSignCircleIcon,SidebarLeftIcon,- Sun03Icon,Upload01Icon,} from "@hugeicons/core-free-icons"import { HugeiconsIcon } from "@hugeicons/react"@@ -26,6 +32,14 @@ import {useElementWidth,useInlineThumbnailSidebar,} from "@/components/ui/document-viewer-sidebar"+import {+ DropdownMenu,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu"import { FileThumbnail } from "@/components/ui/file-thumbnail"import { Input } from "@/components/ui/input"import { ScrollArea } from "@/components/ui/scroll-area"@@ -49,6 +63,9 @@ const DOCX_MIME_TYPE ="application/vnd.openxmlformats-officedocument.wordprocessingml.document"const DOCX_LOADING_INDICATOR_DELAY_MS = 300const DOCX_THUMBNAIL_WIDTH = 92+const DOCX_THUMBNAIL_LIST_PADDING = 16+const DOCX_THUMBNAIL_ROW_ESTIMATE = 172+const DEFAULT_ZOOM = 50const ZOOM_OPTIONS = [10, 25, 50, 75, 100, 125, 150, 175, 200, 400] as constconst DOCX_PADDING_WARNING_TEXT = "a style property during rerender"@@ -156,6 +173,13 @@ function getNextZoomScale(currentZoomScale: number, direction: 1 | -1) {return ZOOM_OPTIONS[nextIndex] ?? currentZoomScale}+function normalizeDocxZoomScale(value: number | undefined): number {+ return typeof value === "number" &&+ ZOOM_OPTIONS.includes(value as (typeof ZOOM_OPTIONS)[number])+ ? value+ : DEFAULT_ZOOM+}+function useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {const [showSpinner, setShowSpinner] = React.useState(false)@@ -229,6 +253,99 @@ function ViewerLoadingSurface({)}+function DocxFileActionsMenu({+ controlsDisabled,+ downloadDisabled,+ isPreparingDownload,+ isDark,+ onDownload,+ onIsDarkChange,+ onShowDocumentMarkupChange,+ onUploadClick,+ showDocumentMarkup,+ showDownloadButton,+ showNightRenderToggle,+ showUploadButton,+}: {+ controlsDisabled: boolean+ downloadDisabled: boolean+ isPreparingDownload: boolean+ isDark: boolean+ onDownload: () => void+ onIsDarkChange: (checked: boolean) => void+ onShowDocumentMarkupChange: (checked: boolean) => void+ onUploadClick: () => void+ showDocumentMarkup: boolean+ showDownloadButton: boolean+ showNightRenderToggle: boolean+ showUploadButton: boolean+}) {+ const showFileActions = showDownloadButton || showUploadButton++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Open DOCX actions"+ >+ <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-52">+ {showNightRenderToggle ? (+ <>+ <DropdownMenuCheckboxItem+ checked={isDark}+ disabled={controlsDisabled}+ variant="switch"+ onCheckedChange={(checked) => onIsDarkChange(checked === true)}+ >+ <span className="flex min-w-0 items-center gap-2">+ <HugeiconsIcon icon={Moon02Icon} className="size-4" />+ Dark mode+ </span>+ </DropdownMenuCheckboxItem>+ <DropdownMenuSeparator />+ </>+ ) : null}+ <DropdownMenuCheckboxItem+ checked={showDocumentMarkup}+ disabled={controlsDisabled}+ variant="switch"+ onCheckedChange={(checked) =>+ onShowDocumentMarkupChange(checked === true)+ }+ >+ <span className="flex min-w-0 items-center gap-2">+ <HugeiconsIcon icon={Comment01Icon} className="size-4" />+ Comments/edits+ </span>+ </DropdownMenuCheckboxItem>+ {showFileActions ? <DropdownMenuSeparator /> : null}+ {showDownloadButton ? (+ <DropdownMenuItem disabled={downloadDisabled} onClick={onDownload}>+ {isPreparingDownload ? (+ <Spinner className="size-4" />+ ) : (+ <HugeiconsIcon icon={Download01Icon} className="size-4" />+ )}+ Download+ </DropdownMenuItem>+ ) : null}+ {showUploadButton ? (+ <DropdownMenuItem onClick={onUploadClick}>+ <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ Upload+ </DropdownMenuItem>+ ) : null}+ </DropdownMenuContent>+ </DropdownMenu>+ )+}+function DocxPageNumberControl({activePage,controlsDisabled,@@ -325,10 +442,12 @@ function DocxToolbar({onDownload,onIsDarkChange,onPageChange,+ onShowDocumentMarkupChange,onToggleSidebar,onUploadClick,pageCount,setZoomScale,+ showDocumentMarkup,showDownloadButton = true,showNightRenderToggle,showUploadButton = true,@@ -342,10 +461,12 @@ function DocxToolbar({onDownload: () => voidonIsDarkChange: (checked: boolean) => voidonPageChange: (pageNumber: number) => void+ onShowDocumentMarkupChange: (checked: boolean) => voidonToggleSidebar: () => voidonUploadClick: () => voidpageCount: numbersetZoomScale: React.Dispatch<React.SetStateAction<number>>+ showDocumentMarkup: booleanshowDownloadButton?: booleanshowNightRenderToggle: booleanshowUploadButton?: boolean@@ -379,26 +500,6 @@ function DocxToolbar({/></div><div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1">- {showNightRenderToggle ? (- <ToolbarTooltip- label={isDark ? "Use light document" : "Use dark document"}- >- <Button- type="button"- variant="ghost"- size="icon-sm"- disabled={controlsDisabled}- aria-label={isDark ? "Use light document" : "Use dark document"}- onClick={() => onIsDarkChange(!isDark)}- >- <HugeiconsIcon- icon={isDark ? Sun03Icon : Moon02Icon}- className="size-4"- />- </Button>- </ToolbarTooltip>- ) : null}- <Separator orientation="vertical" className="mx-1 h-4 self-center" /><div className="flex flex-none items-center gap-1"><ToolbarTooltip label="Zoom out"><Button@@ -454,49 +555,6 @@ function DocxToolbar({</Button></ToolbarTooltip></div>- {showDownloadButton ? (- <>- <Separator- orientation="vertical"- className="mx-1 h-4 self-center"- />- <ToolbarTooltip label="Download DOCX">- <Button- type="button"- variant="ghost"- size="icon-sm"- aria-label="Download DOCX"- disabled={controlsDisabled || isPreparingDownload}- onClick={onDownload}- >- {isPreparingDownload ? (- <Spinner className="size-4" />- ) : (- <HugeiconsIcon icon={Download01Icon} className="size-4" />- )}- </Button>- </ToolbarTooltip>- </>- ) : null}- {showUploadButton ? (- <>- <Separator- orientation="vertical"- className="mx-1 h-4 self-center"- />- <ToolbarTooltip label="Upload DOCX">- <Button- type="button"- variant="ghost"- size="icon-sm"- aria-label="Upload DOCX"- onClick={onUploadClick}- >- <HugeiconsIcon icon={Upload01Icon} className="size-4" />- </Button>- </ToolbarTooltip>- </>- ) : null}{toolbarActions ? (<><Separator@@ -506,6 +564,21 @@ function DocxToolbar({{toolbarActions}</>) : null}+ <Separator orientation="vertical" className="mx-1 h-4 self-center" />+ <DocxFileActionsMenu+ controlsDisabled={controlsDisabled}+ downloadDisabled={controlsDisabled || isPreparingDownload}+ isPreparingDownload={isPreparingDownload}+ isDark={isDark}+ onDownload={onDownload}+ onIsDarkChange={onIsDarkChange}+ onShowDocumentMarkupChange={onShowDocumentMarkupChange}+ onUploadClick={onUploadClick}+ showDocumentMarkup={showDocumentMarkup}+ showDownloadButton={showDownloadButton}+ showNightRenderToggle={showNightRenderToggle}+ showUploadButton={showUploadButton}+ /></div></TooltipProvider></div>@@ -559,8 +632,119 @@ function DocxSidebarThumbnail({)}+function DocxThumbnailSidebarList({+ activePage,+ displayFileName,+ isLoadingDocument,+ onSelectPage,+ pageCount,+ sidebarOpen,+ thumbnails,+}: {+ activePage: number+ displayFileName: string+ isLoadingDocument: boolean+ onSelectPage: (pageNumber: number) => void+ pageCount: number+ sidebarOpen: boolean+ thumbnails: DocxPageThumbnailItem[]+}) {+ const viewportRef = React.useRef<HTMLDivElement | null>(null)+ const visibleThumbnails = React.useMemo(+ () => thumbnails.slice(0, pageCount || 0),+ [pageCount, thumbnails]+ )+ const virtualizer = useVirtualizer({+ count: visibleThumbnails.length,+ estimateSize: () => DOCX_THUMBNAIL_ROW_ESTIMATE,+ getItemKey: (index) => visibleThumbnails[index]?.pageIndex ?? index,+ getScrollElement: () => viewportRef.current,+ overscan: 3,+ })++ React.useEffect(() => {+ if (!sidebarOpen || activePage < 1 || !visibleThumbnails.length) return++ virtualizer.scrollToIndex(+ Math.min(activePage - 1, visibleThumbnails.length - 1),+ { align: "auto" }+ )+ }, [activePage, sidebarOpen, virtualizer, visibleThumbnails.length])++ return (+ <ScrollArea className="h-full" scrollFade viewportRef={viewportRef}>+ {isLoadingDocument ? (+ <div className="p-4">+ <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">+ <div className="h-full animate-pulse bg-muted" />+ </div>+ <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />+ </div>+ ) : visibleThumbnails.length ? (+ <div+ className="relative"+ style={{+ height: virtualizer.getTotalSize() + DOCX_THUMBNAIL_LIST_PADDING * 2,+ }}+ >+ {virtualizer.getVirtualItems().map((virtualRow) => {+ const thumbnail = visibleThumbnails[virtualRow.index]+ if (!thumbnail) return null++ return (+ <div+ key={virtualRow.key}+ ref={virtualizer.measureElement}+ data-index={virtualRow.index}+ className="absolute top-0 right-3 left-3 pb-3 [contain:layout_paint]"+ style={{+ transform: `translateY(${+ virtualRow.start + DOCX_THUMBNAIL_LIST_PADDING+ }px)`,+ }}+ >+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className={cn(+ "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none transition-none hover:bg-sidebar-accent",+ thumbnail.pageNumber === activePage &&+ "bg-sidebar-accent text-foreground",+ thumbnail.pageNumber !== activePage &&+ "text-muted-foreground"+ )}+ onFocus={(event) => event.currentTarget.blur()}+ onClick={() => onSelectPage(thumbnail.pageNumber)}+ >+ <DocxSidebarThumbnail+ canvasRef={thumbnail.canvasRef}+ displayFileName={displayFileName}+ hasError={thumbnail.status === "error"}+ isActive={thumbnail.pageNumber === activePage}+ isLoading={+ thumbnail.status !== "ready" &&+ thumbnail.status !== "error"+ }+ pageNumber={thumbnail.pageNumber}+ pixelHeightPx={thumbnail.pixelHeightPx}+ pixelWidthPx={thumbnail.pixelWidthPx}+ previewAspectRatio={thumbnail.aspectRatio}+ />+ {thumbnail.pageNumber}+ </Button>+ </div>+ )+ })}+ </div>+ ) : null}+ </ScrollArea>+ )+}+export function DocxViewerPreview({className,+ defaultZoom = DEFAULT_ZOOM,fileName,isDark,onIsDarkChange,@@ -571,6 +755,7 @@ export function DocxViewerPreview({toolbarActions,}: {className?: string+ defaultZoom?: numberfileName?: stringisDark: booleanonIsDarkChange: (isDark: boolean) => void@@ -583,6 +768,7 @@ export function DocxViewerPreview({return (<DocxViewerContentclassName={className}+ defaultZoom={defaultZoom}effectiveIsDark={isDark}fileName={fileName}setNightRenderEnabled={onIsDarkChange}@@ -598,6 +784,7 @@ export function DocxViewerPreview({function DocxViewerContent({className,+ defaultZoom,effectiveIsDark,fileName,setNightRenderEnabled,@@ -609,6 +796,7 @@ function DocxViewerContent({url,}: {className?: string+ defaultZoom?: numbereffectiveIsDark: booleanfileName?: stringsetNightRenderEnabled: (checked: boolean) => void@@ -628,6 +816,7 @@ function DocxViewerContent({React.useState<UploadedDocxFile | null>(null)const [activePage, setActivePage] = React.useState(1)const [sidebarOpen, setSidebarOpen] = React.useState(false)+ const resolvedDefaultZoomScale = normalizeDocxZoomScale(defaultZoom)const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)const viewerBackgroundColor ="color-mix(in oklab, var(--muted) 40%, transparent)"@@ -648,7 +837,11 @@ function DocxViewerContent({[displayFileName, initialDocumentTheme])const editor = useDocxEditor(editorOptions)+ const { layout: pageLayout } = useDocxPageLayout(editor)const { importDocxFile, setDocumentTheme, status } = editor+ const { showComments, setShowComments } = useDocxComments(editor)+ const { showTrackedChanges, setShowTrackedChanges } =+ useDocxTrackChanges(editor)const [reportedPageCount, setReportedPageCount] = React.useState(0)const thumbnailEditor = React.useMemo<DocxEditorController>(() => ({@@ -659,10 +852,10 @@ function DocxViewerContent({)const thumbnailOptions = React.useMemo(() => ({- // Thumbnails paint from mounted page DOM, so they can only render- // while the sidebar is showing them; skip the work when it is closed.+ // Detached thumbnail rendering handles offscreen pages; keep the raster+ // queue dormant while the sidebar is closed.disabled: !sidebarOpen,- pixelRatio: 2,+ pixelRatio: 1,resolution: {maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,maxWidth: DOCX_THUMBNAIL_WIDTH,@@ -674,7 +867,9 @@ function DocxViewerContent({thumbnailEditor,thumbnailOptions)- const [zoomScale, setZoomScale] = React.useState(100)+ const [zoomScale, setZoomScale] = React.useState<number>(+ resolvedDefaultZoomScale+ )const [loadError, setLoadError] = React.useState<string>()const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)@@ -692,6 +887,7 @@ function DocxViewerContent({: 0const controlsDisabled =!hasDocument || isLoadingDocument || Boolean(loadError)+ const showDocumentMarkup = showComments || showTrackedChangesconst handlePageCountChange = React.useCallback((nextPageCount: number) => {setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))}, [])@@ -701,14 +897,12 @@ function DocxViewerContent({}, [])const pageVirtualization = React.useMemo(() => ({- // Sidebar thumbnails can only paint from mounted page DOM,- // so every page must mount while the sidebar is open;- // otherwise let the viewer virtualize off-screen pages.- enabled: !sidebarOpen,+ enabled: true,+ overscan: 1,scrollElement: viewportElement,zoomScale: zoomScale / 100,}),- [sidebarOpen, viewportElement, zoomScale]+ [viewportElement, zoomScale])const handleDownload = React.useCallback(async () => {if (isPreparingDownload) return@@ -728,14 +922,21 @@ function DocxViewerContent({setIsPreparingDownload(false)}}, [displayFileName, isPreparingDownload, uploadedDocxFile, url])+ const handleShowDocumentMarkupChange = React.useCallback(+ (checked: boolean) => {+ setShowComments(checked)+ setShowTrackedChanges(checked)+ },+ [setShowComments, setShowTrackedChanges]+ )useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)React.useEffect(() => {- setZoomScale(100)+ setZoomScale(resolvedDefaultZoomScale)setActivePage(1)viewportRef.current?.scrollTo({ top: 0, left: 0 })- }, [url])+ }, [resolvedDefaultZoomScale, url])React.useEffect(() => {setDocumentTheme(effectiveIsDark ? "dark" : "light")@@ -859,26 +1060,41 @@ function DocxViewerContent({}}, [pageCount, updateActivePageFromViewport])- const scrollToPage = React.useCallback((pageNumber: number) => {- const viewport = viewportRef.current- const targetPageIndex = pageNumber - 1- const page = viewport?.querySelector<HTMLElement>(- `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`- )+ const scrollToPage = React.useCallback(+ (pageNumber: number) => {+ const viewport = viewportRef.current+ const targetPageIndex = pageNumber - 1+ const page = viewport?.querySelector<HTMLElement>(+ `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`+ )- setActivePage(pageNumber)+ setActivePage(pageNumber)- if (!viewport || !page) return+ if (!viewport) return- viewport.scrollTo({- top:- page.getBoundingClientRect().top -- viewport.getBoundingClientRect().top +- viewport.scrollTop -- 24,- behavior: "auto",- })- }, [])+ if (!page) {+ const pageStridePx =+ (pageLayout.pageHeightPx + pageLayout.viewportDefaults.pageGapPx) *+ (zoomScale / 100)++ viewport.scrollTo({+ top: Math.max(0, targetPageIndex * pageStridePx - 24),+ behavior: "auto",+ })+ return+ }++ viewport.scrollTo({+ top:+ page.getBoundingClientRect().top -+ viewport.getBoundingClientRect().top ++ viewport.scrollTop -+ 24,+ behavior: "auto",+ })+ },+ [pageLayout.pageHeightPx, pageLayout.viewportDefaults.pageGapPx, zoomScale]+ )async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {const file = event.target.files?.[0]@@ -886,7 +1102,7 @@ function DocxViewerContent({if (!file) return- setZoomScale(100)+ setZoomScale(resolvedDefaultZoomScale)setActivePage(1)setReportedPageCount(0)setUploadedDocxFile({@@ -918,10 +1134,12 @@ function DocxViewerContent({onDownload={handleDownload}onIsDarkChange={setNightRenderEnabled}onPageChange={scrollToPage}+ onShowDocumentMarkupChange={handleShowDocumentMarkupChange}onToggleSidebar={() => setSidebarOpen((open) => !open)}onUploadClick={() => fileInputRef.current?.click()}pageCount={pageCount}setZoomScale={setZoomScale}+ showDocumentMarkup={showDocumentMarkup}showDownloadButton={showDownload}showNightRenderToggle={shouldRenderNightMode}showUploadButton={showUpload}@@ -937,60 +1155,20 @@ function DocxViewerContent({inline={sidebarInline}open={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}>- <ScrollArea className="h-full" scrollFade>- <div className="p-4">- {isLoadingDocument ? (- <>- <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">- <div className="h-full animate-pulse bg-muted" />- </div>- <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />- </>- ) : (- <div className="flex flex-col items-center gap-3">- {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (- <Button- key={thumbnail.pageIndex}- type="button"- variant="ghost"- size="sm"- className={cn(- "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none transition-none hover:bg-sidebar-accent",- thumbnail.pageNumber === activePage &&- "bg-sidebar-accent text-foreground",- thumbnail.pageNumber !== activePage &&- "text-muted-foreground"- )}- onFocus={(event) => event.currentTarget.blur()}- onClick={() => scrollToPage(thumbnail.pageNumber)}- >- <DocxSidebarThumbnail- canvasRef={thumbnail.canvasRef}- displayFileName={displayFileName}- hasError={thumbnail.status === "error"}- isActive={thumbnail.pageNumber === activePage}- isLoading={- !thumbnail.isMounted &&- thumbnail.status !== "ready" &&- thumbnail.status !== "error"- }- pageNumber={thumbnail.pageNumber}- pixelHeightPx={thumbnail.pixelHeightPx}- pixelWidthPx={thumbnail.pixelWidthPx}- previewAspectRatio={thumbnail.aspectRatio}- />- {thumbnail.pageNumber}- </Button>- ))}- </div>- )}- </div>- </ScrollArea>+ <DocxThumbnailSidebarList+ activePage={activePage}+ displayFileName={displayFileName}+ isLoadingDocument={isLoadingDocument}+ onSelectPage={scrollToPage}+ pageCount={pageCount}+ sidebarOpen={sidebarOpen}+ thumbnails={thumbnails}+ /></DocumentViewerThumbnailSidebar><ScrollAreaclassName="min-h-0 flex-1"style={{ backgroundColor: viewerBackgroundColor }}- viewportClassName="p-4"+ viewportClassName="px-4 py-6"viewportRef={setViewportRef}>{!url && !uploadedDocxFile ? (@@ -1034,6 +1212,8 @@ function DocxViewerContent({<DocxEditorViewereditor={editor}mode="read-only"+ showTrackedChanges={showTrackedChanges}+ showComments={showComments}loadingState={loadingState}pageBackgroundColor={effectiveIsDark ? "#0a0a0a" : undefined}pageGapBackgroundColor={viewerBackgroundColor}diff --git a/apps/v4/components/ui/file-system.tsx b/apps/v4/components/ui/file-system.tsxindex b239a9f..01cb49f 100644--- a/apps/v4/components/ui/file-system.tsx+++ b/apps/v4/components/ui/file-system.tsx@@ -4767,9 +4767,11 @@ function FileSystemGalleryStage({src={url}fileName={file.name}isDark={isDark}- className="h-full min-h-0"+ className={cn(+ "h-full min-h-0",+ isDialog && "overflow-hidden rounded-2xl"+ )}onIsDarkChange={setIsDark}- rounded={isDialog}showToolbar={isDialog}showUpload={false}toolbarActions={toolbarActions}@@ -4786,9 +4788,11 @@ function FileSystemGalleryStage({src={url}fileName={file.name}isDark={isDark}- className="h-full min-h-0"+ className={cn(+ "h-full min-h-0",+ isDialog && "overflow-hidden rounded-2xl"+ )}onIsDarkChange={setIsDark}- rounded={isDialog}showToolbar={isDialog}showUpload={false}toolbarActions={toolbarActions}diff --git a/apps/v4/components/ui/pdf-viewer.tsx b/apps/v4/components/ui/pdf-viewer.tsxindex 05c6059..cda6ecb 100644--- a/apps/v4/components/ui/pdf-viewer.tsx+++ b/apps/v4/components/ui/pdf-viewer.tsx@@ -64,6 +64,7 @@ import {ArrowRight01Icon,Download01Icon,MinusSignCircleIcon,+ MoreHorizontalIcon,PlusSignCircleIcon,RotateClockwiseIcon,Search01Icon,@@ -81,6 +82,12 @@ import {useElementWidth,useInlineThumbnailSidebar,} from "@/components/ui/document-viewer-sidebar"+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu"import { Input } from "@/components/ui/input"import {Popover,@@ -127,10 +134,6 @@ export type PDFViewerProps = {className?: stringdefaultZoom?: numberfileName?: string- /** Retained for API compatibility; page sizes come from the document. */- pageWidth?: number- /** Retained for API compatibility; page sizes come from the document. */- pageHeight?: numbershowDownload?: booleanshowToolbar?: booleanshowRotateControls?: boolean@@ -486,7 +489,7 @@ function PDFViewerFallbackShell({{showToolbar ? (<div className="flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2">{showUpload && onUploadFile ? (- <PDFViewerUploadControl onUploadFile={onUploadFile} />+ <PDFViewerFileActionsMenu onUploadFile={onUploadFile} showUpload />) : null}</div>) : null}@@ -534,39 +537,74 @@ function ToolbarTooltip({)}-function PDFViewerUploadControl({+function PDFViewerFileActionsMenu({+ downloadDisabled,+ isPreparingDownload = false,+ onDownload,onUploadFile,+ showDownload = false,+ showUpload = false,}: {- onUploadFile: (file: File) => void+ downloadDisabled?: boolean+ isPreparingDownload?: boolean+ onDownload?: () => void+ onUploadFile?: (file: File) => void+ showDownload?: boolean+ showUpload?: boolean}) {const inputRef = React.useRef<HTMLInputElement>(null)+ if (!showDownload && !showUpload) return null+return (<>- <input- ref={inputRef}- type="file"- accept="application/pdf,.pdf"- className="sr-only"- tabIndex={-1}- onChange={(event) => {- const nextFile = event.target.files?.[0]-- if (nextFile) {- onUploadFile(nextFile)- event.currentTarget.value = ""- }- }}- />- <Button- type="button"- variant="ghost"- size="icon-sm"- aria-label="Upload PDF"- onClick={() => inputRef.current?.click()}- >- <HugeiconsIcon icon={Upload01Icon} className="size-4" />- </Button>+ {showUpload && onUploadFile ? (+ <input+ ref={inputRef}+ type="file"+ accept="application/pdf,.pdf"+ className="sr-only"+ tabIndex={-1}+ onChange={(event) => {+ const nextFile = event.target.files?.[0]++ if (nextFile) {+ onUploadFile(nextFile)+ event.currentTarget.value = ""+ }+ }}+ />+ ) : null}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Open PDF actions"+ >+ <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-40">+ {showDownload && onDownload ? (+ <DropdownMenuItem disabled={downloadDisabled} onClick={onDownload}>+ {isPreparingDownload ? (+ <Spinner className="size-4" />+ ) : (+ <HugeiconsIcon icon={Download01Icon} className="size-4" />+ )}+ Download+ </DropdownMenuItem>+ ) : null}+ {showUpload && onUploadFile ? (+ <DropdownMenuItem onClick={() => inputRef.current?.click()}>+ <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ Upload+ </DropdownMenuItem>+ ) : null}+ </DropdownMenuContent>+ </DropdownMenu></>)}@@ -2354,51 +2392,29 @@ function PDFViewerInner({documentId={documentId}controlsDisabled={controlsDisabled}/>- {showDownload ? (+ {toolbarActions ? (<><Separatororientation="vertical"className="mx-1 h-4 self-center"/>- <ToolbarTooltip label="Download PDF">- <Button- type="button"- variant="ghost"- size="icon-sm"- aria-label="Download PDF"- disabled={downloadDisabled}- onClick={handleDownload}- >- {isPreparingDownload ? (- <Spinner className="size-4" />- ) : (- <HugeiconsIcon- icon={Download01Icon}- className="size-4"- />- )}- </Button>- </ToolbarTooltip>+ {toolbarActions}</>) : null}- {showUpload ? (+ {showDownload || showUpload ? (<><Separatororientation="vertical"className="mx-1 h-4 self-center"/>- <ToolbarTooltip label="Upload PDF">- <PDFViewerUploadControl onUploadFile={handleUpload} />- </ToolbarTooltip>- </>- ) : null}- {toolbarActions ? (- <>- <Separator- orientation="vertical"- className="mx-1 h-4 self-center"+ <PDFViewerFileActionsMenu+ downloadDisabled={downloadDisabled}+ isPreparingDownload={isPreparingDownload}+ onDownload={handleDownload}+ onUploadFile={handleUpload}+ showDownload={showDownload}+ showUpload={showUpload}/>- {toolbarActions}</>) : null}</div>@@ -2544,8 +2560,6 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(className,defaultZoom = DEFAULT_ZOOM,fileName,- pageWidth: _pageWidth,- pageHeight: _pageHeight,showDownload = true,showRotateControls = true,showToolbar = true,@@ -2659,10 +2673,7 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(<div className="min-h-12 border-b bg-background" />) : null}<div className="relative min-h-0 flex-1">- <PDFViewerLoadingSkeleton- sidebarInline- sidebarOpen={false}- />+ <PDFViewerLoadingSkeleton sidebarInline sidebarOpen={false} /></div></div>)diff --git a/apps/v4/components/ui/xlsx-editor.tsx b/apps/v4/components/ui/xlsx-editor.tsxindex ae3cce6..ffd3f7b 100644--- a/apps/v4/components/ui/xlsx-editor.tsx+++ b/apps/v4/components/ui/xlsx-editor.tsx@@ -17,6 +17,7 @@ import {Download01Icon,MinusSignCircleIcon,Moon02Icon,+ MoreHorizontalIcon,PlusSignCircleIcon,Redo02Icon,Sun03Icon,@@ -27,6 +28,12 @@ import { HugeiconsIcon } from "@hugeicons/react"import { cn } from "@/lib/utils"import { Button } from "@/components/ui/button"+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu"import { Group, GroupSeparator, GroupText } from "@/components/ui/group"import { Input } from "@/components/ui/input"import {@@ -126,6 +133,44 @@ function EditorLoadingSurface({)}+function EditorFileActionsMenu({+ canExport,+ exportXlsx,+ onUploadClick,+}: {+ canExport: boolean+ exportXlsx: () => void+ onUploadClick: () => void+}) {+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Open workbook actions"+ >+ <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className={cn("w-40", XLSX_DROPDOWN_Z_INDEX_CLASS)}+ >+ <DropdownMenuItem disabled={!canExport} onClick={exportXlsx}>+ <HugeiconsIcon icon={Download01Icon} className="size-4" />+ Download+ </DropdownMenuItem>+ <DropdownMenuItem onClick={onUploadClick}>+ <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ Upload+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )+}+function EditorToolbar({isDark,onIsDarkChange,@@ -223,29 +268,11 @@ function EditorToolbar({/></>) : null}- <ToolbarTooltip label="Export workbook">- <Button- type="button"- variant="ghost"- size="icon-sm"- aria-label="Export workbook"- disabled={!canExport}- onClick={exportXlsx}- >- <HugeiconsIcon icon={Download01Icon} className="size-4" />- </Button>- </ToolbarTooltip>- <ToolbarTooltip label="Upload XLSX">- <Button- type="button"- variant="ghost"- size="icon-sm"- aria-label="Upload XLSX"- onClick={onUploadClick}- >- <HugeiconsIcon icon={Upload01Icon} className="size-4" />- </Button>- </ToolbarTooltip>+ <EditorFileActionsMenu+ canExport={canExport}+ exportXlsx={exportXlsx}+ onUploadClick={onUploadClick}+ /></div></TooltipProvider></div>@@ -461,7 +488,6 @@ export function XlsxEditorSurface({onIsDarkChange,onUploadClick,renderTableHeaderMenu,- rounded,showNightRenderToggle,workbookIdentity,}: {@@ -472,7 +498,6 @@ export function XlsxEditorSurface({renderTableHeaderMenu: (props: XlsxTableHeaderMenuRenderProps) => React.ReactNode- rounded: booleanshowNightRenderToggle: booleanworkbookIdentity: string}) {@@ -482,8 +507,7 @@ export function XlsxEditorSurface({<divclassName={cn("flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",- className,- rounded && "rounded-lg"+ className)}><EditorToolbar@@ -536,14 +560,12 @@ export function XlsxEditorPreview({fileName,isDark,onIsDarkChange,- rounded = false,src,}: {className?: stringfileName?: stringisDark: booleanonIsDarkChange: (isDark: boolean) => void- rounded?: booleansrc?: string}) {return (@@ -551,7 +573,6 @@ export function XlsxEditorPreview({className={className}effectiveIsDark={isDark}fileName={fileName}- rounded={rounded}setNightRenderEnabled={onIsDarkChange}shouldRenderNightModeurl={src}@@ -563,7 +584,6 @@ function XlsxEditorContent({className,effectiveIsDark,fileName,- rounded,setNightRenderEnabled,shouldRenderNightMode,url,@@ -571,7 +591,6 @@ function XlsxEditorContent({className?: stringeffectiveIsDark: booleanfileName?: string- rounded: booleansetNightRenderEnabled: (checked: boolean) => voidshouldRenderNightMode: booleanurl?: string@@ -766,7 +785,6 @@ function XlsxEditorContent({renderTableHeaderMenu={(props) => (<WorkbookTableHeaderMenu {...props} />)}- rounded={rounded}showNightRenderToggle={shouldRenderNightMode}workbookBuffer={activeBuffer}workbookIdentity={workbookIdentity}@@ -781,7 +799,6 @@ function XlsxWorkbookLoadedEditor({onIsDarkChange,onUploadClick,renderTableHeaderMenu,- rounded,showNightRenderToggle,workbookBuffer,workbookIdentity,@@ -793,7 +810,6 @@ function XlsxWorkbookLoadedEditor({renderTableHeaderMenu: (props: XlsxTableHeaderMenuRenderProps) => React.ReactNode- rounded: booleanshowNightRenderToggle: booleanworkbookBuffer: ArrayBufferworkbookIdentity: string@@ -819,7 +835,6 @@ function XlsxWorkbookLoadedEditor({onIsDarkChange={onIsDarkChange}onUploadClick={onUploadClick}renderTableHeaderMenu={renderTableHeaderMenu}- rounded={rounded}showNightRenderToggle={showNightRenderToggle}workbookIdentity={workbookIdentity}/>diff --git a/apps/v4/components/ui/xlsx-viewer.tsx b/apps/v4/components/ui/xlsx-viewer.tsxindex 5cb8ec5..8fdeaba 100644--- a/apps/v4/components/ui/xlsx-viewer.tsx+++ b/apps/v4/components/ui/xlsx-viewer.tsx@@ -23,7 +23,6 @@ import {MoreHorizontalIcon,PlusSignCircleIcon,Search01Icon,- Sun03Icon,Upload01Icon,} from "@hugeicons/core-free-icons"import { HugeiconsIcon } from "@hugeicons/react"@@ -33,10 +32,12 @@ import { cn } from "@/lib/utils"import { Button } from "@/components/ui/button"import {DropdownMenu,+ DropdownMenuCheckboxItem,DropdownMenuContent,DropdownMenuItem,DropdownMenuRadioGroup,DropdownMenuRadioItem,+ DropdownMenuSeparator,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu"import { Input } from "@/components/ui/input"@@ -466,6 +467,75 @@ function ViewerLoadingSurface({)}+function WorkbookFileActionsMenu({+ isDark,+ onDownload,+ onIsDarkChange,+ onUploadClick,+ showDownloadButton,+ showNightRenderToggle = false,+ showUploadButton,+}: {+ isDark?: boolean+ onDownload?: () => void+ onIsDarkChange?: (checked: boolean) => void+ onUploadClick: () => void+ showDownloadButton: boolean+ showNightRenderToggle?: boolean+ showUploadButton: boolean+}) {+ const showThemeControl = showNightRenderToggle && Boolean(onIsDarkChange)+ const showFileActions = (showDownloadButton && onDownload) || showUploadButton+ if (!showThemeControl && !showFileActions) return null++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Open workbook actions"+ >+ <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className={cn("w-52", XLSX_DROPDOWN_Z_INDEX_CLASS)}+ >+ {showThemeControl ? (+ <>+ <DropdownMenuCheckboxItem+ checked={Boolean(isDark)}+ variant="switch"+ onCheckedChange={(checked) => onIsDarkChange?.(checked === true)}+ >+ <span className="flex min-w-0 items-center gap-2">+ <HugeiconsIcon icon={Moon02Icon} className="size-4" />+ Dark mode+ </span>+ </DropdownMenuCheckboxItem>+ {showFileActions ? <DropdownMenuSeparator /> : null}+ </>+ ) : null}+ {showDownloadButton && onDownload ? (+ <DropdownMenuItem onClick={onDownload}>+ <HugeiconsIcon icon={Download01Icon} className="size-4" />+ Download+ </DropdownMenuItem>+ ) : null}+ {showUploadButton ? (+ <DropdownMenuItem onClick={onUploadClick}>+ <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ Upload+ </DropdownMenuItem>+ ) : null}+ </DropdownMenuContent>+ </DropdownMenu>+ )+}+export function renderXlsxScroller({children,viewportProps,@@ -812,30 +882,6 @@ function WorkbookToolbar({<div className="flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2"><TooltipProvider><div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1">- {showNightRenderToggle ? (- <ToolbarTooltip- label={isDark ? "Use light workbook" : "Use dark workbook"}- >- <Button- type="button"- variant="ghost"- size="icon-sm"- aria-label={isDark ? "Use light workbook" : "Use dark workbook"}- onClick={() => onIsDarkChange(!isDark)}- >- <HugeiconsIcon- icon={isDark ? Sun03Icon : Moon02Icon}- className="size-4"- />- </Button>- </ToolbarTooltip>- ) : null}- {showNightRenderToggle ? (- <Separator- orientation="vertical"- className="mx-1 h-4 self-center"- />- ) : null}<div className="flex flex-none items-center gap-1"><ToolbarTooltip label="Zoom out"><Button@@ -891,51 +937,32 @@ function WorkbookToolbar({viewportRef={viewportRef}workbookIdentity={workbookIdentity}/>- {showDownloadButton && onDownload ? (+ {toolbarActions ? (<><Separatororientation="vertical"className="mx-1 h-4 self-center"/>- <ToolbarTooltip label="Download XLSX">- <Button- type="button"- variant="ghost"- size="icon-sm"- aria-label="Download XLSX"- onClick={onDownload}- >- <HugeiconsIcon icon={Download01Icon} className="size-4" />- </Button>- </ToolbarTooltip>+ {toolbarActions}</>) : null}- {showUploadButton ? (+ {(showDownloadButton && onDownload) ||+ showUploadButton ||+ showNightRenderToggle ? (<><Separatororientation="vertical"className="mx-1 h-4 self-center"/>- <ToolbarTooltip label="Upload XLSX">- <Button- type="button"- variant="ghost"- size="icon-sm"- aria-label="Upload XLSX"- onClick={onUploadClick}- >- <HugeiconsIcon icon={Upload01Icon} className="size-4" />- </Button>- </ToolbarTooltip>- </>- ) : null}- {toolbarActions ? (- <>- <Separator- orientation="vertical"- className="mx-1 h-4 self-center"+ <WorkbookFileActionsMenu+ isDark={isDark}+ onDownload={onDownload}+ onIsDarkChange={onIsDarkChange}+ onUploadClick={onUploadClick}+ showDownloadButton={showDownloadButton}+ showNightRenderToggle={showNightRenderToggle}+ showUploadButton={showUploadButton}/>- {toolbarActions}</>) : null}</div>@@ -957,28 +984,20 @@ function WorkbookStandaloneToolbar({<div className="flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2"><TooltipProvider><div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1">+ {toolbarActions ? <>{toolbarActions}</> : null}{showUploadButton ? (- <ToolbarTooltip label="Upload XLSX">- <Button- type="button"- variant="ghost"- size="icon-sm"- aria-label="Upload XLSX"- onClick={onUploadClick}- >- <HugeiconsIcon icon={Upload01Icon} className="size-4" />- </Button>- </ToolbarTooltip>- ) : null}- {toolbarActions ? (<>- {showUploadButton ? (+ {toolbarActions ? (<Separatororientation="vertical"className="mx-1 h-4 self-center"/>) : null}- {toolbarActions}+ <WorkbookFileActionsMenu+ onUploadClick={onUploadClick}+ showDownloadButton={false}+ showUploadButton={showUploadButton}+ /></>) : null}</div>diff --git a/apps/v4/components/xlsx-editor-docs.tsx b/apps/v4/components/xlsx-editor-docs.tsxindex 62c0e05..dc6f570 100644--- a/apps/v4/components/xlsx-editor-docs.tsx+++ b/apps/v4/components/xlsx-editor-docs.tsx@@ -65,7 +65,7 @@ export function XlsxEditorExample() {}`const xlsxEditorSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n useXlsxViewer,\n useXlsxViewerController,\n useXlsxViewerEditing,\n useXlsxViewerSelection,\n useXlsxViewerZoom,\n XlsxViewer,\n XlsxViewerProvider,\n type XlsxTableHeaderMenuRenderProps,\n} from "@extend-ai/react-xlsx"\nimport {\n Add01Icon,\n Delete02Icon,\n Download01Icon,\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n Redo02Icon,\n Sun03Icon,\n Undo02Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport { Group, GroupSeparator, GroupText } from "@/components/ui/group"\nimport { Input } from "@/components/ui/input"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n renderXlsxScroller,\n WorkbookSheetTabs,\n WorkbookTableHeaderMenu,\n} from "@/components/ui/xlsx-viewer"\nimport { Separator } from "@/components/ui/separator"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\n\nconst XLSX_LOADING_INDICATOR_DELAY_MS = 300\nconst XLSX_EDITOR_READ_ONLY_THRESHOLD_BYTES = 5 * 1024 * 1024\nconst XLSX_DROPDOWN_Z_INDEX_CLASS = "z-40"\nconst ZOOM_OPTIONS = [50, 75, 100, 125, 150, 200, 400] as const\nconst XLSX_EDITOR_SELECT_CHROME_CLASS =\n "shadow-none before:shadow-none not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-none dark:not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-none"\nconst XLSX_EDITOR_FORMULA_INPUT_CHROME_CLASS =\n "has-disabled:opacity-100 dark:has-disabled:before:shadow-[0_-1px_--theme(--color-white/6%)]"\n\ntype UploadedWorkbook = {\n buffer: ArrayBuffer\n fileName: string\n identity: string\n}\n\nfunction formatWorkbookName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "workbook.xlsx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\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 EditorLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 w-full min-w-full place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction EditorToolbar({\n isDark,\n onIsDarkChange,\n onUploadClick,\n showNightRenderToggle,\n}: {\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n showNightRenderToggle: boolean\n}) {\n const {\n activeSheet,\n activeSheetIndex,\n canExport,\n exportXlsx,\n setActiveSheetIndex,\n sheets,\n } = useXlsxViewer()\n const { activeCell, activeCellAddress, selection } = useXlsxViewerSelection()\n const {\n addSheet,\n canRedo,\n canUndo,\n mergeSelection,\n readOnly,\n redo,\n removeActiveSheet,\n selectedFormula,\n selectedValue,\n setCellFormula,\n setCellValue,\n undo,\n unmergeSelection,\n } = useXlsxViewerEditing()\n const { canZoomIn, canZoomOut, setZoomScale, zoomIn, zoomOut, zoomScale } =\n useXlsxViewerZoom()\n const [formulaDraft, setFormulaDraft] = React.useState("")\n const [formulaFocused, setFormulaFocused] = React.useState(false)\n const formulaEditCellRef = React.useRef<typeof activeCell>(null)\n const formulaInitialValueRef = React.useRef("")\n const hasWorkbook = sheets.length > 0\n const hasSelection = Boolean(selection)\n const hasActiveCell = Boolean(activeCell)\n const currentZoom = Math.round(zoomScale)\n const selectedCellInputValue = selectedFormula || selectedValue\n\n React.useEffect(() => {\n if (formulaFocused) return\n setFormulaDraft(selectedCellInputValue)\n }, [formulaFocused, selectedCellInputValue, activeCellAddress])\n\n const commitFormula = React.useCallback(() => {\n const targetCell = formulaEditCellRef.current ?? activeCell\n if (!targetCell) return\n if (formulaDraft === formulaInitialValueRef.current) return\n\n if (formulaDraft.trim().startsWith("=")) {\n setCellFormula(targetCell, formulaDraft)\n } else {\n setCellValue(targetCell, formulaDraft)\n }\n formulaInitialValueRef.current = formulaDraft\n }, [activeCell, formulaDraft, setCellFormula, setCellValue])\n\n return (\n <div className="border-b bg-background">\n <div className="flex min-h-11 items-center justify-between gap-3 border-b px-3">\n <div className="min-w-0 flex-1" />\n <TooltipProvider>\n <div className="flex shrink-0 items-center gap-1">\n {showNightRenderToggle ? (\n <>\n <ToolbarTooltip\n label={isDark ? "Use light workbook" : "Use dark workbook"}\n >\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label={\n isDark ? "Use light workbook" : "Use dark workbook"\n }\n onClick={() => onIsDarkChange(!isDark)}\n >\n <HugeiconsIcon\n icon={isDark ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <ToolbarTooltip label="Export workbook">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Export workbook"\n disabled={!canExport}\n onClick={exportXlsx}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Upload XLSX">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Upload XLSX"\n onClick={onUploadClick}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </div>\n </TooltipProvider>\n </div>\n <TooltipProvider>\n <div className="flex min-h-12 flex-wrap items-center gap-2 border-b bg-background px-3 py-2">\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarTooltip label="Undo">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Undo"\n disabled={!canUndo || readOnly}\n onClick={undo}\n >\n <HugeiconsIcon icon={Undo02Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Redo">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Redo"\n disabled={!canRedo || readOnly}\n onClick={redo}\n >\n <HugeiconsIcon icon={Redo02Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </div>\n <div className="flex shrink-0 items-center gap-1">\n <Button\n type="button"\n variant="ghost"\n size="sm"\n disabled={!hasSelection || readOnly}\n onClick={mergeSelection}\n >\n Merge\n </Button>\n <Button\n type="button"\n variant="ghost"\n size="sm"\n disabled={!hasSelection || readOnly}\n onClick={unmergeSelection}\n >\n Unmerge\n </Button>\n </div>\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarTooltip label="Add sheet">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Add sheet"\n disabled={!hasWorkbook || readOnly}\n onClick={() => addSheet()}\n >\n <HugeiconsIcon icon={Add01Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Remove active sheet">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Remove active sheet"\n disabled={sheets.length <= 1 || readOnly}\n onClick={removeActiveSheet}\n >\n <HugeiconsIcon icon={Delete02Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <Select\n value={String(activeSheetIndex)}\n onValueChange={(value) => setActiveSheetIndex(Number(value))}\n disabled={!hasWorkbook}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[150px] min-w-[150px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Active sheet"\n >\n <SelectValue>{activeSheet?.name ?? "Sheet"}</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="start"\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {sheets.map((sheet, index) => (\n <SelectItem\n key={`${sheet.name}-${index}`}\n value={String(index)}\n >\n {sheet.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\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 disabled={!hasWorkbook || !canZoomOut}\n aria-label="Zoom out"\n onClick={zoomOut}\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <Select\n value={currentZoom.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={!hasWorkbook}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[84px] min-w-[84px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Zoom level"\n >\n <SelectValue>{currentZoom}%</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="end"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\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 disabled={!hasWorkbook || !canZoomIn}\n aria-label="Zoom in"\n onClick={zoomIn}\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </div>\n </div>\n <div className="border-t bg-background px-2 py-1">\n <Group className="w-full">\n <Input\n className={cn(\n "h-8 w-[92px] shrink-0 font-mono text-xs",\n XLSX_EDITOR_FORMULA_INPUT_CHROME_CLASS\n )}\n readOnly\n value={activeCellAddress ?? ""}\n />\n <GroupSeparator />\n <GroupText className="h-8 w-9 shrink-0 justify-center px-0 text-[11px] font-semibold italic">\n fx\n </GroupText>\n <GroupSeparator />\n <Input\n className={cn(\n "h-8 flex-1",\n XLSX_EDITOR_FORMULA_INPUT_CHROME_CLASS\n )}\n disabled={!hasActiveCell || readOnly}\n value={formulaDraft}\n onBlur={() => {\n commitFormula()\n setFormulaFocused(false)\n }}\n onChange={(event) => setFormulaDraft(event.target.value)}\n onFocus={() => {\n formulaEditCellRef.current = activeCell\n formulaInitialValueRef.current = formulaDraft\n setFormulaFocused(true)\n }}\n onKeyDown={(event) => {\n if (event.key === "Enter") {\n event.preventDefault()\n commitFormula()\n setFormulaFocused(false)\n }\n }}\n placeholder="Select a cell, then enter a value or formula"\n />\n </Group>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nexport function XlsxEditorSurface({\n className,\n isDark,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n rounded,\n showNightRenderToggle,\n workbookIdentity,\n}: {\n className?: string\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n rounded: boolean\n showNightRenderToggle: boolean\n workbookIdentity: string\n}) {\n const { error } = useXlsxViewer()\n\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className,\n rounded && "rounded-lg"\n )}\n >\n <EditorToolbar\n isDark={isDark}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n showNightRenderToggle={showNightRenderToggle}\n />\n <div className="flex min-h-0 flex-1 flex-col">\n <div className="min-h-0 flex-1 bg-muted/20">\n <XlsxViewer\n experimentalCanvas\n allowResizeInReadOnly\n className="h-full min-h-0 min-w-0"\n height="100%"\n isDark={isDark}\n readOnly={false}\n rounded={false}\n showDefaultToolbar={false}\n showImages\n fileTooLargeState={\n <div className="grid h-full w-full min-w-full place-items-center p-6">\n <div className="max-w-sm rounded-lg border bg-background p-4 text-sm">\n <p className="font-medium">File too large for editing</p>\n <p className="mt-1 text-muted-foreground">\n This workbook exceeds the editor limit. Download it or open\n a smaller file to make changes.\n </p>\n </div>\n </div>\n }\n loadingState={<EditorLoadingSurface />}\n renderScroller={renderXlsxScroller}\n errorState={\n <div className="grid h-full w-full min-w-full place-items-center p-6 text-sm text-destructive">\n {error?.message ?? "Unable to edit workbook."}\n </div>\n }\n renderTableHeaderMenu={renderTableHeaderMenu}\n />\n </div>\n <WorkbookSheetTabs workbookIdentity={workbookIdentity} />\n </div>\n </div>\n )\n}\n\nexport function XlsxEditorPreview({\n className,\n fileName,\n isDark,\n onIsDarkChange,\n rounded = false,\n src,\n}: {\n className?: string\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n rounded?: boolean\n src?: string\n}) {\n return (\n <XlsxEditorContent\n className={className}\n effectiveIsDark={isDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={onIsDarkChange}\n shouldRenderNightMode\n url={src}\n />\n )\n}\n\nfunction XlsxEditorContent({\n className,\n effectiveIsDark,\n fileName,\n rounded,\n setNightRenderEnabled,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n effectiveIsDark: boolean\n fileName?: string\n rounded: boolean\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const [uploadedWorkbook, setUploadedWorkbook] =\n React.useState<UploadedWorkbook | null>(null)\n const [workbookBuffer, setWorkbookBuffer] =\n React.useState<ArrayBuffer | null>(null)\n const [loadError, setLoadError] = React.useState<string>()\n const sourceFileName = React.useMemo(\n () =>\n url ? formatWorkbookName(fileName, url) : (fileName ?? "workbook.xlsx"),\n [fileName, url]\n )\n const displayFileName = uploadedWorkbook?.fileName ?? sourceFileName\n const workbookIdentity =\n uploadedWorkbook?.identity ?? `${url ?? "empty"}::${displayFileName}`\n const shouldShowLoadingSpinner = useDelayedLoadingIndicator(\n !workbookBuffer && !loadError && !uploadedWorkbook,\n XLSX_LOADING_INDICATOR_DELAY_MS\n )\n\n React.useEffect(() => {\n let isCurrent = true\n\n if (url) {\n setUploadedWorkbook(null)\n }\n\n async function loadWorkbook(): Promise<void> {\n if (!url) {\n setWorkbookBuffer(null)\n setLoadError(undefined)\n return\n }\n\n setWorkbookBuffer(null)\n setLoadError(undefined)\n\n try {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch XLSX (${response.status})`)\n }\n\n const nextWorkbookBuffer = await response.arrayBuffer()\n if (!isCurrent) return\n\n setWorkbookBuffer(nextWorkbookBuffer)\n } catch (error) {\n if (!isCurrent) return\n\n setLoadError(\n error instanceof Error ? error.message : "Unknown XLSX load error"\n )\n }\n }\n\n void loadWorkbook()\n\n return () => {\n isCurrent = false\n }\n }, [url])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n const buffer = await file.arrayBuffer()\n setWorkbookBuffer(null)\n setLoadError(undefined)\n setUploadedWorkbook({\n buffer,\n fileName: file.name,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n const activeBuffer = uploadedWorkbook?.buffer ?? workbookBuffer\n\n if (!url && !uploadedWorkbook) {\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <div className="grid min-h-0 flex-1 place-items-center bg-muted/30 p-4">\n <div className="max-w-md rounded-lg border bg-background p-4 text-center text-sm shadow-xs">\n <p className="font-medium">Upload a workbook to edit</p>\n <p className="mt-1 text-muted-foreground">\n Pass an XLSX URL with the <code>src</code> prop or upload a local\n file.\n </p>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (loadError && !activeBuffer) {\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <div className="grid min-h-0 flex-1 place-items-center bg-muted/30 p-4">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm">\n <p className="font-medium">Unable to edit workbook</p>\n <p className="mt-1 text-muted-foreground">{loadError}</p>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (!activeBuffer) {\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <EditorLoadingSurface showSpinner={shouldShowLoadingSpinner} />\n </div>\n )\n }\n\n return (\n <div className={cn("overflow-hidden", className)}>\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <XlsxWorkbookLoadedEditor\n fileName={displayFileName}\n isDark={effectiveIsDark}\n onIsDarkChange={setNightRenderEnabled}\n onUploadClick={() => fileInputRef.current?.click()}\n renderTableHeaderMenu={(props) => (\n <WorkbookTableHeaderMenu {...props} />\n )}\n rounded={rounded}\n showNightRenderToggle={shouldRenderNightMode}\n workbookBuffer={activeBuffer}\n workbookIdentity={workbookIdentity}\n />\n </div>\n )\n}\n\nfunction XlsxWorkbookLoadedEditor({\n fileName,\n isDark,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n rounded,\n showNightRenderToggle,\n workbookBuffer,\n workbookIdentity,\n}: {\n fileName: string\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n rounded: boolean\n showNightRenderToggle: boolean\n workbookBuffer: ArrayBuffer\n workbookIdentity: string\n}) {\n const controller = useXlsxViewerController(\n React.useMemo(\n () => ({\n allowResizeInReadOnly: true,\n file: workbookBuffer,\n fileName,\n readOnly: false,\n readOnlyAboveBytes: XLSX_EDITOR_READ_ONLY_THRESHOLD_BYTES,\n useWorker: true,\n }),\n [fileName, workbookBuffer]\n )\n )\n\n return (\n <XlsxViewerProvider controller={controller} isDark={isDark}>\n <XlsxEditorSurface\n isDark={isDark}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n renderTableHeaderMenu={renderTableHeaderMenu}\n rounded={rounded}\n showNightRenderToggle={showNightRenderToggle}\n workbookIdentity={workbookIdentity}\n />\n </XlsxViewerProvider>\n )\n}\n'+ "\"use client\"\n\nimport * as React from \"react\"\nimport {\n useXlsxViewer,\n useXlsxViewerController,\n useXlsxViewerEditing,\n useXlsxViewerSelection,\n useXlsxViewerZoom,\n XlsxViewer,\n XlsxViewerProvider,\n type XlsxTableHeaderMenuRenderProps,\n} from \"@extend-ai/react-xlsx\"\nimport {\n Add01Icon,\n Delete02Icon,\n Download01Icon,\n MinusSignCircleIcon,\n Moon02Icon,\n MoreHorizontalIcon,\n PlusSignCircleIcon,\n Redo02Icon,\n Sun03Icon,\n Undo02Icon,\n Upload01Icon,\n} from \"@hugeicons/core-free-icons\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuTrigger,\n} from \"@/components/ui/dropdown-menu\"\nimport { Group, GroupSeparator, GroupText } from \"@/components/ui/group\"\nimport { Input } from \"@/components/ui/input\"\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 {\n renderXlsxScroller,\n WorkbookSheetTabs,\n WorkbookTableHeaderMenu,\n} from \"@/components/ui/xlsx-viewer\"\n\nconst XLSX_LOADING_INDICATOR_DELAY_MS = 300\nconst XLSX_EDITOR_READ_ONLY_THRESHOLD_BYTES = 5 * 1024 * 1024\nconst XLSX_DROPDOWN_Z_INDEX_CLASS = \"z-40\"\nconst ZOOM_OPTIONS = [50, 75, 100, 125, 150, 200, 400] as const\nconst XLSX_EDITOR_SELECT_CHROME_CLASS =\n \"shadow-none before:shadow-none not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-none dark:not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-none\"\nconst XLSX_EDITOR_FORMULA_INPUT_CHROME_CLASS =\n \"has-disabled:opacity-100 dark:has-disabled:before:shadow-[0_-1px_--theme(--color-white/6%)]\"\n\ntype UploadedWorkbook = {\n buffer: ArrayBuffer\n fileName: string\n identity: string\n}\n\nfunction formatWorkbookName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split(\"?\")[0] ?? \"\"\n const rawName = pathname.split(\"/\").pop() ?? \"workbook.xlsx\"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\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 EditorLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className=\"grid h-full min-h-52 w-full min-w-full place-items-center bg-transparent\">\n {showSpinner ? <Spinner className=\"size-4\" /> : null}\n </div>\n )\n}\n\nfunction EditorFileActionsMenu({\n canExport,\n exportXlsx,\n onUploadClick,\n}: {\n canExport: boolean\n exportXlsx: () => void\n onUploadClick: () => void\n}) {\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Open workbook actions\"\n >\n <HugeiconsIcon icon={MoreHorizontalIcon} className=\"size-4\" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align=\"end\"\n className={cn(\"w-40\", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <DropdownMenuItem disabled={!canExport} onClick={exportXlsx}>\n <HugeiconsIcon icon={Download01Icon} className=\"size-4\" />\n Download\n </DropdownMenuItem>\n <DropdownMenuItem onClick={onUploadClick}>\n <HugeiconsIcon icon={Upload01Icon} className=\"size-4\" />\n Upload\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction EditorToolbar({\n isDark,\n onIsDarkChange,\n onUploadClick,\n showNightRenderToggle,\n}: {\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n showNightRenderToggle: boolean\n}) {\n const {\n activeSheet,\n activeSheetIndex,\n canExport,\n exportXlsx,\n setActiveSheetIndex,\n sheets,\n } = useXlsxViewer()\n const { activeCell, activeCellAddress, selection } = useXlsxViewerSelection()\n const {\n addSheet,\n canRedo,\n canUndo,\n mergeSelection,\n readOnly,\n redo,\n removeActiveSheet,\n selectedFormula,\n selectedValue,\n setCellFormula,\n setCellValue,\n undo,\n unmergeSelection,\n } = useXlsxViewerEditing()\n const { canZoomIn, canZoomOut, setZoomScale, zoomIn, zoomOut, zoomScale } =\n useXlsxViewerZoom()\n const [formulaDraft, setFormulaDraft] = React.useState(\"\")\n const [formulaFocused, setFormulaFocused] = React.useState(false)\n const formulaEditCellRef = React.useRef<typeof activeCell>(null)\n const formulaInitialValueRef = React.useRef(\"\")\n const hasWorkbook = sheets.length > 0\n const hasSelection = Boolean(selection)\n const hasActiveCell = Boolean(activeCell)\n const currentZoom = Math.round(zoomScale)\n const selectedCellInputValue = selectedFormula || selectedValue\n\n React.useEffect(() => {\n if (formulaFocused) return\n setFormulaDraft(selectedCellInputValue)\n }, [formulaFocused, selectedCellInputValue, activeCellAddress])\n\n const commitFormula = React.useCallback(() => {\n const targetCell = formulaEditCellRef.current ?? activeCell\n if (!targetCell) return\n if (formulaDraft === formulaInitialValueRef.current) return\n\n if (formulaDraft.trim().startsWith(\"=\")) {\n setCellFormula(targetCell, formulaDraft)\n } else {\n setCellValue(targetCell, formulaDraft)\n }\n formulaInitialValueRef.current = formulaDraft\n }, [activeCell, formulaDraft, setCellFormula, setCellValue])\n\n return (\n <div className=\"border-b bg-background\">\n <div className=\"flex min-h-11 items-center justify-between gap-3 border-b px-3\">\n <div className=\"min-w-0 flex-1\" />\n <TooltipProvider>\n <div className=\"flex shrink-0 items-center gap-1\">\n {showNightRenderToggle ? (\n <>\n <ToolbarTooltip\n label={isDark ? \"Use light workbook\" : \"Use dark workbook\"}\n >\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label={\n isDark ? \"Use light workbook\" : \"Use dark workbook\"\n }\n onClick={() => onIsDarkChange(!isDark)}\n >\n <HugeiconsIcon\n icon={isDark ? Sun03Icon : Moon02Icon}\n className=\"size-4\"\n />\n </Button>\n </ToolbarTooltip>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n </>\n ) : null}\n <EditorFileActionsMenu\n canExport={canExport}\n exportXlsx={exportXlsx}\n onUploadClick={onUploadClick}\n />\n </div>\n </TooltipProvider>\n </div>\n <TooltipProvider>\n <div className=\"flex min-h-12 flex-wrap items-center gap-2 border-b bg-background px-3 py-2\">\n <div className=\"flex shrink-0 items-center gap-1\">\n <ToolbarTooltip label=\"Undo\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Undo\"\n disabled={!canUndo || readOnly}\n onClick={undo}\n >\n <HugeiconsIcon icon={Undo02Icon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label=\"Redo\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Redo\"\n disabled={!canRedo || readOnly}\n onClick={redo}\n >\n <HugeiconsIcon icon={Redo02Icon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n </div>\n <div className=\"flex shrink-0 items-center gap-1\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n disabled={!hasSelection || readOnly}\n onClick={mergeSelection}\n >\n Merge\n </Button>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n disabled={!hasSelection || readOnly}\n onClick={unmergeSelection}\n >\n Unmerge\n </Button>\n </div>\n <div className=\"flex shrink-0 items-center gap-1\">\n <ToolbarTooltip label=\"Add sheet\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Add sheet\"\n disabled={!hasWorkbook || readOnly}\n onClick={() => addSheet()}\n >\n <HugeiconsIcon icon={Add01Icon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label=\"Remove active sheet\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Remove active sheet\"\n disabled={sheets.length <= 1 || readOnly}\n onClick={removeActiveSheet}\n >\n <HugeiconsIcon icon={Delete02Icon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n <Select\n value={String(activeSheetIndex)}\n onValueChange={(value) => setActiveSheetIndex(Number(value))}\n disabled={!hasWorkbook}\n >\n <SelectTrigger\n size=\"sm\"\n className={cn(\n \"w-[150px] min-w-[150px]\",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label=\"Active sheet\"\n >\n <SelectValue>{activeSheet?.name ?? \"Sheet\"}</SelectValue>\n </SelectTrigger>\n <SelectContent\n align=\"start\"\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {sheets.map((sheet, index) => (\n <SelectItem\n key={`${sheet.name}-${index}`}\n value={String(index)}\n >\n {sheet.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\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 disabled={!hasWorkbook || !canZoomOut}\n aria-label=\"Zoom out\"\n onClick={zoomOut}\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n <Select\n value={currentZoom.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={!hasWorkbook}\n modal={false}\n >\n <SelectTrigger\n size=\"sm\"\n className={cn(\n \"w-[84px] min-w-[84px]\",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label=\"Zoom level\"\n >\n <SelectValue>{currentZoom}%</SelectValue>\n </SelectTrigger>\n <SelectContent\n align=\"end\"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\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 disabled={!hasWorkbook || !canZoomIn}\n aria-label=\"Zoom in\"\n onClick={zoomIn}\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n </div>\n </div>\n <div className=\"border-t bg-background px-2 py-1\">\n <Group className=\"w-full\">\n <Input\n className={cn(\n \"h-8 w-[92px] shrink-0 font-mono text-xs\",\n XLSX_EDITOR_FORMULA_INPUT_CHROME_CLASS\n )}\n readOnly\n value={activeCellAddress ?? \"\"}\n />\n <GroupSeparator />\n <GroupText className=\"h-8 w-9 shrink-0 justify-center px-0 text-[11px] font-semibold italic\">\n fx\n </GroupText>\n <GroupSeparator />\n <Input\n className={cn(\n \"h-8 flex-1\",\n XLSX_EDITOR_FORMULA_INPUT_CHROME_CLASS\n )}\n disabled={!hasActiveCell || readOnly}\n value={formulaDraft}\n onBlur={() => {\n commitFormula()\n setFormulaFocused(false)\n }}\n onChange={(event) => setFormulaDraft(event.target.value)}\n onFocus={() => {\n formulaEditCellRef.current = activeCell\n formulaInitialValueRef.current = formulaDraft\n setFormulaFocused(true)\n }}\n onKeyDown={(event) => {\n if (event.key === \"Enter\") {\n event.preventDefault()\n commitFormula()\n setFormulaFocused(false)\n }\n }}\n placeholder=\"Select a cell, then enter a value or formula\"\n />\n </Group>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nexport function XlsxEditorSurface({\n className,\n isDark,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n showNightRenderToggle,\n workbookIdentity,\n}: {\n className?: string\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n showNightRenderToggle: boolean\n workbookIdentity: string\n}) {\n const { error } = useXlsxViewer()\n\n return (\n <div\n className={cn(\n \"flex h-[640px] min-h-0 flex-col overflow-hidden bg-background\",\n className\n )}\n >\n <EditorToolbar\n isDark={isDark}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n showNightRenderToggle={showNightRenderToggle}\n />\n <div className=\"flex min-h-0 flex-1 flex-col\">\n <div className=\"min-h-0 flex-1 bg-muted/20\">\n <XlsxViewer\n experimentalCanvas\n allowResizeInReadOnly\n className=\"h-full min-h-0 min-w-0\"\n height=\"100%\"\n isDark={isDark}\n readOnly={false}\n rounded={false}\n showDefaultToolbar={false}\n showImages\n fileTooLargeState={\n <div className=\"grid h-full w-full min-w-full place-items-center p-6\">\n <div className=\"max-w-sm rounded-lg border bg-background p-4 text-sm\">\n <p className=\"font-medium\">File too large for editing</p>\n <p className=\"mt-1 text-muted-foreground\">\n This workbook exceeds the editor limit. Download it or open\n a smaller file to make changes.\n </p>\n </div>\n </div>\n }\n loadingState={<EditorLoadingSurface />}\n renderScroller={renderXlsxScroller}\n errorState={\n <div className=\"grid h-full w-full min-w-full place-items-center p-6 text-sm text-destructive\">\n {error?.message ?? \"Unable to edit workbook.\"}\n </div>\n }\n renderTableHeaderMenu={renderTableHeaderMenu}\n />\n </div>\n <WorkbookSheetTabs workbookIdentity={workbookIdentity} />\n </div>\n </div>\n )\n}\n\nexport function XlsxEditorPreview({\n className,\n fileName,\n isDark,\n onIsDarkChange,\n src,\n}: {\n className?: string\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n src?: string\n}) {\n return (\n <XlsxEditorContent\n className={className}\n effectiveIsDark={isDark}\n fileName={fileName}\n setNightRenderEnabled={onIsDarkChange}\n shouldRenderNightMode\n url={src}\n />\n )\n}\n\nfunction XlsxEditorContent({\n className,\n effectiveIsDark,\n fileName,\n setNightRenderEnabled,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n effectiveIsDark: boolean\n fileName?: string\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const [uploadedWorkbook, setUploadedWorkbook] =\n React.useState<UploadedWorkbook | null>(null)\n const [workbookBuffer, setWorkbookBuffer] =\n React.useState<ArrayBuffer | null>(null)\n const [loadError, setLoadError] = React.useState<string>()\n const sourceFileName = React.useMemo(\n () =>\n url ? formatWorkbookName(fileName, url) : (fileName ?? \"workbook.xlsx\"),\n [fileName, url]\n )\n const displayFileName = uploadedWorkbook?.fileName ?? sourceFileName\n const workbookIdentity =\n uploadedWorkbook?.identity ?? `${url ?? \"empty\"}::${displayFileName}`\n const shouldShowLoadingSpinner = useDelayedLoadingIndicator(\n !workbookBuffer && !loadError && !uploadedWorkbook,\n XLSX_LOADING_INDICATOR_DELAY_MS\n )\n\n React.useEffect(() => {\n let isCurrent = true\n\n if (url) {\n setUploadedWorkbook(null)\n }\n\n async function loadWorkbook(): Promise<void> {\n if (!url) {\n setWorkbookBuffer(null)\n setLoadError(undefined)\n return\n }\n\n setWorkbookBuffer(null)\n setLoadError(undefined)\n\n try {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch XLSX (${response.status})`)\n }\n\n const nextWorkbookBuffer = await response.arrayBuffer()\n if (!isCurrent) return\n\n setWorkbookBuffer(nextWorkbookBuffer)\n } catch (error) {\n if (!isCurrent) return\n\n setLoadError(\n error instanceof Error ? error.message : \"Unknown XLSX load error\"\n )\n }\n }\n\n void loadWorkbook()\n\n return () => {\n isCurrent = false\n }\n }, [url])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = \"\"\n\n if (!file) return\n\n const buffer = await file.arrayBuffer()\n setWorkbookBuffer(null)\n setLoadError(undefined)\n setUploadedWorkbook({\n buffer,\n fileName: file.name,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n const activeBuffer = uploadedWorkbook?.buffer ?? workbookBuffer\n\n if (!url && !uploadedWorkbook) {\n return (\n <div\n className={cn(\n \"flex h-[640px] min-h-0 flex-col overflow-hidden bg-background\",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel\"\n className=\"hidden\"\n onChange={handleUpload}\n />\n <div className=\"grid min-h-0 flex-1 place-items-center bg-muted/30 p-4\">\n <div className=\"max-w-md rounded-lg border bg-background p-4 text-center text-sm shadow-xs\">\n <p className=\"font-medium\">Upload a workbook to edit</p>\n <p className=\"mt-1 text-muted-foreground\">\n Pass an XLSX URL with the <code>src</code> prop or upload a local\n file.\n </p>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n className=\"mt-4\"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className=\"size-4\" />\n Upload XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (loadError && !activeBuffer) {\n return (\n <div\n className={cn(\n \"flex h-[640px] min-h-0 flex-col overflow-hidden bg-background\",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel\"\n className=\"hidden\"\n onChange={handleUpload}\n />\n <div className=\"grid min-h-0 flex-1 place-items-center bg-muted/30 p-4\">\n <div className=\"max-w-md rounded-lg border bg-background p-4 text-sm\">\n <p className=\"font-medium\">Unable to edit workbook</p>\n <p className=\"mt-1 text-muted-foreground\">{loadError}</p>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n className=\"mt-4\"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className=\"size-4\" />\n Upload XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (!activeBuffer) {\n return (\n <div\n className={cn(\n \"flex h-[640px] min-h-0 flex-col overflow-hidden bg-background\",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel\"\n className=\"hidden\"\n onChange={handleUpload}\n />\n <EditorLoadingSurface showSpinner={shouldShowLoadingSpinner} />\n </div>\n )\n }\n\n return (\n <div className={cn(\"overflow-hidden\", className)}>\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel\"\n className=\"hidden\"\n onChange={handleUpload}\n />\n <XlsxWorkbookLoadedEditor\n fileName={displayFileName}\n isDark={effectiveIsDark}\n onIsDarkChange={setNightRenderEnabled}\n onUploadClick={() => fileInputRef.current?.click()}\n renderTableHeaderMenu={(props) => (\n <WorkbookTableHeaderMenu {...props} />\n )}\n showNightRenderToggle={shouldRenderNightMode}\n workbookBuffer={activeBuffer}\n workbookIdentity={workbookIdentity}\n />\n </div>\n )\n}\n\nfunction XlsxWorkbookLoadedEditor({\n fileName,\n isDark,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n showNightRenderToggle,\n workbookBuffer,\n workbookIdentity,\n}: {\n fileName: string\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n showNightRenderToggle: boolean\n workbookBuffer: ArrayBuffer\n workbookIdentity: string\n}) {\n const controller = useXlsxViewerController(\n React.useMemo(\n () => ({\n allowResizeInReadOnly: true,\n file: workbookBuffer,\n fileName,\n readOnly: false,\n readOnlyAboveBytes: XLSX_EDITOR_READ_ONLY_THRESHOLD_BYTES,\n useWorker: true,\n }),\n [fileName, workbookBuffer]\n )\n )\n\n return (\n <XlsxViewerProvider controller={controller} isDark={isDark}>\n <XlsxEditorSurface\n isDark={isDark}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n renderTableHeaderMenu={renderTableHeaderMenu}\n showNightRenderToggle={showNightRenderToggle}\n workbookIdentity={workbookIdentity}\n />\n </XlsxViewerProvider>\n )\n}\n"export function XlsxEditorSource() {return (diff --git a/apps/v4/components/xlsx-viewer-docs.tsx b/apps/v4/components/xlsx-viewer-docs.tsxindex f4203a5..2bf57dd 100644--- a/apps/v4/components/xlsx-viewer-docs.tsx+++ b/apps/v4/components/xlsx-viewer-docs.tsx@@ -36,7 +36,7 @@ export function XlsxViewerDemo() {return (<divdata-slot="component-preview"- className="group relative mt-4 mb-12 flex flex-col overflow-hidden rounded-xl border"+ className="group relative mt-4 mb-12 flex flex-col overflow-hidden border rounded-xl"><XlsxViewerPreviewsrc={SAMPLE_XLSX_URL}@@ -65,7 +65,7 @@ export function XlsxViewerExample() {}`const xlsxViewerSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n useXlsxViewer,\n useXlsxViewerController,\n useXlsxViewerThumbnails,\n useXlsxViewerZoom,\n XlsxViewer,\n XlsxViewerProvider,\n type XlsxCellAddress,\n type XlsxScrollerRenderProps,\n type XlsxSheetData,\n type XlsxTableHeaderMenuRenderProps,\n type XlsxViewerController,\n} from "@extend-ai/react-xlsx"\nimport {\n ArrowLeft01Icon,\n ArrowRight01Icon,\n Download01Icon,\n MinusSignCircleIcon,\n Moon02Icon,\n MoreHorizontalIcon,\n PlusSignCircleIcon,\n Search01Icon,\n Sun03Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { createPortal } from "react-dom"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuRadioGroup,\n DropdownMenuRadioItem,\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 { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\n\nconst XLSX_LOADING_INDICATOR_DELAY_MS = 300\nconst XLSX_DROPDOWN_Z_INDEX_CLASS = "z-40"\nconst XLSX_SEARCH_BATCH_ROW_COUNT = 500\nconst XLSX_SEARCH_DEBOUNCE_MS = 300\nconst XLSX_GRID_HEADER_HEIGHT = 24\nconst XLSX_GRID_ROW_HEADER_WIDTH = 40\nconst XLSX_MAX_FILE_SIZE_BYTES = 50 * 1024 * 1024\nconst ZOOM_OPTIONS = [10, 25, 50, 75, 100, 125, 150, 175, 200, 400] as const\n\n// Stable reference so the thumbnails memo isn\'t invalidated on every render\n// (e.g. by selection changes), which would recompute every sheet thumbnail.\nconst XLSX_SHEET_TAB_THUMBNAIL_OPTIONS = {\n resolution: {\n maxHeight: 360,\n maxWidth: 560,\n },\n} as const\n\ntype UploadedWorkbook = {\n buffer: ArrayBuffer\n fileName: string\n identity: string\n}\n\ntype XlsxSearchResult = {\n cell: XlsxCellAddress\n displayValue: string\n formula?: string\n sheetIndex: number\n sheetName: string\n workbookSheetIndex: number\n}\n\ntype XlsxBatchCell = {\n col?: unknown\n formula?: unknown\n value?: unknown\n}\n\ntype XlsxBatchRow = {\n cells?: unknown\n index?: unknown\n}\n\nfunction formatWorkbookName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "workbook.xlsx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction ensureWorkbookExtension(fileName: string) {\n const lowerFileName = fileName.toLowerCase()\n return lowerFileName.endsWith(".xlsx") || lowerFileName.endsWith(".xls")\n ? fileName\n : `${fileName}.xlsx`\n}\n\nfunction downloadWorkbookBuffer(buffer: ArrayBuffer, fileName: string) {\n const resolvedFileName = ensureWorkbookExtension(fileName)\n const blob = new Blob([buffer], {\n type: resolvedFileName.toLowerCase().endsWith(".xls")\n ? "application/vnd.ms-excel"\n : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",\n })\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n\n anchor.href = url\n anchor.download = resolvedFileName\n anchor.rel = "noopener"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nfunction normalizeSearchText(value: unknown) {\n return typeof value === "string"\n ? value\n : value === null || value === undefined\n ? ""\n : String(value)\n}\n\nfunction cellValueToSearchText(value: unknown) {\n if (!value || typeof value !== "object") return normalizeSearchText(value)\n\n const record = value as {\n asBoolean?: () => boolean | null\n asError?: () => string | null\n asNumber?: () => number | null\n asText?: () => string | null\n is_boolean?: boolean\n is_empty?: boolean\n is_error?: boolean\n is_number?: boolean\n is_text?: boolean\n }\n\n if (record.is_empty) return ""\n if (record.is_error) return record.asError?.() ?? ""\n if (record.is_text) return record.asText?.() ?? ""\n if (record.is_number) return normalizeSearchText(record.asNumber?.())\n if (record.is_boolean) return record.asBoolean?.() ? "TRUE" : "FALSE"\n\n return normalizeSearchText(value)\n}\n\nfunction getCellSearchText(\n controller: XlsxViewerController,\n sheet: XlsxSheetData,\n row: number,\n col: number\n) {\n const worksheet = controller.workbook?.getSheet(sheet.workbookSheetIndex)\n if (!worksheet) return { displayValue: "", formula: "" }\n\n const formula = worksheet.getFormulaAt(row, col) ?? ""\n const cachedFormulaValue = formula\n ? sheet.cachedFormulaValues[cellAddressToA1({ row, col })]\n : undefined\n const formatted = worksheet.getFormattedValueAt(row, col)\n\n if (\n formatted &&\n !(formula && cachedFormulaValue !== undefined && formatted.startsWith("#"))\n ) {\n return { displayValue: formatted, formula }\n }\n\n const calculated = worksheet.getCalculatedValueAt(row, col)\n const displayValue =\n formula && cachedFormulaValue !== undefined && calculated.is_error\n ? cachedFormulaValue\n : cellValueToSearchText(calculated)\n\n return { displayValue, formula }\n}\n\nfunction getBatchRows(rows: unknown): XlsxBatchRow[] {\n return Array.isArray(rows) ? (rows as XlsxBatchRow[]) : []\n}\n\nfunction getBatchCells(row: XlsxBatchRow): XlsxBatchCell[] {\n return Array.isArray(row.cells) ? (row.cells as XlsxBatchCell[]) : []\n}\n\nfunction cellMatchesQuery(\n displayValue: string,\n formula: string,\n query: string\n) {\n return (\n displayValue.toLowerCase().includes(query) ||\n formula.toLowerCase().includes(query)\n )\n}\n\nfunction cellAddressToA1({ col, row }: XlsxCellAddress) {\n let columnNumber = col + 1\n let columnName = ""\n\n while (columnNumber > 0) {\n const remainder = (columnNumber - 1) % 26\n columnName = String.fromCharCode(65 + remainder) + columnName\n columnNumber = Math.floor((columnNumber - 1) / 26)\n }\n\n return `${columnName}${row + 1}`\n}\n\nasync function findXlsxSearchResults(\n controller: XlsxViewerController,\n rawQuery: string\n) {\n const query = rawQuery.trim().toLowerCase()\n if (!query) return []\n\n const results: XlsxSearchResult[] = []\n\n for (const [sheetIndex, sheet] of controller.sheets.entries()) {\n const startRow = Math.max(0, sheet.minUsedRow)\n const endRow = Math.max(startRow, sheet.maxUsedRow)\n const visibleCols = sheet.visibleCols.filter(\n (col) => col >= sheet.minUsedCol && col <= sheet.maxUsedCol\n )\n const visibleRowSet = new Set(sheet.visibleRows)\n const visibleColSet = new Set(visibleCols)\n\n if (!visibleCols.length || sheet.maxUsedRow < sheet.minUsedRow) continue\n\n const worksheet = controller.workbook?.getSheet(sheet.workbookSheetIndex)\n const worksheetWithBatch = worksheet as\n | {\n getRowsBatch?: (\n startRow: number,\n rowCount: number,\n options?: Record<string, unknown>\n ) => unknown\n }\n | undefined\n\n for (\n let batchStartRow = startRow;\n batchStartRow <= endRow;\n batchStartRow += XLSX_SEARCH_BATCH_ROW_COUNT\n ) {\n const rowCount = Math.min(\n XLSX_SEARCH_BATCH_ROW_COUNT,\n endRow - batchStartRow + 1\n )\n const rows = controller.getRowsBatchAsync\n ? await controller.getRowsBatchAsync(\n sheet.workbookSheetIndex,\n batchStartRow,\n rowCount\n )\n : worksheetWithBatch?.getRowsBatch?.(batchStartRow, rowCount, {\n includeFormulas: true,\n useFormattedValues: true,\n })\n\n if (rows) {\n for (const rowEntry of getBatchRows(rows)) {\n const row = Number(rowEntry.index)\n if (!Number.isInteger(row) || !visibleRowSet.has(row)) {\n continue\n }\n\n for (const cellEntry of getBatchCells(rowEntry)) {\n const col = Number(cellEntry.col)\n if (!Number.isInteger(col) || !visibleColSet.has(col)) continue\n\n const displayValue = normalizeSearchText(cellEntry.value)\n const formula = normalizeSearchText(cellEntry.formula)\n\n if (!cellMatchesQuery(displayValue, formula, query)) continue\n\n results.push({\n cell: { row, col },\n displayValue,\n formula,\n sheetIndex,\n sheetName: sheet.name,\n workbookSheetIndex: sheet.workbookSheetIndex,\n })\n }\n }\n continue\n }\n\n if (!worksheet) continue\n\n const batchEndRow = batchStartRow + rowCount - 1\n for (const row of sheet.visibleRows) {\n if (row < batchStartRow || row > batchEndRow) continue\n\n for (const col of visibleCols) {\n const { displayValue, formula } = getCellSearchText(\n controller,\n sheet,\n row,\n col\n )\n\n if (!cellMatchesQuery(displayValue, formula, query)) continue\n\n results.push({\n cell: { row, col },\n displayValue,\n formula,\n sheetIndex,\n sheetName: sheet.name,\n workbookSheetIndex: sheet.workbookSheetIndex,\n })\n }\n }\n }\n }\n\n return results\n}\n\nfunction sumAxisBefore(values: number[], endIndex: number, zoomFactor: number) {\n let total = 0\n for (let index = 0; index < endIndex; index += 1) {\n total += (values[index] ?? 0) * zoomFactor\n }\n return total\n}\n\nfunction scrollXlsxCellIntoView({\n controller,\n result,\n viewport,\n}: {\n controller: XlsxViewerController\n result: XlsxSearchResult\n viewport: HTMLDivElement | null\n}) {\n if (!viewport) return\n\n const sheet = controller.sheets[result.sheetIndex]\n if (!sheet) return\n\n const rowIndex = sheet.visibleRows.indexOf(result.cell.row)\n const colIndex = sheet.visibleCols.indexOf(result.cell.col)\n if (rowIndex < 0 || colIndex < 0) return\n\n const zoomFactor = Math.max(0.1, controller.zoomScale / 100)\n const headerHeight = XLSX_GRID_HEADER_HEIGHT * zoomFactor\n const rowHeaderWidth = XLSX_GRID_ROW_HEADER_WIDTH * zoomFactor\n const rowStart =\n headerHeight + sumAxisBefore(sheet.rowHeights, rowIndex, zoomFactor)\n const colStart =\n rowHeaderWidth + sumAxisBefore(sheet.colWidths, colIndex, zoomFactor)\n const rowHeight =\n (sheet.rowHeights[rowIndex] ?? sheet.defaultRowHeightPx) * zoomFactor\n const colWidth =\n (sheet.colWidths[colIndex] ?? sheet.defaultColWidthPx) * zoomFactor\n const rowEnd = rowStart + rowHeight\n const colEnd = colStart + colWidth\n let nextTop = viewport.scrollTop\n let nextLeft = viewport.scrollLeft\n const visibleTop = viewport.scrollTop + headerHeight\n const visibleLeft = viewport.scrollLeft + rowHeaderWidth\n const visibleBottom = viewport.scrollTop + viewport.clientHeight\n const visibleRight = viewport.scrollLeft + viewport.clientWidth\n\n if (rowStart < visibleTop) {\n nextTop = rowStart - headerHeight\n } else if (rowEnd > visibleBottom) {\n nextTop = rowEnd - viewport.clientHeight\n }\n\n if (colStart < visibleLeft) {\n nextLeft = colStart - rowHeaderWidth\n } else if (colEnd > visibleRight) {\n nextLeft = colEnd - viewport.clientWidth\n }\n\n viewport.scrollTo({\n left: Math.max(0, nextLeft),\n top: Math.max(0, nextTop),\n behavior: "auto",\n })\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\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 ViewerLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 w-full min-w-full place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nexport function renderXlsxScroller({\n children,\n viewportProps,\n}: XlsxScrollerRenderProps) {\n return (\n <ScrollArea\n className="h-full min-h-0 w-full min-w-0 flex-1"\n viewportProps={viewportProps}\n >\n {children}\n </ScrollArea>\n )\n}\n\nexport function WorkbookTableHeaderMenu({\n direction,\n sortAscending,\n sortDescending,\n triggerIcon,\n triggerProps,\n}: XlsxTableHeaderMenuRenderProps) {\n const [open, setOpen] = React.useState(false)\n\n return (\n <DropdownMenu open={open} onOpenChange={setOpen}>\n <DropdownMenuTrigger asChild>\n <Button\n {...triggerProps}\n type="button"\n variant="ghost"\n size="icon-sm"\n className={cn("size-6 rounded-sm", triggerProps.className)}\n aria-label="Column menu"\n >\n {triggerIcon ? (\n triggerIcon\n ) : (\n <HugeiconsIcon icon={MoreHorizontalIcon} className="size-3.5" />\n )}\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align="end"\n className={cn("w-40", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <DropdownMenuRadioGroup\n value={direction ?? ""}\n onValueChange={(value) => {\n if (value === "ascending") {\n sortAscending()\n } else {\n sortDescending()\n }\n setOpen(false)\n }}\n >\n <DropdownMenuRadioItem value="ascending">\n Sort ascending\n </DropdownMenuRadioItem>\n <DropdownMenuRadioItem value="descending">\n Sort descending\n </DropdownMenuRadioItem>\n </DropdownMenuRadioGroup>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction WorkbookSearchPopover({\n viewportRef,\n workbookIdentity,\n}: {\n viewportRef: React.RefObject<HTMLDivElement | null>\n workbookIdentity: string\n}) {\n const controller = useXlsxViewer()\n const [searchDraft, setSearchDraft] = React.useState("")\n const [searchQuery, setSearchQuery] = React.useState("")\n const [searchResults, setSearchResults] = React.useState<XlsxSearchResult[]>(\n []\n )\n const [activeResultIndex, setActiveResultIndex] = React.useState(0)\n const [isSearching, setIsSearching] = React.useState(false)\n const controllerRef = React.useRef(controller)\n const searchRequestIdRef = React.useRef(0)\n const appliedResultKeyRef = React.useRef("")\n const activeResult = searchResults[activeResultIndex] ?? null\n const activeResultKey = activeResult\n ? `${activeResult.workbookSheetIndex}:${activeResult.cell.row}:${activeResult.cell.col}`\n : ""\n const controlsDisabled =\n controller.isLoading ||\n Boolean(controller.error) ||\n !controller.sheets.length\n const hasActiveQuery = Boolean(searchQuery.trim())\n const resultLabel = isSearching\n ? "Searching"\n : !hasActiveQuery\n ? "No search"\n : searchResults.length\n ? `${activeResultIndex + 1} / ${searchResults.length}`\n : "No results"\n\n React.useEffect(() => {\n controllerRef.current = controller\n }, [controller])\n\n const runSearch = React.useCallback((rawQuery: string) => {\n const nextQuery = rawQuery.trim()\n const requestId = searchRequestIdRef.current + 1\n searchRequestIdRef.current = requestId\n appliedResultKeyRef.current = ""\n setSearchQuery(nextQuery)\n setActiveResultIndex(0)\n\n if (!nextQuery) {\n setSearchResults([])\n setIsSearching(false)\n return\n }\n\n setIsSearching(true)\n void findXlsxSearchResults(controllerRef.current, nextQuery)\n .then((nextResults) => {\n if (searchRequestIdRef.current !== requestId) return\n setSearchResults(nextResults)\n })\n .catch(() => {\n if (searchRequestIdRef.current !== requestId) return\n setSearchResults([])\n })\n .finally(() => {\n if (searchRequestIdRef.current !== requestId) return\n setIsSearching(false)\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 }, XLSX_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 setSearchResults([])\n setActiveResultIndex(0)\n setIsSearching(false)\n appliedResultKeyRef.current = ""\n controller.clearSelection()\n }, [controller])\n\n const goToRelativeResult = React.useCallback(\n (direction: 1 | -1) => {\n if (!searchResults.length) return\n\n setActiveResultIndex((currentIndex) => {\n return (\n (currentIndex + direction + searchResults.length) %\n searchResults.length\n )\n })\n },\n [searchResults.length]\n )\n\n React.useEffect(() => {\n searchRequestIdRef.current += 1\n setSearchDraft("")\n setSearchQuery("")\n setSearchResults([])\n setActiveResultIndex(0)\n setIsSearching(false)\n appliedResultKeyRef.current = ""\n }, [workbookIdentity])\n\n React.useEffect(() => {\n if (!activeResult) return\n\n if (controller.activeSheetIndex !== activeResult.sheetIndex) {\n appliedResultKeyRef.current = ""\n controller.setActiveSheetIndex(activeResult.sheetIndex)\n return\n }\n\n if (appliedResultKeyRef.current === activeResultKey) return\n appliedResultKeyRef.current = activeResultKey\n controller.selectCell(activeResult.cell)\n\n const frame = window.requestAnimationFrame(() => {\n scrollXlsxCellIntoView({\n controller,\n result: activeResult,\n viewport: viewportRef.current,\n })\n })\n\n return () => window.cancelAnimationFrame(frame)\n }, [\n activeResult,\n activeResultKey,\n controller,\n controller.activeSheetIndex,\n viewportRef,\n ])\n\n return (\n <Popover>\n <ToolbarTooltip label="Search workbook">\n <PopoverTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search workbook"\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 workbook"\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 && searchResults.length) {\n goToRelativeResult(-1)\n } else if (searchResults.length) {\n goToRelativeResult(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 {searchResults.length ? (\n <>\n <span className="text-primary">\n {activeResultIndex + 1}\n </span>\n {` / ${searchResults.length}`}\n </>\n ) : (\n resultLabel\n )}\n </div>\n {activeResult ? (\n <div className="mt-0.5 truncate">\n {activeResult.sheetName}!{cellAddressToA1(activeResult.cell)}\n </div>\n ) : null}\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 || searchResults.length === 0}\n onClick={() => goToRelativeResult(-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 || searchResults.length === 0}\n onClick={() => goToRelativeResult(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 WorkbookToolbar({\n isDark,\n onDownload,\n onIsDarkChange,\n onUploadClick,\n showDownloadButton = true,\n showNightRenderToggle,\n showUploadButton = true,\n toolbarActions,\n viewportRef,\n workbookIdentity,\n}: {\n isDark: boolean\n onDownload?: () => void\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n showDownloadButton?: boolean\n showNightRenderToggle: boolean\n showUploadButton?: boolean\n toolbarActions?: React.ReactNode\n viewportRef: React.RefObject<HTMLDivElement | null>\n workbookIdentity: string\n}) {\n const { canZoomIn, canZoomOut, setZoomScale, zoomIn, zoomOut, zoomScale } =\n useXlsxViewerZoom()\n const currentZoom = Math.round(zoomScale)\n\n React.useEffect(() => {\n setZoomScale(100)\n }, [setZoomScale, workbookIdentity])\n\n return (\n <div className="flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2">\n <TooltipProvider>\n <div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1">\n {showNightRenderToggle ? (\n <ToolbarTooltip\n label={isDark ? "Use light workbook" : "Use dark workbook"}\n >\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label={isDark ? "Use light workbook" : "Use dark workbook"}\n onClick={() => onIsDarkChange(!isDark)}\n >\n <HugeiconsIcon\n icon={isDark ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n ) : null}\n {showNightRenderToggle ? (\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\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 disabled={!canZoomOut}\n aria-label="Zoom out"\n onClick={zoomOut}\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <Select\n value={currentZoom.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{currentZoom}%</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="end"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\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 disabled={!canZoomIn}\n aria-label="Zoom in"\n onClick={zoomIn}\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <WorkbookSearchPopover\n viewportRef={viewportRef}\n workbookIdentity={workbookIdentity}\n />\n {showDownloadButton && onDownload ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <ToolbarTooltip label="Download XLSX">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Download XLSX"\n onClick={onDownload}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </>\n ) : null}\n {showUploadButton ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <ToolbarTooltip label="Upload XLSX">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Upload XLSX"\n onClick={onUploadClick}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </>\n ) : null}\n {toolbarActions ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {toolbarActions}\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nfunction WorkbookStandaloneToolbar({\n onUploadClick,\n showUploadButton = true,\n toolbarActions,\n}: {\n onUploadClick: () => void\n showUploadButton?: boolean\n toolbarActions?: React.ReactNode\n}) {\n return (\n <div className="flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2">\n <TooltipProvider>\n <div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1">\n {showUploadButton ? (\n <ToolbarTooltip label="Upload XLSX">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Upload XLSX"\n onClick={onUploadClick}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n ) : null}\n {toolbarActions ? (\n <>\n {showUploadButton ? (\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n ) : null}\n {toolbarActions}\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\ntype WorkbookSheetTab = {\n name: string\n workbookSheetIndex: number\n}\n\ntype WorkbookSheetTabsInnerProps = {\n activeSheetIndex: number\n onActiveSheetIndexChange: (index: number) => void\n sheets: WorkbookSheetTab[]\n workbookIdentity: string\n}\n\nexport function WorkbookSheetTabs({\n workbookIdentity,\n}: {\n workbookIdentity: string\n}) {\n const { activeSheetIndex, setActiveSheetIndex, sheets } = useXlsxViewer()\n\n const handleActiveSheetIndexChange = React.useCallback(\n (index: number) => setActiveSheetIndex(index),\n [setActiveSheetIndex]\n )\n\n return (\n <WorkbookSheetTabsInner\n activeSheetIndex={activeSheetIndex}\n onActiveSheetIndexChange={handleActiveSheetIndexChange}\n sheets={sheets}\n workbookIdentity={workbookIdentity}\n />\n )\n}\n\nconst WorkbookSheetTabsInner = React.memo(function WorkbookSheetTabsInner({\n activeSheetIndex,\n onActiveSheetIndexChange,\n sheets,\n workbookIdentity,\n}: WorkbookSheetTabsInnerProps) {\n const [visiblePreviewIndex, setVisiblePreviewIndex] = React.useState<\n number | null\n >(null)\n const [previewPosition, setPreviewPosition] = React.useState({\n left: 0,\n top: 0,\n })\n const { thumbnails } = useXlsxViewerThumbnails(\n XLSX_SHEET_TAB_THUMBNAIL_OPTIONS\n )\n const [thumbnailUrls, setThumbnailUrls] = React.useState<\n Record<number, string>\n >({})\n const scrollRef = React.useRef<HTMLDivElement | null>(null)\n const itemRefs = React.useRef<Record<number, HTMLButtonElement | null>>({})\n const openTimeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(\n null\n )\n const closeTimeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(\n null\n )\n const previewWidth = 220\n const previewHeight = (previewWidth * 7) / 11\n const previewGap = 12\n const previewOpenDelayMs = 500\n\n const clearOpenTimeout = React.useCallback(() => {\n if (openTimeoutRef.current) {\n clearTimeout(openTimeoutRef.current)\n openTimeoutRef.current = null\n }\n }, [])\n\n const clearCloseTimeout = React.useCallback(() => {\n if (closeTimeoutRef.current) {\n clearTimeout(closeTimeoutRef.current)\n closeTimeoutRef.current = null\n }\n }, [])\n\n const getPreviewPosition = React.useCallback(\n (sheetIndex: number) => {\n const item = itemRefs.current[sheetIndex]\n if (!item || typeof window === "undefined") {\n return { left: 0, top: 0 }\n }\n\n const itemRect = item.getBoundingClientRect()\n const centeredLeft = itemRect.left + itemRect.width / 2 - previewWidth / 2\n const minLeft = 8\n const maxLeft = Math.max(minLeft, window.innerWidth - previewWidth - 8)\n const left = Math.max(minLeft, Math.min(centeredLeft, maxLeft))\n const top = Math.max(8, itemRect.top - previewHeight - previewGap)\n\n return { left, top }\n },\n [previewHeight]\n )\n\n const updatePreviewPosition = React.useCallback(\n (sheetIndex: number) => {\n setPreviewPosition(getPreviewPosition(sheetIndex))\n },\n [getPreviewPosition]\n )\n\n const handleItemEnter = React.useCallback(\n (sheetIndex: number) => {\n clearCloseTimeout()\n const nextPreviewPosition = getPreviewPosition(sheetIndex)\n\n if (visiblePreviewIndex !== null) {\n clearOpenTimeout()\n setPreviewPosition(nextPreviewPosition)\n setVisiblePreviewIndex(sheetIndex)\n return\n }\n\n clearOpenTimeout()\n openTimeoutRef.current = setTimeout(() => {\n setPreviewPosition(nextPreviewPosition)\n setVisiblePreviewIndex(sheetIndex)\n }, previewOpenDelayMs)\n },\n [\n clearCloseTimeout,\n clearOpenTimeout,\n getPreviewPosition,\n visiblePreviewIndex,\n ]\n )\n\n const handleContainerLeave = React.useCallback(() => {\n clearOpenTimeout()\n clearCloseTimeout()\n closeTimeoutRef.current = setTimeout(() => {\n setVisiblePreviewIndex(null)\n }, 80)\n }, [clearCloseTimeout, clearOpenTimeout])\n\n React.useEffect(() => {\n return () => {\n clearOpenTimeout()\n clearCloseTimeout()\n }\n }, [clearCloseTimeout, clearOpenTimeout])\n\n React.useEffect(() => {\n clearOpenTimeout()\n clearCloseTimeout()\n setVisiblePreviewIndex(null)\n setPreviewPosition({ left: 0, top: 0 })\n setThumbnailUrls({})\n }, [clearCloseTimeout, clearOpenTimeout, workbookIdentity])\n\n React.useEffect(() => {\n thumbnails.forEach((thumbnail) => {\n setThumbnailUrls((current) => {\n if (current[thumbnail.sheetIndex]) return current\n\n const canvas = document.createElement("canvas")\n canvas.width = thumbnail.width\n canvas.height = thumbnail.height\n\n if (!thumbnail.paint(canvas)) return current\n\n return {\n ...current,\n [thumbnail.sheetIndex]: canvas.toDataURL("image/png"),\n }\n })\n })\n }, [thumbnails])\n\n React.useEffect(() => {\n if (visiblePreviewIndex === null) return\n\n const handleReposition = () => updatePreviewPosition(visiblePreviewIndex)\n handleReposition()\n\n const scrollElement = scrollRef.current\n window.addEventListener("resize", handleReposition)\n scrollElement?.addEventListener("scroll", handleReposition, {\n passive: true,\n })\n\n return () => {\n window.removeEventListener("resize", handleReposition)\n scrollElement?.removeEventListener("scroll", handleReposition)\n }\n }, [updatePreviewPosition, visiblePreviewIndex])\n\n // The preview card portals to document.body, so it outlives the tab\n // strip\'s own visibility: when the viewer is hidden or reparented under\n // the cursor (keep-alive preview pools, a closing dialog) no mouseleave\n // fires and the card would hang on screen. While the preview is open,\n // poll the strip\'s effective visibility and dismiss as soon as it stops\n // being shown.\n React.useEffect(() => {\n if (visiblePreviewIndex === null) return\n\n const dismissWhenHidden = () => {\n const element = scrollRef.current\n const isVisible = Boolean(\n element?.isConnected &&\n (element.checkVisibility?.({ checkVisibilityCSS: true }) ?? true)\n )\n\n if (isVisible) return\n clearOpenTimeout()\n clearCloseTimeout()\n setVisiblePreviewIndex(null)\n }\n const interval = setInterval(dismissWhenHidden, 200)\n\n return () => clearInterval(interval)\n }, [clearCloseTimeout, clearOpenTimeout, visiblePreviewIndex])\n\n if (sheets.length <= 1) return null\n\n const previewSheet =\n visiblePreviewIndex === null ? null : sheets[visiblePreviewIndex]\n const previewUrl =\n visiblePreviewIndex === null\n ? null\n : (thumbnailUrls[visiblePreviewIndex] ?? null)\n\n return (\n <div\n className="border-t bg-muted/40 px-3 py-2"\n onMouseLeave={handleContainerLeave}\n >\n <Tabs\n value={String(activeSheetIndex)}\n onValueChange={(value) => onActiveSheetIndexChange(Number(value))}\n className="gap-0"\n >\n <ScrollArea\n orientation="horizontal"\n scrollbarGutter\n className="h-10 w-full has-[[data-slot=scroll-area-viewport][data-has-overflow-x]]:h-[50px]"\n viewportClassName="overflow-y-hidden"\n viewportRef={scrollRef}\n >\n <div className="flex h-full items-center">\n <TabsList className="shrink-0">\n {sheets.map((sheet, index) => (\n <TabsTrigger\n key={`${sheet.workbookSheetIndex}-${sheet.name}`}\n ref={(node) => {\n itemRefs.current[index] = node\n }}\n value={String(index)}\n className="max-w-48 flex-none"\n onMouseEnter={() => handleItemEnter(index)}\n >\n <span className="truncate">{sheet.name}</span>\n </TabsTrigger>\n ))}\n </TabsList>\n </div>\n </ScrollArea>\n </Tabs>\n {typeof document !== "undefined" &&\n previewSheet &&\n visiblePreviewIndex !== null &&\n previewUrl\n ? createPortal(\n <div\n className="pointer-events-none fixed z-40 translate-y-0 overflow-hidden rounded-lg border bg-background/95 opacity-100 shadow-xl backdrop-blur-md transition-[opacity,transform] duration-100"\n style={{\n left: previewPosition.left,\n top: previewPosition.top,\n width: previewWidth,\n }}\n >\n <div className="relative aspect-[11/7] w-full overflow-hidden bg-muted/60">\n <img\n key={`${workbookIdentity}-${visiblePreviewIndex}-${previewUrl}`}\n src={previewUrl}\n alt={`${previewSheet.name} preview`}\n className="absolute inset-0 h-full w-full object-cover object-left-top"\n />\n </div>\n </div>,\n document.body\n )\n : null}\n </div>\n )\n})\n\nexport function XlsxWorkbookSurface({\n className,\n isDark,\n onDownload,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n rounded,\n showDownloadButton = true,\n showNightRenderToggle,\n showToolbar = true,\n showUploadButton = true,\n toolbarActions,\n workbookIdentity,\n}: {\n className?: string\n isDark: boolean\n onDownload?: () => void\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n rounded: boolean\n showDownloadButton?: boolean\n showNightRenderToggle: boolean\n showToolbar?: boolean\n showUploadButton?: boolean\n toolbarActions?: React.ReactNode\n workbookIdentity: string\n}) {\n const { error } = useXlsxViewer()\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const renderSearchableScroller = React.useCallback(\n ({ children, viewportProps }: XlsxScrollerRenderProps) => (\n <ScrollArea\n className="h-full min-h-0 w-full min-w-0 flex-1"\n viewportProps={viewportProps}\n viewportRef={viewportRef}\n >\n {children}\n </ScrollArea>\n ),\n []\n )\n\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className,\n rounded && "rounded-lg"\n )}\n >\n {showToolbar ? (\n <WorkbookToolbar\n isDark={isDark}\n onDownload={onDownload}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n showDownloadButton={showDownloadButton}\n showNightRenderToggle={showNightRenderToggle}\n showUploadButton={showUploadButton}\n toolbarActions={toolbarActions}\n viewportRef={viewportRef}\n workbookIdentity={workbookIdentity}\n />\n ) : null}\n <div className="flex min-h-0 flex-1 flex-col">\n <div className="min-h-0 flex-1 bg-muted/20">\n <XlsxViewer\n experimentalCanvas\n allowResizeInReadOnly\n className="h-full min-h-0 min-w-0"\n height="100%"\n isDark={isDark}\n readOnly\n rounded={false}\n showDefaultToolbar={false}\n showImages\n fileTooLargeState={\n <div className="grid h-full w-full min-w-full place-items-center p-6">\n <div className="max-w-sm rounded-lg border bg-background p-4 text-sm">\n <p className="font-medium">File too large</p>\n <p className="mt-1 text-muted-foreground">\n This workbook exceeds the display limit. Download it to view\n the full file.\n </p>\n </div>\n </div>\n }\n loadingState={<ViewerLoadingSurface />}\n renderScroller={renderSearchableScroller}\n errorState={\n <div className="grid h-full w-full min-w-full place-items-center p-6 text-sm text-destructive">\n {error?.message ?? "Unable to display workbook."}\n </div>\n }\n renderTableHeaderMenu={renderTableHeaderMenu}\n />\n </div>\n <WorkbookSheetTabs workbookIdentity={workbookIdentity} />\n </div>\n </div>\n )\n}\n\nexport function XlsxViewerPreview({\n className,\n fileName,\n isDark,\n onIsDarkChange,\n rounded = false,\n showDownload = true,\n showToolbar = true,\n showUpload = true,\n src,\n toolbarActions,\n}: {\n className?: string\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n rounded?: boolean\n showDownload?: boolean\n showToolbar?: boolean\n showUpload?: boolean\n src?: string\n toolbarActions?: React.ReactNode\n}) {\n return (\n <XlsxViewerContent\n className={className}\n effectiveIsDark={isDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={onIsDarkChange}\n shouldRenderNightMode\n showDownload={showDownload}\n showToolbar={showToolbar}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n url={src}\n />\n )\n}\n\nfunction XlsxViewerContent({\n className,\n effectiveIsDark,\n fileName,\n rounded,\n setNightRenderEnabled,\n shouldRenderNightMode,\n showDownload,\n showToolbar = true,\n showUpload,\n toolbarActions,\n url,\n}: {\n className?: string\n effectiveIsDark: boolean\n fileName?: string\n rounded: boolean\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n showDownload: boolean\n showToolbar?: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const [uploadedWorkbook, setUploadedWorkbook] =\n React.useState<UploadedWorkbook | null>(null)\n const sourceFileName = React.useMemo(\n () =>\n url ? formatWorkbookName(fileName, url) : (fileName ?? "workbook.xlsx"),\n [fileName, url]\n )\n const displayFileName = React.useMemo(\n () => uploadedWorkbook?.fileName ?? sourceFileName,\n [sourceFileName, uploadedWorkbook?.fileName]\n )\n const workbookIdentity = React.useMemo(\n () => uploadedWorkbook?.identity ?? `${url ?? "empty"}::${displayFileName}`,\n [displayFileName, uploadedWorkbook?.identity, url]\n )\n const [workbookBuffer, setWorkbookBuffer] =\n React.useState<ArrayBuffer | null>(null)\n const [loadError, setLoadError] = React.useState<string>()\n const shouldShowLoadingSpinner = useDelayedLoadingIndicator(\n !workbookBuffer && !loadError && !uploadedWorkbook,\n XLSX_LOADING_INDICATOR_DELAY_MS\n )\n\n React.useEffect(() => {\n let isCurrent = true\n if (url) {\n setUploadedWorkbook(null)\n }\n\n async function loadWorkbook(): Promise<void> {\n if (!url) {\n setWorkbookBuffer(null)\n setLoadError(undefined)\n return\n }\n\n setWorkbookBuffer(null)\n setLoadError(undefined)\n\n try {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch XLSX (${response.status})`)\n }\n\n const nextWorkbookBuffer = await response.arrayBuffer()\n if (!isCurrent) return\n\n setWorkbookBuffer(nextWorkbookBuffer)\n } catch (error) {\n if (!isCurrent) return\n\n setLoadError(\n error instanceof Error ? error.message : "Unknown XLSX load error"\n )\n }\n }\n\n void loadWorkbook()\n\n return () => {\n isCurrent = false\n }\n }, [url])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n const buffer = await file.arrayBuffer()\n setLoadError(undefined)\n setUploadedWorkbook({\n buffer,\n fileName: file.name,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n const activeBuffer = uploadedWorkbook?.buffer ?? workbookBuffer\n const activeFileName = uploadedWorkbook?.fileName ?? displayFileName\n const activeIdentity = workbookIdentity\n\n if (!url && !uploadedWorkbook) {\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <WorkbookStandaloneToolbar\n onUploadClick={() => fileInputRef.current?.click()}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n />\n <div className="grid min-h-0 flex-1 place-items-center bg-muted/30 p-4">\n <div className="max-w-md rounded-lg border bg-background p-4 text-center text-sm shadow-xs">\n <p className="font-medium">Upload a workbook to preview</p>\n <p className="mt-1 text-muted-foreground">\n Pass an XLSX URL with the <code>src</code> prop or upload a file.\n </p>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (loadError && !activeBuffer) {\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <WorkbookStandaloneToolbar\n onUploadClick={() => fileInputRef.current?.click()}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n />\n <div className="grid min-h-0 flex-1 place-items-center bg-muted/30 p-4">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm">\n <p className="font-medium">Unable to display workbook</p>\n <p className="mt-1 text-muted-foreground">{loadError}</p>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (!activeBuffer) {\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <WorkbookStandaloneToolbar\n onUploadClick={() => fileInputRef.current?.click()}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n />\n <ViewerLoadingSurface showSpinner={shouldShowLoadingSpinner} />\n </div>\n )\n }\n\n return (\n <div className={cn("overflow-hidden", className)}>\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <XlsxWorkbookLoadedViewer\n className={className}\n fileName={activeFileName}\n isDark={effectiveIsDark}\n onDownload={() => downloadWorkbookBuffer(activeBuffer, activeFileName)}\n onIsDarkChange={setNightRenderEnabled}\n onUploadClick={() => fileInputRef.current?.click()}\n renderTableHeaderMenu={(props) => (\n <WorkbookTableHeaderMenu {...props} />\n )}\n rounded={rounded}\n showDownloadButton={showDownload}\n showNightRenderToggle={shouldRenderNightMode}\n showToolbar={showToolbar}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n workbookBuffer={activeBuffer}\n workbookIdentity={activeIdentity}\n />\n </div>\n )\n}\n\nfunction XlsxWorkbookLoadedViewer({\n className,\n fileName,\n isDark,\n onDownload,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n rounded,\n showDownloadButton,\n showNightRenderToggle,\n showToolbar = true,\n showUploadButton,\n toolbarActions,\n workbookBuffer,\n workbookIdentity,\n}: {\n className?: string\n fileName: string\n isDark: boolean\n onDownload: () => void\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n rounded: boolean\n showDownloadButton: boolean\n showNightRenderToggle: boolean\n showToolbar?: boolean\n showUploadButton: boolean\n toolbarActions?: React.ReactNode\n workbookBuffer: ArrayBuffer\n workbookIdentity: string\n}) {\n const controller = useXlsxViewerController(\n React.useMemo(\n () => ({\n allowResizeInReadOnly: true,\n file: workbookBuffer,\n fileName,\n maxFileSizeBytes: XLSX_MAX_FILE_SIZE_BYTES,\n readOnly: true,\n useWorker: true,\n }),\n [fileName, workbookBuffer]\n )\n )\n\n return (\n <XlsxViewerProvider controller={controller} isDark={isDark}>\n <XlsxWorkbookSurface\n className={className}\n isDark={isDark}\n onDownload={onDownload}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n renderTableHeaderMenu={renderTableHeaderMenu}\n rounded={rounded}\n showDownloadButton={showDownloadButton}\n showNightRenderToggle={showNightRenderToggle}\n showToolbar={showToolbar}\n showUploadButton={showUploadButton}\n toolbarActions={toolbarActions}\n workbookIdentity={workbookIdentity}\n />\n </XlsxViewerProvider>\n )\n}\n'+ "\"use client\"\n\nimport * as React from \"react\"\nimport {\n useXlsxViewer,\n useXlsxViewerController,\n useXlsxViewerThumbnails,\n useXlsxViewerZoom,\n XlsxViewer,\n XlsxViewerProvider,\n type XlsxCellAddress,\n type XlsxScrollerRenderProps,\n type XlsxSheetData,\n type XlsxTableHeaderMenuRenderProps,\n type XlsxViewerController,\n} from \"@extend-ai/react-xlsx\"\nimport {\n ArrowLeft01Icon,\n ArrowRight01Icon,\n Download01Icon,\n MinusSignCircleIcon,\n Moon02Icon,\n MoreHorizontalIcon,\n PlusSignCircleIcon,\n Search01Icon,\n Upload01Icon,\n} from \"@hugeicons/core-free-icons\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { createPortal } from \"react-dom\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuRadioGroup,\n DropdownMenuRadioItem,\n DropdownMenuSeparator,\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 { Tabs, TabsList, TabsTrigger } from \"@/components/ui/tabs\"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from \"@/components/ui/tooltip\"\n\nconst XLSX_LOADING_INDICATOR_DELAY_MS = 300\nconst XLSX_DROPDOWN_Z_INDEX_CLASS = \"z-40\"\nconst XLSX_SEARCH_BATCH_ROW_COUNT = 500\nconst XLSX_SEARCH_DEBOUNCE_MS = 300\nconst XLSX_GRID_HEADER_HEIGHT = 24\nconst XLSX_GRID_ROW_HEADER_WIDTH = 40\nconst XLSX_MAX_FILE_SIZE_BYTES = 50 * 1024 * 1024\nconst ZOOM_OPTIONS = [10, 25, 50, 75, 100, 125, 150, 175, 200, 400] as const\n\n// Stable reference so the thumbnails memo isn't invalidated on every render\n// (e.g. by selection changes), which would recompute every sheet thumbnail.\nconst XLSX_SHEET_TAB_THUMBNAIL_OPTIONS = {\n resolution: {\n maxHeight: 360,\n maxWidth: 560,\n },\n} as const\n\ntype UploadedWorkbook = {\n buffer: ArrayBuffer\n fileName: string\n identity: string\n}\n\ntype XlsxSearchResult = {\n cell: XlsxCellAddress\n displayValue: string\n formula?: string\n sheetIndex: number\n sheetName: string\n workbookSheetIndex: number\n}\n\ntype XlsxBatchCell = {\n col?: unknown\n formula?: unknown\n value?: unknown\n}\n\ntype XlsxBatchRow = {\n cells?: unknown\n index?: unknown\n}\n\nfunction formatWorkbookName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split(\"?\")[0] ?? \"\"\n const rawName = pathname.split(\"/\").pop() ?? \"workbook.xlsx\"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction ensureWorkbookExtension(fileName: string) {\n const lowerFileName = fileName.toLowerCase()\n return lowerFileName.endsWith(\".xlsx\") || lowerFileName.endsWith(\".xls\")\n ? fileName\n : `${fileName}.xlsx`\n}\n\nfunction downloadWorkbookBuffer(buffer: ArrayBuffer, fileName: string) {\n const resolvedFileName = ensureWorkbookExtension(fileName)\n const blob = new Blob([buffer], {\n type: resolvedFileName.toLowerCase().endsWith(\".xls\")\n ? \"application/vnd.ms-excel\"\n : \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n })\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement(\"a\")\n\n anchor.href = url\n anchor.download = resolvedFileName\n anchor.rel = \"noopener\"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nfunction normalizeSearchText(value: unknown) {\n return typeof value === \"string\"\n ? value\n : value === null || value === undefined\n ? \"\"\n : String(value)\n}\n\nfunction cellValueToSearchText(value: unknown) {\n if (!value || typeof value !== \"object\") return normalizeSearchText(value)\n\n const record = value as {\n asBoolean?: () => boolean | null\n asError?: () => string | null\n asNumber?: () => number | null\n asText?: () => string | null\n is_boolean?: boolean\n is_empty?: boolean\n is_error?: boolean\n is_number?: boolean\n is_text?: boolean\n }\n\n if (record.is_empty) return \"\"\n if (record.is_error) return record.asError?.() ?? \"\"\n if (record.is_text) return record.asText?.() ?? \"\"\n if (record.is_number) return normalizeSearchText(record.asNumber?.())\n if (record.is_boolean) return record.asBoolean?.() ? \"TRUE\" : \"FALSE\"\n\n return normalizeSearchText(value)\n}\n\nfunction getCellSearchText(\n controller: XlsxViewerController,\n sheet: XlsxSheetData,\n row: number,\n col: number\n) {\n const worksheet = controller.workbook?.getSheet(sheet.workbookSheetIndex)\n if (!worksheet) return { displayValue: \"\", formula: \"\" }\n\n const formula = worksheet.getFormulaAt(row, col) ?? \"\"\n const cachedFormulaValue = formula\n ? sheet.cachedFormulaValues[cellAddressToA1({ row, col })]\n : undefined\n const formatted = worksheet.getFormattedValueAt(row, col)\n\n if (\n formatted &&\n !(formula && cachedFormulaValue !== undefined && formatted.startsWith(\"#\"))\n ) {\n return { displayValue: formatted, formula }\n }\n\n const calculated = worksheet.getCalculatedValueAt(row, col)\n const displayValue =\n formula && cachedFormulaValue !== undefined && calculated.is_error\n ? cachedFormulaValue\n : cellValueToSearchText(calculated)\n\n return { displayValue, formula }\n}\n\nfunction getBatchRows(rows: unknown): XlsxBatchRow[] {\n return Array.isArray(rows) ? (rows as XlsxBatchRow[]) : []\n}\n\nfunction getBatchCells(row: XlsxBatchRow): XlsxBatchCell[] {\n return Array.isArray(row.cells) ? (row.cells as XlsxBatchCell[]) : []\n}\n\nfunction cellMatchesQuery(\n displayValue: string,\n formula: string,\n query: string\n) {\n return (\n displayValue.toLowerCase().includes(query) ||\n formula.toLowerCase().includes(query)\n )\n}\n\nfunction cellAddressToA1({ col, row }: XlsxCellAddress) {\n let columnNumber = col + 1\n let columnName = \"\"\n\n while (columnNumber > 0) {\n const remainder = (columnNumber - 1) % 26\n columnName = String.fromCharCode(65 + remainder) + columnName\n columnNumber = Math.floor((columnNumber - 1) / 26)\n }\n\n return `${columnName}${row + 1}`\n}\n\nasync function findXlsxSearchResults(\n controller: XlsxViewerController,\n rawQuery: string\n) {\n const query = rawQuery.trim().toLowerCase()\n if (!query) return []\n\n const results: XlsxSearchResult[] = []\n\n for (const [sheetIndex, sheet] of controller.sheets.entries()) {\n const startRow = Math.max(0, sheet.minUsedRow)\n const endRow = Math.max(startRow, sheet.maxUsedRow)\n const visibleCols = sheet.visibleCols.filter(\n (col) => col >= sheet.minUsedCol && col <= sheet.maxUsedCol\n )\n const visibleRowSet = new Set(sheet.visibleRows)\n const visibleColSet = new Set(visibleCols)\n\n if (!visibleCols.length || sheet.maxUsedRow < sheet.minUsedRow) continue\n\n const worksheet = controller.workbook?.getSheet(sheet.workbookSheetIndex)\n const worksheetWithBatch = worksheet as\n | {\n getRowsBatch?: (\n startRow: number,\n rowCount: number,\n options?: Record<string, unknown>\n ) => unknown\n }\n | undefined\n\n for (\n let batchStartRow = startRow;\n batchStartRow <= endRow;\n batchStartRow += XLSX_SEARCH_BATCH_ROW_COUNT\n ) {\n const rowCount = Math.min(\n XLSX_SEARCH_BATCH_ROW_COUNT,\n endRow - batchStartRow + 1\n )\n const rows = controller.getRowsBatchAsync\n ? await controller.getRowsBatchAsync(\n sheet.workbookSheetIndex,\n batchStartRow,\n rowCount\n )\n : worksheetWithBatch?.getRowsBatch?.(batchStartRow, rowCount, {\n includeFormulas: true,\n useFormattedValues: true,\n })\n\n if (rows) {\n for (const rowEntry of getBatchRows(rows)) {\n const row = Number(rowEntry.index)\n if (!Number.isInteger(row) || !visibleRowSet.has(row)) {\n continue\n }\n\n for (const cellEntry of getBatchCells(rowEntry)) {\n const col = Number(cellEntry.col)\n if (!Number.isInteger(col) || !visibleColSet.has(col)) continue\n\n const displayValue = normalizeSearchText(cellEntry.value)\n const formula = normalizeSearchText(cellEntry.formula)\n\n if (!cellMatchesQuery(displayValue, formula, query)) continue\n\n results.push({\n cell: { row, col },\n displayValue,\n formula,\n sheetIndex,\n sheetName: sheet.name,\n workbookSheetIndex: sheet.workbookSheetIndex,\n })\n }\n }\n continue\n }\n\n if (!worksheet) continue\n\n const batchEndRow = batchStartRow + rowCount - 1\n for (const row of sheet.visibleRows) {\n if (row < batchStartRow || row > batchEndRow) continue\n\n for (const col of visibleCols) {\n const { displayValue, formula } = getCellSearchText(\n controller,\n sheet,\n row,\n col\n )\n\n if (!cellMatchesQuery(displayValue, formula, query)) continue\n\n results.push({\n cell: { row, col },\n displayValue,\n formula,\n sheetIndex,\n sheetName: sheet.name,\n workbookSheetIndex: sheet.workbookSheetIndex,\n })\n }\n }\n }\n }\n\n return results\n}\n\nfunction sumAxisBefore(values: number[], endIndex: number, zoomFactor: number) {\n let total = 0\n for (let index = 0; index < endIndex; index += 1) {\n total += (values[index] ?? 0) * zoomFactor\n }\n return total\n}\n\nfunction scrollXlsxCellIntoView({\n controller,\n result,\n viewport,\n}: {\n controller: XlsxViewerController\n result: XlsxSearchResult\n viewport: HTMLDivElement | null\n}) {\n if (!viewport) return\n\n const sheet = controller.sheets[result.sheetIndex]\n if (!sheet) return\n\n const rowIndex = sheet.visibleRows.indexOf(result.cell.row)\n const colIndex = sheet.visibleCols.indexOf(result.cell.col)\n if (rowIndex < 0 || colIndex < 0) return\n\n const zoomFactor = Math.max(0.1, controller.zoomScale / 100)\n const headerHeight = XLSX_GRID_HEADER_HEIGHT * zoomFactor\n const rowHeaderWidth = XLSX_GRID_ROW_HEADER_WIDTH * zoomFactor\n const rowStart =\n headerHeight + sumAxisBefore(sheet.rowHeights, rowIndex, zoomFactor)\n const colStart =\n rowHeaderWidth + sumAxisBefore(sheet.colWidths, colIndex, zoomFactor)\n const rowHeight =\n (sheet.rowHeights[rowIndex] ?? sheet.defaultRowHeightPx) * zoomFactor\n const colWidth =\n (sheet.colWidths[colIndex] ?? sheet.defaultColWidthPx) * zoomFactor\n const rowEnd = rowStart + rowHeight\n const colEnd = colStart + colWidth\n let nextTop = viewport.scrollTop\n let nextLeft = viewport.scrollLeft\n const visibleTop = viewport.scrollTop + headerHeight\n const visibleLeft = viewport.scrollLeft + rowHeaderWidth\n const visibleBottom = viewport.scrollTop + viewport.clientHeight\n const visibleRight = viewport.scrollLeft + viewport.clientWidth\n\n if (rowStart < visibleTop) {\n nextTop = rowStart - headerHeight\n } else if (rowEnd > visibleBottom) {\n nextTop = rowEnd - viewport.clientHeight\n }\n\n if (colStart < visibleLeft) {\n nextLeft = colStart - rowHeaderWidth\n } else if (colEnd > visibleRight) {\n nextLeft = colEnd - viewport.clientWidth\n }\n\n viewport.scrollTo({\n left: Math.max(0, nextLeft),\n top: Math.max(0, nextTop),\n behavior: \"auto\",\n })\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\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 ViewerLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className=\"grid h-full min-h-52 w-full min-w-full place-items-center bg-transparent\">\n {showSpinner ? <Spinner className=\"size-4\" /> : null}\n </div>\n )\n}\n\nfunction WorkbookFileActionsMenu({\n isDark,\n onDownload,\n onIsDarkChange,\n onUploadClick,\n showDownloadButton,\n showNightRenderToggle = false,\n showUploadButton,\n}: {\n isDark?: boolean\n onDownload?: () => void\n onIsDarkChange?: (checked: boolean) => void\n onUploadClick: () => void\n showDownloadButton: boolean\n showNightRenderToggle?: boolean\n showUploadButton: boolean\n}) {\n const showThemeControl = showNightRenderToggle && Boolean(onIsDarkChange)\n const showFileActions = (showDownloadButton && onDownload) || showUploadButton\n if (!showThemeControl && !showFileActions) return null\n\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Open workbook actions\"\n >\n <HugeiconsIcon icon={MoreHorizontalIcon} className=\"size-4\" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align=\"end\"\n className={cn(\"w-52\", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n {showThemeControl ? (\n <>\n <DropdownMenuCheckboxItem\n checked={Boolean(isDark)}\n variant=\"switch\"\n onCheckedChange={(checked) => onIsDarkChange?.(checked === true)}\n >\n <span className=\"flex min-w-0 items-center gap-2\">\n <HugeiconsIcon icon={Moon02Icon} className=\"size-4\" />\n Dark mode\n </span>\n </DropdownMenuCheckboxItem>\n {showFileActions ? <DropdownMenuSeparator /> : null}\n </>\n ) : null}\n {showDownloadButton && onDownload ? (\n <DropdownMenuItem onClick={onDownload}>\n <HugeiconsIcon icon={Download01Icon} className=\"size-4\" />\n Download\n </DropdownMenuItem>\n ) : null}\n {showUploadButton ? (\n <DropdownMenuItem onClick={onUploadClick}>\n <HugeiconsIcon icon={Upload01Icon} className=\"size-4\" />\n Upload\n </DropdownMenuItem>\n ) : null}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nexport function renderXlsxScroller({\n children,\n viewportProps,\n}: XlsxScrollerRenderProps) {\n return (\n <ScrollArea\n className=\"h-full min-h-0 w-full min-w-0 flex-1\"\n viewportProps={viewportProps}\n >\n {children}\n </ScrollArea>\n )\n}\n\nexport function WorkbookTableHeaderMenu({\n direction,\n sortAscending,\n sortDescending,\n triggerIcon,\n triggerProps,\n}: XlsxTableHeaderMenuRenderProps) {\n const [open, setOpen] = React.useState(false)\n\n return (\n <DropdownMenu open={open} onOpenChange={setOpen}>\n <DropdownMenuTrigger asChild>\n <Button\n {...triggerProps}\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n className={cn(\"size-6 rounded-sm\", triggerProps.className)}\n aria-label=\"Column menu\"\n >\n {triggerIcon ? (\n triggerIcon\n ) : (\n <HugeiconsIcon icon={MoreHorizontalIcon} className=\"size-3.5\" />\n )}\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align=\"end\"\n className={cn(\"w-40\", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <DropdownMenuRadioGroup\n value={direction ?? \"\"}\n onValueChange={(value) => {\n if (value === \"ascending\") {\n sortAscending()\n } else {\n sortDescending()\n }\n setOpen(false)\n }}\n >\n <DropdownMenuRadioItem value=\"ascending\">\n Sort ascending\n </DropdownMenuRadioItem>\n <DropdownMenuRadioItem value=\"descending\">\n Sort descending\n </DropdownMenuRadioItem>\n </DropdownMenuRadioGroup>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction WorkbookSearchPopover({\n viewportRef,\n workbookIdentity,\n}: {\n viewportRef: React.RefObject<HTMLDivElement | null>\n workbookIdentity: string\n}) {\n const controller = useXlsxViewer()\n const [searchDraft, setSearchDraft] = React.useState(\"\")\n const [searchQuery, setSearchQuery] = React.useState(\"\")\n const [searchResults, setSearchResults] = React.useState<XlsxSearchResult[]>(\n []\n )\n const [activeResultIndex, setActiveResultIndex] = React.useState(0)\n const [isSearching, setIsSearching] = React.useState(false)\n const controllerRef = React.useRef(controller)\n const searchRequestIdRef = React.useRef(0)\n const appliedResultKeyRef = React.useRef(\"\")\n const activeResult = searchResults[activeResultIndex] ?? null\n const activeResultKey = activeResult\n ? `${activeResult.workbookSheetIndex}:${activeResult.cell.row}:${activeResult.cell.col}`\n : \"\"\n const controlsDisabled =\n controller.isLoading ||\n Boolean(controller.error) ||\n !controller.sheets.length\n const hasActiveQuery = Boolean(searchQuery.trim())\n const resultLabel = isSearching\n ? \"Searching\"\n : !hasActiveQuery\n ? \"No search\"\n : searchResults.length\n ? `${activeResultIndex + 1} / ${searchResults.length}`\n : \"No results\"\n\n React.useEffect(() => {\n controllerRef.current = controller\n }, [controller])\n\n const runSearch = React.useCallback((rawQuery: string) => {\n const nextQuery = rawQuery.trim()\n const requestId = searchRequestIdRef.current + 1\n searchRequestIdRef.current = requestId\n appliedResultKeyRef.current = \"\"\n setSearchQuery(nextQuery)\n setActiveResultIndex(0)\n\n if (!nextQuery) {\n setSearchResults([])\n setIsSearching(false)\n return\n }\n\n setIsSearching(true)\n void findXlsxSearchResults(controllerRef.current, nextQuery)\n .then((nextResults) => {\n if (searchRequestIdRef.current !== requestId) return\n setSearchResults(nextResults)\n })\n .catch(() => {\n if (searchRequestIdRef.current !== requestId) return\n setSearchResults([])\n })\n .finally(() => {\n if (searchRequestIdRef.current !== requestId) return\n setIsSearching(false)\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 }, XLSX_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 setSearchResults([])\n setActiveResultIndex(0)\n setIsSearching(false)\n appliedResultKeyRef.current = \"\"\n controller.clearSelection()\n }, [controller])\n\n const goToRelativeResult = React.useCallback(\n (direction: 1 | -1) => {\n if (!searchResults.length) return\n\n setActiveResultIndex((currentIndex) => {\n return (\n (currentIndex + direction + searchResults.length) %\n searchResults.length\n )\n })\n },\n [searchResults.length]\n )\n\n React.useEffect(() => {\n searchRequestIdRef.current += 1\n setSearchDraft(\"\")\n setSearchQuery(\"\")\n setSearchResults([])\n setActiveResultIndex(0)\n setIsSearching(false)\n appliedResultKeyRef.current = \"\"\n }, [workbookIdentity])\n\n React.useEffect(() => {\n if (!activeResult) return\n\n if (controller.activeSheetIndex !== activeResult.sheetIndex) {\n appliedResultKeyRef.current = \"\"\n controller.setActiveSheetIndex(activeResult.sheetIndex)\n return\n }\n\n if (appliedResultKeyRef.current === activeResultKey) return\n appliedResultKeyRef.current = activeResultKey\n controller.selectCell(activeResult.cell)\n\n const frame = window.requestAnimationFrame(() => {\n scrollXlsxCellIntoView({\n controller,\n result: activeResult,\n viewport: viewportRef.current,\n })\n })\n\n return () => window.cancelAnimationFrame(frame)\n }, [\n activeResult,\n activeResultKey,\n controller,\n controller.activeSheetIndex,\n viewportRef,\n ])\n\n return (\n <Popover>\n <ToolbarTooltip label=\"Search workbook\">\n <PopoverTrigger asChild>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Search workbook\"\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 workbook\"\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 && searchResults.length) {\n goToRelativeResult(-1)\n } else if (searchResults.length) {\n goToRelativeResult(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 {searchResults.length ? (\n <>\n <span className=\"text-primary\">\n {activeResultIndex + 1}\n </span>\n {` / ${searchResults.length}`}\n </>\n ) : (\n resultLabel\n )}\n </div>\n {activeResult ? (\n <div className=\"mt-0.5 truncate\">\n {activeResult.sheetName}!{cellAddressToA1(activeResult.cell)}\n </div>\n ) : null}\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 || searchResults.length === 0}\n onClick={() => goToRelativeResult(-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 || searchResults.length === 0}\n onClick={() => goToRelativeResult(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 WorkbookToolbar({\n isDark,\n onDownload,\n onIsDarkChange,\n onUploadClick,\n showDownloadButton = true,\n showNightRenderToggle,\n showUploadButton = true,\n toolbarActions,\n viewportRef,\n workbookIdentity,\n}: {\n isDark: boolean\n onDownload?: () => void\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n showDownloadButton?: boolean\n showNightRenderToggle: boolean\n showUploadButton?: boolean\n toolbarActions?: React.ReactNode\n viewportRef: React.RefObject<HTMLDivElement | null>\n workbookIdentity: string\n}) {\n const { canZoomIn, canZoomOut, setZoomScale, zoomIn, zoomOut, zoomScale } =\n useXlsxViewerZoom()\n const currentZoom = Math.round(zoomScale)\n\n React.useEffect(() => {\n setZoomScale(100)\n }, [setZoomScale, workbookIdentity])\n\n return (\n <div className=\"flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2\">\n <TooltipProvider>\n <div className=\"ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1\">\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 disabled={!canZoomOut}\n aria-label=\"Zoom out\"\n onClick={zoomOut}\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n <Select\n value={currentZoom.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n modal={false}\n >\n <SelectTrigger\n size=\"sm\"\n className=\"w-[84px] min-w-[84px]\"\n aria-label=\"Zoom level\"\n >\n <SelectValue>{currentZoom}%</SelectValue>\n </SelectTrigger>\n <SelectContent\n align=\"end\"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\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 disabled={!canZoomIn}\n aria-label=\"Zoom in\"\n onClick={zoomIn}\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator orientation=\"vertical\" className=\"mx-1 h-4 self-center\" />\n <WorkbookSearchPopover\n viewportRef={viewportRef}\n workbookIdentity={workbookIdentity}\n />\n {toolbarActions ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n {toolbarActions}\n </>\n ) : null}\n {(showDownloadButton && onDownload) ||\n showUploadButton ||\n showNightRenderToggle ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n <WorkbookFileActionsMenu\n isDark={isDark}\n onDownload={onDownload}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n showDownloadButton={showDownloadButton}\n showNightRenderToggle={showNightRenderToggle}\n showUploadButton={showUploadButton}\n />\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nfunction WorkbookStandaloneToolbar({\n onUploadClick,\n showUploadButton = true,\n toolbarActions,\n}: {\n onUploadClick: () => void\n showUploadButton?: boolean\n toolbarActions?: React.ReactNode\n}) {\n return (\n <div className=\"flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2\">\n <TooltipProvider>\n <div className=\"ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1\">\n {toolbarActions ? <>{toolbarActions}</> : null}\n {showUploadButton ? (\n <>\n {toolbarActions ? (\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n ) : null}\n <WorkbookFileActionsMenu\n onUploadClick={onUploadClick}\n showDownloadButton={false}\n showUploadButton={showUploadButton}\n />\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\ntype WorkbookSheetTab = {\n name: string\n workbookSheetIndex: number\n}\n\ntype WorkbookSheetTabsInnerProps = {\n activeSheetIndex: number\n onActiveSheetIndexChange: (index: number) => void\n sheets: WorkbookSheetTab[]\n workbookIdentity: string\n}\n\nexport function WorkbookSheetTabs({\n workbookIdentity,\n}: {\n workbookIdentity: string\n}) {\n const { activeSheetIndex, setActiveSheetIndex, sheets } = useXlsxViewer()\n\n const handleActiveSheetIndexChange = React.useCallback(\n (index: number) => setActiveSheetIndex(index),\n [setActiveSheetIndex]\n )\n\n return (\n <WorkbookSheetTabsInner\n activeSheetIndex={activeSheetIndex}\n onActiveSheetIndexChange={handleActiveSheetIndexChange}\n sheets={sheets}\n workbookIdentity={workbookIdentity}\n />\n )\n}\n\nconst WorkbookSheetTabsInner = React.memo(function WorkbookSheetTabsInner({\n activeSheetIndex,\n onActiveSheetIndexChange,\n sheets,\n workbookIdentity,\n}: WorkbookSheetTabsInnerProps) {\n const [visiblePreviewIndex, setVisiblePreviewIndex] = React.useState<\n number | null\n >(null)\n const [previewPosition, setPreviewPosition] = React.useState({\n left: 0,\n top: 0,\n })\n const { thumbnails } = useXlsxViewerThumbnails(\n XLSX_SHEET_TAB_THUMBNAIL_OPTIONS\n )\n const [thumbnailUrls, setThumbnailUrls] = React.useState<\n Record<number, string>\n >({})\n const scrollRef = React.useRef<HTMLDivElement | null>(null)\n const itemRefs = React.useRef<Record<number, HTMLButtonElement | null>>({})\n const openTimeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(\n null\n )\n const closeTimeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(\n null\n )\n const previewWidth = 220\n const previewHeight = (previewWidth * 7) / 11\n const previewGap = 12\n const previewOpenDelayMs = 500\n\n const clearOpenTimeout = React.useCallback(() => {\n if (openTimeoutRef.current) {\n clearTimeout(openTimeoutRef.current)\n openTimeoutRef.current = null\n }\n }, [])\n\n const clearCloseTimeout = React.useCallback(() => {\n if (closeTimeoutRef.current) {\n clearTimeout(closeTimeoutRef.current)\n closeTimeoutRef.current = null\n }\n }, [])\n\n const getPreviewPosition = React.useCallback(\n (sheetIndex: number) => {\n const item = itemRefs.current[sheetIndex]\n if (!item || typeof window === \"undefined\") {\n return { left: 0, top: 0 }\n }\n\n const itemRect = item.getBoundingClientRect()\n const centeredLeft = itemRect.left + itemRect.width / 2 - previewWidth / 2\n const minLeft = 8\n const maxLeft = Math.max(minLeft, window.innerWidth - previewWidth - 8)\n const left = Math.max(minLeft, Math.min(centeredLeft, maxLeft))\n const top = Math.max(8, itemRect.top - previewHeight - previewGap)\n\n return { left, top }\n },\n [previewHeight]\n )\n\n const updatePreviewPosition = React.useCallback(\n (sheetIndex: number) => {\n setPreviewPosition(getPreviewPosition(sheetIndex))\n },\n [getPreviewPosition]\n )\n\n const handleItemEnter = React.useCallback(\n (sheetIndex: number) => {\n clearCloseTimeout()\n const nextPreviewPosition = getPreviewPosition(sheetIndex)\n\n if (visiblePreviewIndex !== null) {\n clearOpenTimeout()\n setPreviewPosition(nextPreviewPosition)\n setVisiblePreviewIndex(sheetIndex)\n return\n }\n\n clearOpenTimeout()\n openTimeoutRef.current = setTimeout(() => {\n setPreviewPosition(nextPreviewPosition)\n setVisiblePreviewIndex(sheetIndex)\n }, previewOpenDelayMs)\n },\n [\n clearCloseTimeout,\n clearOpenTimeout,\n getPreviewPosition,\n visiblePreviewIndex,\n ]\n )\n\n const handleContainerLeave = React.useCallback(() => {\n clearOpenTimeout()\n clearCloseTimeout()\n closeTimeoutRef.current = setTimeout(() => {\n setVisiblePreviewIndex(null)\n }, 80)\n }, [clearCloseTimeout, clearOpenTimeout])\n\n React.useEffect(() => {\n return () => {\n clearOpenTimeout()\n clearCloseTimeout()\n }\n }, [clearCloseTimeout, clearOpenTimeout])\n\n React.useEffect(() => {\n clearOpenTimeout()\n clearCloseTimeout()\n setVisiblePreviewIndex(null)\n setPreviewPosition({ left: 0, top: 0 })\n setThumbnailUrls({})\n }, [clearCloseTimeout, clearOpenTimeout, workbookIdentity])\n\n React.useEffect(() => {\n thumbnails.forEach((thumbnail) => {\n setThumbnailUrls((current) => {\n if (current[thumbnail.sheetIndex]) return current\n\n const canvas = document.createElement(\"canvas\")\n canvas.width = thumbnail.width\n canvas.height = thumbnail.height\n\n if (!thumbnail.paint(canvas)) return current\n\n return {\n ...current,\n [thumbnail.sheetIndex]: canvas.toDataURL(\"image/png\"),\n }\n })\n })\n }, [thumbnails])\n\n React.useEffect(() => {\n if (visiblePreviewIndex === null) return\n\n const handleReposition = () => updatePreviewPosition(visiblePreviewIndex)\n handleReposition()\n\n const scrollElement = scrollRef.current\n window.addEventListener(\"resize\", handleReposition)\n scrollElement?.addEventListener(\"scroll\", handleReposition, {\n passive: true,\n })\n\n return () => {\n window.removeEventListener(\"resize\", handleReposition)\n scrollElement?.removeEventListener(\"scroll\", handleReposition)\n }\n }, [updatePreviewPosition, visiblePreviewIndex])\n\n // The preview card portals to document.body, so it outlives the tab\n // strip's own visibility: when the viewer is hidden or reparented under\n // the cursor (keep-alive preview pools, a closing dialog) no mouseleave\n // fires and the card would hang on screen. While the preview is open,\n // poll the strip's effective visibility and dismiss as soon as it stops\n // being shown.\n React.useEffect(() => {\n if (visiblePreviewIndex === null) return\n\n const dismissWhenHidden = () => {\n const element = scrollRef.current\n const isVisible = Boolean(\n element?.isConnected &&\n (element.checkVisibility?.({ checkVisibilityCSS: true }) ?? true)\n )\n\n if (isVisible) return\n clearOpenTimeout()\n clearCloseTimeout()\n setVisiblePreviewIndex(null)\n }\n const interval = setInterval(dismissWhenHidden, 200)\n\n return () => clearInterval(interval)\n }, [clearCloseTimeout, clearOpenTimeout, visiblePreviewIndex])\n\n if (sheets.length <= 1) return null\n\n const previewSheet =\n visiblePreviewIndex === null ? null : sheets[visiblePreviewIndex]\n const previewUrl =\n visiblePreviewIndex === null\n ? null\n : (thumbnailUrls[visiblePreviewIndex] ?? null)\n\n return (\n <div\n className=\"border-t bg-muted/40 px-3 py-2\"\n onMouseLeave={handleContainerLeave}\n >\n <Tabs\n value={String(activeSheetIndex)}\n onValueChange={(value) => onActiveSheetIndexChange(Number(value))}\n className=\"gap-0\"\n >\n <ScrollArea\n orientation=\"horizontal\"\n scrollbarGutter\n className=\"h-10 w-full has-[[data-slot=scroll-area-viewport][data-has-overflow-x]]:h-[50px]\"\n viewportClassName=\"overflow-y-hidden\"\n viewportRef={scrollRef}\n >\n <div className=\"flex h-full items-center\">\n <TabsList className=\"shrink-0\">\n {sheets.map((sheet, index) => (\n <TabsTrigger\n key={`${sheet.workbookSheetIndex}-${sheet.name}`}\n ref={(node) => {\n itemRefs.current[index] = node\n }}\n value={String(index)}\n className=\"max-w-48 flex-none\"\n onMouseEnter={() => handleItemEnter(index)}\n >\n <span className=\"truncate\">{sheet.name}</span>\n </TabsTrigger>\n ))}\n </TabsList>\n </div>\n </ScrollArea>\n </Tabs>\n {typeof document !== \"undefined\" &&\n previewSheet &&\n visiblePreviewIndex !== null &&\n previewUrl\n ? createPortal(\n <div\n className=\"pointer-events-none fixed z-40 translate-y-0 overflow-hidden rounded-lg border bg-background/95 opacity-100 shadow-xl backdrop-blur-md transition-[opacity,transform] duration-100\"\n style={{\n left: previewPosition.left,\n top: previewPosition.top,\n width: previewWidth,\n }}\n >\n <div className=\"relative aspect-[11/7] w-full overflow-hidden bg-muted/60\">\n <img\n key={`${workbookIdentity}-${visiblePreviewIndex}-${previewUrl}`}\n src={previewUrl}\n alt={`${previewSheet.name} preview`}\n className=\"absolute inset-0 h-full w-full object-cover object-left-top\"\n />\n </div>\n </div>,\n document.body\n )\n : null}\n </div>\n )\n})\n\nexport function XlsxWorkbookSurface({\n className,\n isDark,\n onDownload,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n showDownloadButton = true,\n showNightRenderToggle,\n showToolbar = true,\n showUploadButton = true,\n toolbarActions,\n workbookIdentity,\n}: {\n className?: string\n isDark: boolean\n onDownload?: () => void\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n showDownloadButton?: boolean\n showNightRenderToggle: boolean\n showToolbar?: boolean\n showUploadButton?: boolean\n toolbarActions?: React.ReactNode\n workbookIdentity: string\n}) {\n const { error } = useXlsxViewer()\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const renderSearchableScroller = React.useCallback(\n ({ children, viewportProps }: XlsxScrollerRenderProps) => (\n <ScrollArea\n className=\"h-full min-h-0 w-full min-w-0 flex-1\"\n viewportProps={viewportProps}\n viewportRef={viewportRef}\n >\n {children}\n </ScrollArea>\n ),\n []\n )\n\n return (\n <div\n className={cn(\n \"flex h-[640px] min-h-0 flex-col overflow-hidden bg-background\",\n className\n )}\n >\n {showToolbar ? (\n <WorkbookToolbar\n isDark={isDark}\n onDownload={onDownload}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n showDownloadButton={showDownloadButton}\n showNightRenderToggle={showNightRenderToggle}\n showUploadButton={showUploadButton}\n toolbarActions={toolbarActions}\n viewportRef={viewportRef}\n workbookIdentity={workbookIdentity}\n />\n ) : null}\n <div className=\"flex min-h-0 flex-1 flex-col\">\n <div className=\"min-h-0 flex-1 bg-muted/20\">\n <XlsxViewer\n experimentalCanvas\n allowResizeInReadOnly\n className=\"h-full min-h-0 min-w-0\"\n height=\"100%\"\n isDark={isDark}\n readOnly\n rounded={false}\n showDefaultToolbar={false}\n showImages\n fileTooLargeState={\n <div className=\"grid h-full w-full min-w-full place-items-center p-6\">\n <div className=\"max-w-sm rounded-lg border bg-background p-4 text-sm\">\n <p className=\"font-medium\">File too large</p>\n <p className=\"mt-1 text-muted-foreground\">\n This workbook exceeds the display limit. Download it to view\n the full file.\n </p>\n </div>\n </div>\n }\n loadingState={<ViewerLoadingSurface />}\n renderScroller={renderSearchableScroller}\n errorState={\n <div className=\"grid h-full w-full min-w-full place-items-center p-6 text-sm text-destructive\">\n {error?.message ?? \"Unable to display workbook.\"}\n </div>\n }\n renderTableHeaderMenu={renderTableHeaderMenu}\n />\n </div>\n <WorkbookSheetTabs workbookIdentity={workbookIdentity} />\n </div>\n </div>\n )\n}\n\nexport function XlsxViewerPreview({\n className,\n fileName,\n isDark,\n onIsDarkChange,\n showDownload = true,\n showToolbar = true,\n showUpload = true,\n src,\n toolbarActions,\n}: {\n className?: string\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n showDownload?: boolean\n showToolbar?: boolean\n showUpload?: boolean\n src?: string\n toolbarActions?: React.ReactNode\n}) {\n return (\n <XlsxViewerContent\n className={className}\n effectiveIsDark={isDark}\n fileName={fileName}\n setNightRenderEnabled={onIsDarkChange}\n shouldRenderNightMode\n showDownload={showDownload}\n showToolbar={showToolbar}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n url={src}\n />\n )\n}\n\nfunction XlsxViewerContent({\n className,\n effectiveIsDark,\n fileName,\n setNightRenderEnabled,\n shouldRenderNightMode,\n showDownload,\n showToolbar = true,\n showUpload,\n toolbarActions,\n url,\n}: {\n className?: string\n effectiveIsDark: boolean\n fileName?: string\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n showDownload: boolean\n showToolbar?: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const [uploadedWorkbook, setUploadedWorkbook] =\n React.useState<UploadedWorkbook | null>(null)\n const sourceFileName = React.useMemo(\n () =>\n url ? formatWorkbookName(fileName, url) : (fileName ?? \"workbook.xlsx\"),\n [fileName, url]\n )\n const displayFileName = React.useMemo(\n () => uploadedWorkbook?.fileName ?? sourceFileName,\n [sourceFileName, uploadedWorkbook?.fileName]\n )\n const workbookIdentity = React.useMemo(\n () => uploadedWorkbook?.identity ?? `${url ?? \"empty\"}::${displayFileName}`,\n [displayFileName, uploadedWorkbook?.identity, url]\n )\n const [workbookBuffer, setWorkbookBuffer] =\n React.useState<ArrayBuffer | null>(null)\n const [loadError, setLoadError] = React.useState<string>()\n const shouldShowLoadingSpinner = useDelayedLoadingIndicator(\n !workbookBuffer && !loadError && !uploadedWorkbook,\n XLSX_LOADING_INDICATOR_DELAY_MS\n )\n\n React.useEffect(() => {\n let isCurrent = true\n if (url) {\n setUploadedWorkbook(null)\n }\n\n async function loadWorkbook(): Promise<void> {\n if (!url) {\n setWorkbookBuffer(null)\n setLoadError(undefined)\n return\n }\n\n setWorkbookBuffer(null)\n setLoadError(undefined)\n\n try {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch XLSX (${response.status})`)\n }\n\n const nextWorkbookBuffer = await response.arrayBuffer()\n if (!isCurrent) return\n\n setWorkbookBuffer(nextWorkbookBuffer)\n } catch (error) {\n if (!isCurrent) return\n\n setLoadError(\n error instanceof Error ? error.message : \"Unknown XLSX load error\"\n )\n }\n }\n\n void loadWorkbook()\n\n return () => {\n isCurrent = false\n }\n }, [url])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = \"\"\n\n if (!file) return\n\n const buffer = await file.arrayBuffer()\n setLoadError(undefined)\n setUploadedWorkbook({\n buffer,\n fileName: file.name,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n const activeBuffer = uploadedWorkbook?.buffer ?? workbookBuffer\n const activeFileName = uploadedWorkbook?.fileName ?? displayFileName\n const activeIdentity = workbookIdentity\n\n if (!url && !uploadedWorkbook) {\n return (\n <div\n className={cn(\n \"flex h-[640px] min-h-0 flex-col overflow-hidden bg-background\",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel\"\n className=\"hidden\"\n onChange={handleUpload}\n />\n <WorkbookStandaloneToolbar\n onUploadClick={() => fileInputRef.current?.click()}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n />\n <div className=\"grid min-h-0 flex-1 place-items-center bg-muted/30 p-4\">\n <div className=\"max-w-md rounded-lg border bg-background p-4 text-center text-sm shadow-xs\">\n <p className=\"font-medium\">Upload a workbook to preview</p>\n <p className=\"mt-1 text-muted-foreground\">\n Pass an XLSX URL with the <code>src</code> prop or upload a file.\n </p>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n className=\"mt-4\"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className=\"size-4\" />\n Upload XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (loadError && !activeBuffer) {\n return (\n <div\n className={cn(\n \"flex h-[640px] min-h-0 flex-col overflow-hidden bg-background\",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel\"\n className=\"hidden\"\n onChange={handleUpload}\n />\n <WorkbookStandaloneToolbar\n onUploadClick={() => fileInputRef.current?.click()}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n />\n <div className=\"grid min-h-0 flex-1 place-items-center bg-muted/30 p-4\">\n <div className=\"max-w-md rounded-lg border bg-background p-4 text-sm\">\n <p className=\"font-medium\">Unable to display workbook</p>\n <p className=\"mt-1 text-muted-foreground\">{loadError}</p>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n className=\"mt-4\"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className=\"size-4\" />\n Upload XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (!activeBuffer) {\n return (\n <div\n className={cn(\n \"flex h-[640px] min-h-0 flex-col overflow-hidden bg-background\",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel\"\n className=\"hidden\"\n onChange={handleUpload}\n />\n <WorkbookStandaloneToolbar\n onUploadClick={() => fileInputRef.current?.click()}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n />\n <ViewerLoadingSurface showSpinner={shouldShowLoadingSpinner} />\n </div>\n )\n }\n\n return (\n <div className={cn(\"overflow-hidden\", className)}>\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel\"\n className=\"hidden\"\n onChange={handleUpload}\n />\n <XlsxWorkbookLoadedViewer\n className={className}\n fileName={activeFileName}\n isDark={effectiveIsDark}\n onDownload={() => downloadWorkbookBuffer(activeBuffer, activeFileName)}\n onIsDarkChange={setNightRenderEnabled}\n onUploadClick={() => fileInputRef.current?.click()}\n renderTableHeaderMenu={(props) => (\n <WorkbookTableHeaderMenu {...props} />\n )}\n showDownloadButton={showDownload}\n showNightRenderToggle={shouldRenderNightMode}\n showToolbar={showToolbar}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n workbookBuffer={activeBuffer}\n workbookIdentity={activeIdentity}\n />\n </div>\n )\n}\n\nfunction XlsxWorkbookLoadedViewer({\n className,\n fileName,\n isDark,\n onDownload,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n showDownloadButton,\n showNightRenderToggle,\n showToolbar = true,\n showUploadButton,\n toolbarActions,\n workbookBuffer,\n workbookIdentity,\n}: {\n className?: string\n fileName: string\n isDark: boolean\n onDownload: () => void\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n showDownloadButton: boolean\n showNightRenderToggle: boolean\n showToolbar?: boolean\n showUploadButton: boolean\n toolbarActions?: React.ReactNode\n workbookBuffer: ArrayBuffer\n workbookIdentity: string\n}) {\n const controller = useXlsxViewerController(\n React.useMemo(\n () => ({\n allowResizeInReadOnly: true,\n file: workbookBuffer,\n fileName,\n maxFileSizeBytes: XLSX_MAX_FILE_SIZE_BYTES,\n readOnly: true,\n useWorker: true,\n }),\n [fileName, workbookBuffer]\n )\n )\n\n return (\n <XlsxViewerProvider controller={controller} isDark={isDark}>\n <XlsxWorkbookSurface\n className={className}\n isDark={isDark}\n onDownload={onDownload}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n renderTableHeaderMenu={renderTableHeaderMenu}\n showDownloadButton={showDownloadButton}\n showNightRenderToggle={showNightRenderToggle}\n showToolbar={showToolbar}\n showUploadButton={showUploadButton}\n toolbarActions={toolbarActions}\n workbookIdentity={workbookIdentity}\n />\n </XlsxViewerProvider>\n )\n}\n"export function XlsxViewerSource() {return (diff --git a/apps/v4/content/docs/components/docx-editor.mdx b/apps/v4/content/docs/components/docx-editor.mdxindex 66ca094..31c35cf 100644--- a/apps/v4/content/docs/components/docx-editor.mdx+++ b/apps/v4/content/docs/components/docx-editor.mdx@@ -32,7 +32,7 @@ npx shadcn@latest add @extend/docx-editor<Step>Install the following dependencies:</Step>```bash-npm install @base-ui/react@^1.4.1 @extend-ai/react-docx@^0.7.0-alpha.6 @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6+npm install @base-ui/react@^1.4.1 @extend-ai/react-docx@^0.7.0-alpha.7 @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6```<Step>@@ -75,5 +75,4 @@ The DocxEditorPreview component renders an editable DOCX file with upload, toolb| `fileName` | `string` | `-` | No || `isDark` | `boolean` | `-` | Yes || `onIsDarkChange` | `(isDark: boolean) => void` | `-` | Yes |-| `rounded` | `boolean` | `false` | No || `src` | `string` | `-` | No |diff --git a/apps/v4/content/docs/components/docx-viewer.mdx b/apps/v4/content/docs/components/docx-viewer.mdxindex 4d85bab..eac3e21 100644--- a/apps/v4/content/docs/components/docx-viewer.mdx+++ b/apps/v4/content/docs/components/docx-viewer.mdx@@ -32,7 +32,7 @@ npx shadcn@latest add @extend/docx-viewer<Step>Install the following dependencies:</Step>```bash-npm install @extend-ai/react-docx@^0.7.0-alpha.6 @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6+npm install @extend-ai/react-docx@^0.7.0-alpha.7 @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6```<Step>Copy and paste the following code into your project.</Step>@@ -67,5 +67,4 @@ The DocxViewerPreview component renders a DOCX file with upload, theme, and zoom| `fileName` | `string` | `-` | No || `isDark` | `boolean` | `-` | Yes || `onIsDarkChange` | `(isDark: boolean) => void` | `-` | Yes |-| `rounded` | `boolean` | `false` | No || `src` | `string` | `-` | No |diff --git a/apps/v4/content/docs/components/pdf-viewer.mdx b/apps/v4/content/docs/components/pdf-viewer.mdxindex a6a8688..e15451f 100644--- a/apps/v4/content/docs/components/pdf-viewer.mdx+++ b/apps/v4/content/docs/components/pdf-viewer.mdx@@ -64,25 +64,22 @@ npm install @embedpdf/core@^2.14.4 @embedpdf/engines@^2.14.4 @embedpdf/models@^2The PDFViewer component renders a scrollable PDF surface with toolbar controls, lazy page rendering, uploads, and page-level extension hooks.-| Prop | Type | Default | Required |-| ----------------------------- | ------------------------------------------------------------------------- | ------- | -------- |-| `src` | `string` | `-` | No |-| `className` | `string` | `-` | No |-| `defaultThumbnailSidebarOpen` | `boolean` | `false` | No |-| `defaultZoom` | `number` | `1` | No |-| `pageWidth` | `number` | `-` | No |-| `pageHeight` | `number` | `-` | No |-| `showDownload` | `boolean` | `true` | No |-| `showToolbar` | `boolean` | `true` | No |-| `showRotateControls` | `boolean` | `true` | No |-| `showUpload` | `boolean` | `true` | No |-| `toolbarActions` | `React.ReactNode` | `-` | No |-| `pageClassName` | `(pageNumber: number) => string \| undefined` | `-` | No |-| `renderPageOverlay` | `(props: PDFViewerPageOverlayProps) => React.ReactNode` | `-` | No |-| `onActivePageChange` | `(pageNumber: number) => void` | `-` | No |-| `onDocumentLoadSuccess` | `(numPages: number) => void` | `-` | No |-| `onPdfUpload` | `(file: File) => void` | `-` | No |-| `onPagePointerDown` | `(event: React.PointerEvent<HTMLDivElement>, pageNumber: number) => void` | `-` | No |-| `onPagePointerMove` | `(event: React.PointerEvent<HTMLDivElement>, pageNumber: number) => void` | `-` | No |-| `onPagePointerUp` | `(event: React.PointerEvent<HTMLDivElement>, pageNumber: number) => void` | `-` | No |-| `onPagePointerCancel` | `(event: React.PointerEvent<HTMLDivElement>, pageNumber: number) => void` | `-` | No |+| Prop | Type | Default | Required |+| ----------------------- | ------------------------------------------------------------------------- | ------- | -------- |+| `src` | `string` | `-` | No |+| `className` | `string` | `-` | No |+| `defaultZoom` | `number` | `1` | No |+| `showDownload` | `boolean` | `true` | No |+| `showToolbar` | `boolean` | `true` | No |+| `showRotateControls` | `boolean` | `true` | No |+| `showUpload` | `boolean` | `true` | No |+| `toolbarActions` | `React.ReactNode` | `-` | No |+| `pageClassName` | `(pageNumber: number) => string \| undefined` | `-` | No |+| `renderPageOverlay` | `(props: PDFViewerPageOverlayProps) => React.ReactNode` | `-` | No |+| `onActivePageChange` | `(pageNumber: number) => void` | `-` | No |+| `onDocumentLoadSuccess` | `(numPages: number) => void` | `-` | No |+| `onPdfUpload` | `(file: File) => void` | `-` | No |+| `onPagePointerDown` | `(event: React.PointerEvent<HTMLDivElement>, pageNumber: number) => void` | `-` | No |+| `onPagePointerMove` | `(event: React.PointerEvent<HTMLDivElement>, pageNumber: number) => void` | `-` | No |+| `onPagePointerUp` | `(event: React.PointerEvent<HTMLDivElement>, pageNumber: number) => void` | `-` | No |+| `onPagePointerCancel` | `(event: React.PointerEvent<HTMLDivElement>, pageNumber: number) => void` | `-` | No |diff --git a/apps/v4/content/docs/components/xlsx-editor.mdx b/apps/v4/content/docs/components/xlsx-editor.mdxindex d1634a1..cd8d17e 100644--- a/apps/v4/content/docs/components/xlsx-editor.mdx+++ b/apps/v4/content/docs/components/xlsx-editor.mdx@@ -75,5 +75,4 @@ The XlsxEditorPreview component renders an editable Excel workbook with upload,| `fileName` | `string` | `-` | No || `isDark` | `boolean` | `-` | Yes || `onIsDarkChange` | `(isDark: boolean) => void` | `-` | Yes |-| `rounded` | `boolean` | `false` | No || `src` | `string` | `-` | No |diff --git a/apps/v4/content/docs/components/xlsx-viewer.mdx b/apps/v4/content/docs/components/xlsx-viewer.mdxindex 8a2f1e4..8f41ec7 100644--- a/apps/v4/content/docs/components/xlsx-viewer.mdx+++ b/apps/v4/content/docs/components/xlsx-viewer.mdx@@ -66,5 +66,4 @@ The XlsxViewerPreview component renders an Excel workbook with upload, theme, zo| `fileName` | `string` | `-` | No || `isDark` | `boolean` | `-` | Yes || `onIsDarkChange` | `(isDark: boolean) => void` | `-` | Yes |-| `rounded` | `boolean` | `false` | No || `src` | `string` | `-` | No |diff --git a/apps/v4/package.json b/apps/v4/package.jsonindex 8dd0293..077463c 100644--- a/apps/v4/package.json+++ b/apps/v4/package.json@@ -36,7 +36,7 @@"@embedpdf/plugin-tiling": "^2.14.4","@embedpdf/plugin-viewport": "^2.14.4","@embedpdf/plugin-zoom": "^2.14.4",- "@extend-ai/react-docx": "0.7.0-alpha.6",+ "@extend-ai/react-docx": "0.7.0-alpha.7","@extend-ai/react-xlsx": "0.10.2","@glideapps/glide-data-grid": "6.0.4-alpha24","@hugeicons/core-free-icons": "^4.2.0",diff --git a/apps/v4/registry.json b/apps/v4/registry.jsonindex 1080736..6cad85e 100644--- a/apps/v4/registry.json+++ b/apps/v4/registry.json@@ -653,7 +653,7 @@"title": "DOCX Viewer","description": "A DOCX viewer with upload, zoom, theme controls, and read-only rendering.","dependencies": [- "@extend-ai/react-docx@^0.7.0-alpha.6",+ "@extend-ai/react-docx@^0.7.0-alpha.7","@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6"],@@ -684,7 +684,7 @@"description": "An experimental DOCX editor with a Word-style toolbar, page thumbnails, import, export, and live document mutation.","dependencies": ["@base-ui/react@^1.4.1",- "@extend-ai/react-docx@^0.7.0-alpha.6",+ "@extend-ai/react-docx@^0.7.0-alpha.7","@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6"],diff --git a/apps/v4/registry/new-york-v4/blocks/e-signature.tsx b/apps/v4/registry/new-york-v4/blocks/e-signature.tsxindex 1cf4369..a5e6f38 100644--- a/apps/v4/registry/new-york-v4/blocks/e-signature.tsx+++ b/apps/v4/registry/new-york-v4/blocks/e-signature.tsx@@ -559,8 +559,6 @@ export function ESignatureBlock({ file }: { file?: string }) {<PDFViewersrc={file}defaultZoom={DEFAULT_ZOOM}- pageWidth={PAGE_WIDTH}- pageHeight={PAGE_HEIGHT}toolbarActions={<Buttontype="button"diff --git a/apps/v4/registry/new-york-v4/ui/dropdown-menu.tsx b/apps/v4/registry/new-york-v4/ui/dropdown-menu.tsxindex 1db9c4a..3d227e3 100644--- a/apps/v4/registry/new-york-v4/ui/dropdown-menu.tsx+++ b/apps/v4/registry/new-york-v4/ui/dropdown-menu.tsx@@ -148,24 +148,44 @@ function DropdownMenuCheckboxItem({className,children,checked,+ variant = "default",...props-}: DropdownMenuPrimitive.CheckboxItem.Props): React.ReactElement {+}: DropdownMenuPrimitive.CheckboxItem.Props & {+ variant?: "default" | "switch"+}): React.ReactElement {return (<DropdownMenuPrimitive.CheckboxItemchecked={checked}className={cn(- "relative flex min-h-8 cursor-default items-center gap-2 rounded-sm py-1 ps-8 pe-2 text-base outline-none select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground sm:min-h-7 sm:text-sm data-disabled:pointer-events-none data-disabled:opacity-64 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4",+ "relative flex min-h-8 cursor-default items-center gap-2 rounded-sm py-1 pe-2 text-base outline-none select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground sm:min-h-7 sm:text-sm data-disabled:pointer-events-none data-disabled:opacity-64 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4",+ variant === "default" && "ps-8",+ variant === "switch" && "justify-between ps-2",className)}data-slot="dropdown-menu-checkbox-item"+ data-variant={variant}{...props}>- <span className="pointer-events-none absolute start-2 flex size-4 items-center justify-center">- <DropdownMenuPrimitive.CheckboxItemIndicator>- <HugeiconsIcon icon={Tick02Icon} />- </DropdownMenuPrimitive.CheckboxItemIndicator>- </span>+ {variant === "switch" ? null : (+ <span className="pointer-events-none absolute start-2 flex size-4 items-center justify-center">+ <DropdownMenuPrimitive.CheckboxItemIndicator>+ <HugeiconsIcon icon={Tick02Icon} />+ </DropdownMenuPrimitive.CheckboxItemIndicator>+ </span>+ )}{children}+ {variant === "switch" ? (+ <span+ aria-hidden="true"+ className="pointer-events-none relative ms-4 inline-flex h-4 w-7 shrink-0 items-center rounded-full bg-input transition-colors data-[checked=true]:bg-primary"+ data-checked={checked ? "true" : "false"}+ >+ <span+ className="size-3 translate-x-0.5 rounded-full bg-background shadow-xs transition-transform data-[checked=true]:translate-x-3.5"+ data-checked={checked ? "true" : "false"}+ />+ </span>+ ) : null}</DropdownMenuPrimitive.CheckboxItem>)}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 692dfb0..1b24aa3 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -73,8 +73,8 @@ importers:specifier: ^2.14.4version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'@extend-ai/react-docx':- specifier: 0.7.0-alpha.6+ specifier: 0.7.0-alpha.7'@extend-ai/react-xlsx':specifier: 0.10.2@@ -1055,8 +1055,8 @@ packages:resolution: {integrity: sha512-ZAoA40rNMPwSm+AeHpCq8STiNAwzWLJuP8Xv4CHIc9wv/PSuExjMrmjfYNj682vW0OOiZ1HKxzvjQr9XZIisQA==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}- '@extend-ai/[email protected]':- resolution: {integrity: sha512-CxAd1oFR06U9CrIe2VOYBTKPL+IScmgzrZqpsOQd9xgqGoyekl84xSnGlcPqKs6I9jr51wv7amOs7LiDLFdn0A==}+ '@extend-ai/[email protected]':+ resolution: {integrity: sha512-9j2BCc+UPThnVIANGYEnkk5+JDdyeni267LqDYzwqNdGx1VjKFlXCG5q54PWUaDHjARJ3Qfyxp6m6WO7xAmxrg==}peerDependencies:react: '>=18'react-dom: '>=18'@@ -6154,7 +6154,7 @@ snapshots:'@eslint/core': 0.13.0levn: 0.4.1dependencies:'@chenglou/pretext': 0.0.5