TypeScript
Restore DOCX thumbnails after react-docx upgrade
Andrew Luo10a67d91f5fd
diff --git a/apps/v4/app/(app)/layout.tsx b/apps/v4/app/(app)/layout.tsxindex ca5f8e1..7275215 100644--- a/apps/v4/app/(app)/layout.tsx+++ b/apps/v4/app/(app)/layout.tsx@@ -5,7 +5,7 @@ export default function AppLayout({ children }: { children: React.ReactNode }) {return (<divdata-slot="layout"- className="group/layout relative z-10 flex min-h-svh flex-col bg-background has-data-[slot=designer]:h-svh has-data-[slot=designer]:overflow-hidden"+ className="group/layout relative isolate z-10 flex min-h-svh flex-col bg-background has-data-[slot=designer]:h-svh has-data-[slot=designer]:overflow-hidden"><SiteHeader /><main className="flex min-h-0 flex-1 flex-col">{children}</main>diff --git a/apps/v4/app/globals.css b/apps/v4/app/globals.cssindex e885713..8091491 100644--- a/apps/v4/app/globals.css+++ b/apps/v4/app/globals.css@@ -93,38 +93,46 @@:root {--radius: 0.625rem;- --background: oklch(1 0 0);- --foreground: oklch(0.145 0 0);- --card: oklch(1 0 0);- --card-foreground: oklch(0.145 0 0);- --popover: oklch(1 0 0);- --popover-foreground: oklch(0.145 0 0);- --primary: oklch(0.205 0 0);- --primary-foreground: oklch(0.985 0 0);- --secondary: oklch(0.97 0 0);- --secondary-foreground: oklch(0.205 0 0);- --muted: oklch(0.97 0 0);- --muted-foreground: oklch(0.556 0 0);- --accent: oklch(0.97 0 0);- --accent-foreground: oklch(0.205 0 0);- --destructive: oklch(0.577 0.245 27.325);- --destructive-foreground: oklch(0.97 0.01 17);- --border: oklch(0.922 0 0);- --input: oklch(0.922 0 0);- --ring: oklch(0.708 0 0);+ --background: var(--color-white);+ --foreground: var(--color-neutral-800);+ --card: var(--color-white);+ --card-foreground: var(--color-neutral-800);+ --popover: var(--color-white);+ --popover-foreground: var(--color-neutral-800);+ --primary: var(--color-neutral-800);+ --primary-foreground: var(--color-neutral-50);+ --secondary: --alpha(var(--color-black) / 4%);+ --secondary-foreground: var(--color-neutral-800);+ --muted: --alpha(var(--color-black) / 4%);+ --muted-foreground: color-mix(+ in srgb,+ var(--color-neutral-500) 90%,+ var(--color-black)+ );+ --accent: --alpha(var(--color-black) / 4%);+ --accent-foreground: var(--color-neutral-800);+ --destructive: var(--color-red-500);+ --destructive-foreground: var(--color-red-700);+ --border: --alpha(var(--color-black) / 8%);+ --input: --alpha(var(--color-black) / 10%);+ --ring: var(--color-neutral-400);--chart-1: var(--color-blue-300);--chart-2: var(--color-blue-500);--chart-3: var(--color-blue-600);--chart-4: var(--color-blue-700);--chart-5: var(--color-blue-800);- --sidebar: oklch(0.985 0 0);- --sidebar-foreground: oklch(0.145 0 0);- --sidebar-primary: oklch(0.205 0 0);- --sidebar-primary-foreground: oklch(0.985 0 0);- --sidebar-accent: oklch(0.97 0 0);- --sidebar-accent-foreground: oklch(0.205 0 0);- --sidebar-border: oklch(0.922 0 0);- --sidebar-ring: oklch(0.708 0 0);+ --sidebar: var(--color-neutral-50);+ --sidebar-foreground: color-mix(+ in srgb,+ var(--color-neutral-800) 64%,+ var(--sidebar)+ );+ --sidebar-primary: var(--color-neutral-800);+ --sidebar-primary-foreground: var(--color-neutral-50);+ --sidebar-accent: --alpha(var(--color-black) / 4%);+ --sidebar-accent-foreground: var(--color-neutral-800);+ --sidebar-border: --alpha(var(--color-black) / 6%);+ --sidebar-ring: var(--color-neutral-400);--surface: oklch(0.98 0 0);--surface-foreground: var(--foreground);--code: var(--surface);@@ -142,38 +150,58 @@}.dark {- --background: oklch(0.145 0 0);- --foreground: oklch(0.985 0 0);- --card: oklch(0.205 0 0);- --card-foreground: oklch(0.985 0 0);- --popover: oklch(0.205 0 0);- --popover-foreground: oklch(0.985 0 0);- --primary: oklch(0.922 0 0);- --primary-foreground: oklch(0.205 0 0);- --secondary: oklch(0.269 0 0);- --secondary-foreground: oklch(0.985 0 0);- --muted: oklch(0.269 0 0);- --muted-foreground: oklch(0.708 0 0);- --accent: oklch(0.371 0 0);- --accent-foreground: oklch(0.985 0 0);- --destructive: oklch(0.704 0.191 22.216);- --destructive-foreground: oklch(0.58 0.22 27);- --border: oklch(1 0 0 / 10%);- --input: oklch(1 0 0 / 15%);- --ring: oklch(0.556 0 0);+ --background: color-mix(+ in srgb,+ var(--color-neutral-950) 95%,+ var(--color-white)+ );+ --foreground: var(--color-neutral-100);+ --card: color-mix(in srgb, var(--background) 98%, var(--color-white));+ --card-foreground: var(--color-neutral-100);+ --popover: color-mix(in srgb, var(--background) 98%, var(--color-white));+ --popover-foreground: var(--color-neutral-100);+ --primary: var(--color-neutral-100);+ --primary-foreground: var(--color-neutral-800);+ --secondary: --alpha(var(--color-white) / 4%);+ --secondary-foreground: var(--color-neutral-100);+ --muted: --alpha(var(--color-white) / 4%);+ --muted-foreground: color-mix(+ in srgb,+ var(--color-neutral-500) 90%,+ var(--color-white)+ );+ --accent: --alpha(var(--color-white) / 4%);+ --accent-foreground: var(--color-neutral-100);+ --destructive: color-mix(+ in srgb,+ var(--color-red-500) 90%,+ var(--color-white)+ );+ --destructive-foreground: var(--color-red-400);+ --border: --alpha(var(--color-white) / 6%);+ --input: --alpha(var(--color-white) / 8%);+ --ring: var(--color-neutral-500);--chart-1: var(--color-blue-300);--chart-2: var(--color-blue-500);--chart-3: var(--color-blue-600);--chart-4: var(--color-blue-700);--chart-5: var(--color-blue-800);- --sidebar: oklch(0.205 0 0);- --sidebar-foreground: oklch(0.985 0 0);- --sidebar-primary: oklch(0.488 0.243 264.376);- --sidebar-primary-foreground: oklch(0.985 0 0);- --sidebar-accent: oklch(0.269 0 0);- --sidebar-accent-foreground: oklch(0.985 0 0);- --sidebar-border: oklch(1 0 0 / 10%);- --sidebar-ring: oklch(0.439 0 0);+ --sidebar: color-mix(+ in srgb,+ var(--color-neutral-950) 97%,+ var(--color-white)+ );+ --sidebar-foreground: color-mix(+ in srgb,+ var(--color-neutral-100) 64%,+ var(--sidebar)+ );+ --sidebar-primary: var(--color-neutral-100);+ --sidebar-primary-foreground: var(--color-neutral-800);+ --sidebar-accent: --alpha(var(--color-white) / 4%);+ --sidebar-accent-foreground: var(--color-neutral-100);+ --sidebar-border: --alpha(var(--color-white) / 5%);+ --sidebar-ring: var(--color-neutral-400);--surface: oklch(0.2 0 0);--surface-foreground: oklch(0.708 0 0);--code: var(--surface);diff --git a/apps/v4/app/layout.tsx b/apps/v4/app/layout.tsxindex d58139f..633c765 100644--- a/apps/v4/app/layout.tsx+++ b/apps/v4/app/layout.tsx@@ -86,7 +86,7 @@ export default function RootLayout({</head><bodyclassName={cn(- "group/body overscroll-none antialiased [--footer-height:calc(var(--spacing)*14)] [--header-height:calc(var(--spacing)*14)] xl:[--footer-height:calc(var(--spacing)*24)]"+ "group/body relative overscroll-none antialiased [--footer-height:calc(var(--spacing)*14)] [--header-height:calc(var(--spacing)*14)] xl:[--footer-height:calc(var(--spacing)*24)]")}><ThemeProvider>diff --git a/apps/v4/components/csv-viewer-docs.tsx b/apps/v4/components/csv-viewer-docs.tsxindex 8512608..b0fc812 100644--- a/apps/v4/components/csv-viewer-docs.tsx+++ b/apps/v4/components/csv-viewer-docs.tsx@@ -247,26 +247,6 @@ function parseDelimitedText(text: string): {}}-function useIsDarkTheme() {- const [isDark, setIsDark] = React.useState(false)-- React.useEffect(() => {- const update = () =>- setIsDark(document.documentElement.classList.contains("dark"))- update()-- const observer = new MutationObserver(update)- observer.observe(document.documentElement, {- attributeFilter: ["class"],- attributes: true,- })-- return () => observer.disconnect()- }, [])-- return isDark-}-function ToolbarTooltip({label,children,@@ -286,7 +266,7 @@ function ToolbarTooltip({export function CsvViewer({ className, data }: CsvViewerProps) {const inputRef = React.useRef<HTMLInputElement | null>(null)- const isDark = useIsDarkTheme()+ const isDark = falseconst [glide, setGlide] = React.useState<GlideDataGridModule | null>(null)const [zoom, setZoom] = React.useState<(typeof ZOOM_OPTIONS)[number]>(1)const [parsed, setParsed] = React.useState(() =>diff --git a/apps/v4/components/docs-copy-page.tsx b/apps/v4/components/docs-copy-page.tsxindex 8f57351..0df4bae 100644--- a/apps/v4/components/docs-copy-page.tsx+++ b/apps/v4/components/docs-copy-page.tsx@@ -6,6 +6,7 @@ import { HugeiconsIcon } from "@hugeicons/react"import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard"import { Button } from "@/components/ui/button"+import { Group, GroupSeparator } from "@/components/ui/group"import { CopyButtonIcon } from "@/components/copy-button"import {DropdownMenu,@@ -15,11 +16,9 @@ import {} from "@/registry/new-york-v4/ui/dropdown-menu"import {Popover,- PopoverAnchor,PopoverContent,PopoverTrigger,} from "@/registry/new-york-v4/ui/popover"-import { Separator } from "@/registry/new-york-v4/ui/separator"function getPromptUrl(baseURL: string, url: string) {return `${baseURL}?q=${encodeURIComponent(@@ -159,33 +158,39 @@ const menuItems = {export function DocsCopyPage({ page, url }: { page: string; url: string }) {const { copyToClipboard, isCopied } = useCopyToClipboard()- const trigger = (+ const handleCopyPage = React.useCallback(() => {+ copyToClipboard(page)+ }, [copyToClipboard, page])++ const renderTrigger = (mobile = false) => (<Buttonvariant="secondary"size="sm"- className="peer -ml-0.5 size-8 shadow-none md:size-7 md:text-[0.8rem]"+ className="size-8 px-0 shadow-none md:size-7 md:text-[0.8rem]"+ aria-label="Copy page options">- <HugeiconsIcon icon={ChevronDown} className="rotate-180 sm:rotate-0" />+ <HugeiconsIcon+ icon={ChevronDown}+ className={mobile ? "rotate-180" : undefined}+ /></Button>)return (- <Popover>- <div className="group/buttons relative flex rounded-lg bg-secondary *:[[data-slot=button]]:focus-visible:relative *:[[data-slot=button]]:focus-visible:z-10">- <PopoverAnchor />+ <>+ <Group className="hidden rounded-lg bg-secondary sm:flex"><Buttonvariant="secondary"size="sm"className="h-8 shadow-none md:h-7 md:text-[0.8rem]"- onClick={() => copyToClipboard(page)}+ onClick={handleCopyPage}><CopyButtonIcon copied={isCopied} />Copy Page</Button>- <DropdownMenu>- <DropdownMenuTrigger asChild className="hidden sm:flex">- {trigger}- </DropdownMenuTrigger>+ <GroupSeparator className="h-8! bg-foreground/5! md:h-7!" />+ <DropdownMenu modal={false}>+ <DropdownMenuTrigger asChild>{renderTrigger()}</DropdownMenuTrigger><DropdownMenuContentalign="end"className="animate-none! rounded-lg shadow-none"@@ -197,13 +202,22 @@ export function DocsCopyPage({ page, url }: { page: string; url: string }) {))}</DropdownMenuContent></DropdownMenu>- <Separator- orientation="vertical"- className="absolute top-1 right-8 z-0 h-6! bg-foreground/5! peer-focus-visible:opacity-0 sm:right-7 sm:h-5!"- />- <PopoverTrigger asChild className="flex sm:hidden">- {trigger}- </PopoverTrigger>+ </Group>++ <Popover>+ <Group className="flex rounded-lg bg-secondary sm:hidden">+ <Button+ variant="secondary"+ size="sm"+ className="h-8 shadow-none"+ onClick={handleCopyPage}+ >+ <CopyButtonIcon copied={isCopied} />+ Copy Page+ </Button>+ <GroupSeparator className="h-8! bg-foreground/5!" />+ <PopoverTrigger asChild>{renderTrigger(true)}</PopoverTrigger>+ </Group><PopoverContentclassName="w-52 origin-center! rounded-lg bg-background/70 p-1 shadow-none backdrop-blur-sm dark:bg-background/60"align="start"@@ -224,7 +238,7 @@ export function DocsCopyPage({ page, url }: { page: string; url: string }) {)})}</PopoverContent>- </div>- </Popover>+ </Popover>+ </>)}diff --git a/apps/v4/components/docx-editor-docs.tsx b/apps/v4/components/docx-editor-docs.tsxindex 3e57c94..5691e04 100644--- a/apps/v4/components/docx-editor-docs.tsx+++ b/apps/v4/components/docx-editor-docs.tsx@@ -90,7 +90,7 @@ export function DocxEditorExample() {}`const docxEditorSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n DocxEditorViewer,\n paragraphLetterheadFloatSideAtNodeIndex,\n useDocxBorders,\n useDocxDocumentTheme,\n useDocxEditor,\n useDocxLineSpacing,\n useDocxPageLayout,\n useDocxParagraphStyles,\n useDocxTrackChanges,\n useDocxViewerThumbnails,\n type DocxBorderContext,\n type DocxBorderPreset,\n type DocxDocumentTheme,\n type DocxEditorController,\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 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"\nimport { useTheme } from "next-themes"\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 { Spinner } from "@/components/ui/spinner"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/registry/new-york-v4/ui/dropdown-menu"\nimport { Separator } from "@/registry/new-york-v4/ui/separator"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_SOURCE_CACHE_LIMIT = 3\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst DOCX_EDITOR_DEFAULT_ZOOM_SCALE = 75\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 DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\n\nconst docxFileCache = new Map<string, File>()\nconst docxFilePromiseCache = new Map<string, Promise<File>>()\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\nfunction getDocumentCacheKey(url: string, fileName?: string) {\n return `${url.split("?")[0] ?? url}::${fileName ?? ""}`\n}\n\nfunction rememberDocxFile(cacheKey: string, file: File) {\n if (docxFileCache.has(cacheKey)) {\n docxFileCache.delete(cacheKey)\n }\n\n docxFileCache.set(cacheKey, file)\n\n while (docxFileCache.size > DOCX_SOURCE_CACHE_LIMIT) {\n const oldestKey = docxFileCache.keys().next().value\n if (!oldestKey) break\n docxFileCache.delete(oldestKey)\n }\n}\n\nasync function loadCachedDocxFile(\n url: string,\n displayFileName: string,\n cacheKey: string\n): Promise<File> {\n const cachedFile = docxFileCache.get(cacheKey)\n if (cachedFile) return cachedFile\n\n const pendingRequest = docxFilePromiseCache.get(cacheKey)\n if (pendingRequest) return pendingRequest\n\n const nextRequest = fetch(url)\n .then(async (response) => {\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n const docxFile = new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n\n rememberDocxFile(cacheKey, docxFile)\n return docxFile\n })\n .finally(() => {\n docxFilePromiseCache.delete(cacheKey)\n })\n\n docxFilePromiseCache.set(cacheKey, nextRequest)\n return nextRequest\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 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 useDocumentNightRenderPreference() {\n const [nightRenderEnabled, setNightRenderEnabled] = React.useState(false)\n const [nightRenderPrefLoaded, setNightRenderPrefLoaded] =\n React.useState(false)\n\n React.useEffect(() => {\n const storedValue = window.localStorage.getItem("docx-editor-night-render")\n setNightRenderEnabled(storedValue !== "false")\n setNightRenderPrefLoaded(true)\n }, [])\n\n const updateNightRenderEnabled = React.useCallback((checked: boolean) => {\n setNightRenderEnabled(checked)\n window.localStorage.setItem("docx-editor-night-render", String(checked))\n }, [])\n\n return {\n nightRenderEnabled,\n nightRenderPrefLoaded,\n setNightRenderEnabled: updateNightRenderEnabled,\n }\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 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="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 renderDocumentPreview={false}\n isLoading={isLoading}\n hasError={hasError}\n showMetadata={false}\n className={cn(\n "w-full rounded-sm border shadow-xs transition-[border-color,box-shadow] duration-150",\n isActive && "border-primary shadow-sm"\n )}\n />\n )\n}\n\nfunction DocxEditorToolbar({\n activePage,\n controlsDisabled,\n editor,\n isReadOnly,\n onImageUploadClick,\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 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 selectedRunStyle = editor.selectedRunStyle\n const selectedParagraph = editor.selectedParagraph\n const paragraphStyleOptions =\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 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="border-b 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 setDocumentTheme(documentTheme === "dark" ? "light" : "dark")\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={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 <Select\n value={selectedParagraphStyleValue}\n onValueChange={(value) => {\n if (value) {\n setParagraphStyle(value)\n }\n }}\n disabled={!canEdit}\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 align="start" className="z-[100010]">\n {paragraphStyleOptions.map((option) => (\n <SelectItem key={option.id} value={option.id}>\n {option.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={selectedRunStyle?.fontFamily ?? "Calibri"}\n onValueChange={(value) => {\n if (value) {\n editor.setFontFamily(value)\n }\n }}\n disabled={!canEdit}\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 align="start" className="z-[100010]">\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 >\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 align="start" className="z-[100010]">\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 >\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 align="start" className="z-[100010]">\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-[100010] 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-[100010] 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 shrink-0 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 >\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" className="z-[100010]">\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 fileName,\n rounded = false,\n src,\n}: {\n className?: string\n fileName?: string\n rounded?: boolean\n src?: string\n}) {\n const { resolvedTheme } = useTheme()\n const { nightRenderEnabled, nightRenderPrefLoaded, setNightRenderEnabled } =\n useDocumentNightRenderPreference()\n const isViewerHydrated = resolvedTheme !== undefined && nightRenderPrefLoaded\n const shouldShowHydrationSpinner = useDelayedLoadingIndicator(\n !isViewerHydrated,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n\n if (!isViewerHydrated) {\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 <div\n className={cn(\n "min-h-0 flex-1 overflow-hidden bg-muted/30 p-4",\n rounded && "rounded-b-lg"\n )}\n >\n <EditorLoadingSurface showSpinner={shouldShowHydrationSpinner} />\n </div>\n </div>\n )\n }\n\n const shouldRenderNightMode = resolvedTheme === "dark"\n const effectiveIsDark = shouldRenderNightMode && nightRenderEnabled\n\n return (\n <DocxEditorContent\n className={className}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={setNightRenderEnabled}\n shouldRenderNightMode={shouldRenderNightMode}\n url={src}\n />\n )\n}\n\nfunction DocxEditorContent({\n className,\n effectiveIsDark,\n fileName,\n rounded,\n setNightRenderEnabled: _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 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 [zoomScale, setZoomScale] = React.useState<number>(\n DOCX_EDITOR_DEFAULT_ZOOM_SCALE\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 cacheKey = React.useMemo(\n () =>\n uploadedDocxFile?.identity ??\n (url ? getDocumentCacheKey(url, displayFileName) : "docx-empty"),\n [displayFileName, uploadedDocxFile?.identity, 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 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(editor, thumbnailOptions)\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, editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(DOCX_EDITOR_DEFAULT_ZOOM_SCALE)\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 React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n if (!uploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url\n ? await loadCachedDocxFile(url, displayFileName, cacheKey)\n : 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 }, [cacheKey, 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(DOCX_EDITOR_DEFAULT_ZOOM_SCALE)\n setActivePage(1)\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 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={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 rounded-sm border 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 text-muted-foreground shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent"\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 <div\n ref={viewportRef}\n className={cn(\n "min-h-0 flex-1 overflow-auto p-4",\n rounded && "rounded-b-lg"\n )}\n style={{ backgroundColor: viewerBackgroundColor }}\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 loadingState={loadingState}\n pageBackgroundColor={\n editor.documentTheme === "dark" ? "#0a0a0a" : undefined\n }\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={{ enabled: false }}\n deferInitialPaginationPaint={false}\n />\n </div>\n </div>\n )}\n </div>\n </div>\n </div>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport {\n DocxEditorViewer,\n paragraphLetterheadFloatSideAtNodeIndex,\n useDocxBorders,\n useDocxDocumentTheme,\n useDocxEditor,\n useDocxLineSpacing,\n useDocxPageLayout,\n useDocxParagraphStyles,\n useDocxTrackChanges,\n useDocxViewerThumbnails,\n type DocxBorderContext,\n type DocxBorderPreset,\n type DocxDocumentTheme,\n type DocxEditorController,\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 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"\nimport { useTheme } from "next-themes"\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 { Spinner } from "@/components/ui/spinner"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/registry/new-york-v4/ui/dropdown-menu"\nimport { Separator } from "@/registry/new-york-v4/ui/separator"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_SOURCE_CACHE_LIMIT = 3\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst DOCX_EDITOR_DEFAULT_ZOOM_SCALE = 75\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 DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\n\nconst docxFileCache = new Map<string, File>()\nconst docxFilePromiseCache = new Map<string, Promise<File>>()\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\nfunction getDocumentCacheKey(url: string, fileName?: string) {\n return `${url.split("?")[0] ?? url}::${fileName ?? ""}`\n}\n\nfunction rememberDocxFile(cacheKey: string, file: File) {\n if (docxFileCache.has(cacheKey)) {\n docxFileCache.delete(cacheKey)\n }\n\n docxFileCache.set(cacheKey, file)\n\n while (docxFileCache.size > DOCX_SOURCE_CACHE_LIMIT) {\n const oldestKey = docxFileCache.keys().next().value\n if (!oldestKey) break\n docxFileCache.delete(oldestKey)\n }\n}\n\nasync function loadCachedDocxFile(\n url: string,\n displayFileName: string,\n cacheKey: string\n): Promise<File> {\n const cachedFile = docxFileCache.get(cacheKey)\n if (cachedFile) return cachedFile\n\n const pendingRequest = docxFilePromiseCache.get(cacheKey)\n if (pendingRequest) return pendingRequest\n\n const nextRequest = fetch(url)\n .then(async (response) => {\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n const docxFile = new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n\n rememberDocxFile(cacheKey, docxFile)\n return docxFile\n })\n .finally(() => {\n docxFilePromiseCache.delete(cacheKey)\n })\n\n docxFilePromiseCache.set(cacheKey, nextRequest)\n return nextRequest\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 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 useDocumentNightRenderPreference() {\n const [nightRenderEnabled, setNightRenderEnabled] = React.useState(false)\n const [nightRenderPrefLoaded, setNightRenderPrefLoaded] =\n React.useState(false)\n\n React.useEffect(() => {\n const storedValue = window.localStorage.getItem("docx-editor-night-render")\n setNightRenderEnabled(storedValue === "true")\n setNightRenderPrefLoaded(true)\n }, [])\n\n const updateNightRenderEnabled = React.useCallback((checked: boolean) => {\n setNightRenderEnabled(checked)\n window.localStorage.setItem("docx-editor-night-render", String(checked))\n }, [])\n\n return {\n nightRenderEnabled,\n nightRenderPrefLoaded,\n setNightRenderEnabled: updateNightRenderEnabled,\n }\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 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="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 renderDocumentPreview={false}\n isLoading={isLoading}\n hasError={hasError}\n showMetadata={false}\n className={cn(\n "w-full rounded-sm border shadow-xs transition-[border-color,box-shadow] duration-150",\n isActive && "border-primary shadow-sm"\n )}\n />\n )\n}\n\nfunction DocxEditorToolbar({\n activePage,\n controlsDisabled,\n editor,\n isReadOnly,\n onImageUploadClick,\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 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 selectedRunStyle = editor.selectedRunStyle\n const selectedParagraph = editor.selectedParagraph\n const paragraphStyleOptions =\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 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="border-b 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 setDocumentTheme(documentTheme === "dark" ? "light" : "dark")\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={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 <Select\n value={selectedParagraphStyleValue}\n onValueChange={(value) => {\n if (value) {\n setParagraphStyle(value)\n }\n }}\n disabled={!canEdit}\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 align="start" className="z-[100010]">\n {paragraphStyleOptions.map((option) => (\n <SelectItem key={option.id} value={option.id}>\n {option.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={selectedRunStyle?.fontFamily ?? "Calibri"}\n onValueChange={(value) => {\n if (value) {\n editor.setFontFamily(value)\n }\n }}\n disabled={!canEdit}\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 align="start" className="z-[100010]">\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 >\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 align="start" className="z-[100010]">\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 >\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 align="start" className="z-[100010]">\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-[100010] 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-[100010] 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 shrink-0 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 >\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" className="z-[100010]">\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 fileName,\n rounded = false,\n src,\n}: {\n className?: string\n fileName?: string\n rounded?: boolean\n src?: string\n}) {\n const { resolvedTheme } = useTheme()\n const { nightRenderEnabled, nightRenderPrefLoaded, setNightRenderEnabled } =\n useDocumentNightRenderPreference()\n const isViewerHydrated = resolvedTheme !== undefined && nightRenderPrefLoaded\n const shouldShowHydrationSpinner = useDelayedLoadingIndicator(\n !isViewerHydrated,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n\n if (!isViewerHydrated) {\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 <div\n className={cn(\n "min-h-0 flex-1 overflow-hidden bg-muted/30 p-4",\n rounded && "rounded-b-lg"\n )}\n >\n <EditorLoadingSurface showSpinner={shouldShowHydrationSpinner} />\n </div>\n </div>\n )\n }\n\n const shouldRenderNightMode = resolvedTheme === "dark"\n const effectiveIsDark = shouldRenderNightMode && nightRenderEnabled\n\n return (\n <DocxEditorContent\n className={className}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={setNightRenderEnabled}\n shouldRenderNightMode={shouldRenderNightMode}\n url={src}\n />\n )\n}\n\nfunction DocxEditorContent({\n className,\n effectiveIsDark,\n fileName,\n rounded,\n setNightRenderEnabled: _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 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 [zoomScale, setZoomScale] = React.useState<number>(\n DOCX_EDITOR_DEFAULT_ZOOM_SCALE\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 cacheKey = React.useMemo(\n () =>\n uploadedDocxFile?.identity ??\n (url ? getDocumentCacheKey(url, displayFileName) : "docx-empty"),\n [displayFileName, uploadedDocxFile?.identity, 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 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(editor, thumbnailOptions)\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, editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(DOCX_EDITOR_DEFAULT_ZOOM_SCALE)\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 React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n if (!uploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url\n ? await loadCachedDocxFile(url, displayFileName, cacheKey)\n : 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 }, [cacheKey, 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(DOCX_EDITOR_DEFAULT_ZOOM_SCALE)\n setActivePage(1)\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 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={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 rounded-sm border 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 text-muted-foreground shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent"\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 <div\n ref={viewportRef}\n className={cn(\n "min-h-0 flex-1 overflow-auto p-4",\n rounded && "rounded-b-lg"\n )}\n style={{ backgroundColor: viewerBackgroundColor }}\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 loadingState={loadingState}\n pageBackgroundColor={\n editor.documentTheme === "dark" ? "#0a0a0a" : undefined\n }\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={{ enabled: false }}\n deferInitialPaginationPaint={false}\n />\n </div>\n </div>\n )}\n </div>\n </div>\n </div>\n )\n}\n'export function DocxEditorSource() {return <HighlightedCodeBlock code={docxEditorSourceCode} />diff --git a/apps/v4/components/docx-viewer-docs.tsx b/apps/v4/components/docx-viewer-docs.tsxindex 437808c..ecda382 100644--- a/apps/v4/components/docx-viewer-docs.tsx+++ b/apps/v4/components/docx-viewer-docs.tsx@@ -94,7 +94,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} from "@extend-ai/react-docx"\nimport {\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n SidebarLeftIcon,\n Sun03Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { useTheme } from "next-themes"\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 { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Spinner } from "@/components/ui/spinner"\nimport { Separator } from "@/registry/new-york-v4/ui/separator"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_SOURCE_CACHE_LIMIT = 3\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\nconst docxFileCache = new Map<string, File>()\nconst docxFilePromiseCache = new Map<string, Promise<File>>()\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n}\n\nfunction getDocumentCacheKey(url: string, fileName?: string) {\n return `${url.split("?")[0] ?? url}::${fileName ?? ""}`\n}\n\nfunction rememberDocxFile(cacheKey: string, file: File) {\n if (docxFileCache.has(cacheKey)) {\n docxFileCache.delete(cacheKey)\n }\n\n docxFileCache.set(cacheKey, file)\n\n while (docxFileCache.size > DOCX_SOURCE_CACHE_LIMIT) {\n const oldestKey = docxFileCache.keys().next().value\n if (!oldestKey) break\n docxFileCache.delete(oldestKey)\n }\n}\n\nasync function loadCachedDocxFile(\n url: string,\n displayFileName: string,\n cacheKey: string\n): Promise<File> {\n const cachedFile = docxFileCache.get(cacheKey)\n if (cachedFile) return cachedFile\n\n const pendingRequest = docxFilePromiseCache.get(cacheKey)\n if (pendingRequest) return pendingRequest\n\n const nextRequest = fetch(url)\n .then(async (response) => {\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n const docxFile = new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n\n rememberDocxFile(cacheKey, docxFile)\n return docxFile\n })\n .finally(() => {\n docxFilePromiseCache.delete(cacheKey)\n })\n\n docxFilePromiseCache.set(cacheKey, nextRequest)\n return nextRequest\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 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 useDocumentNightRenderPreference() {\n const [nightRenderEnabled, setNightRenderEnabled] = React.useState(false)\n const [nightRenderPrefLoaded, setNightRenderPrefLoaded] =\n React.useState(false)\n\n React.useEffect(() => {\n const storedValue = window.localStorage.getItem("docx-night-render")\n setNightRenderEnabled(storedValue !== "false")\n setNightRenderPrefLoaded(true)\n }, [])\n\n const updateNightRenderEnabled = React.useCallback((checked: boolean) => {\n setNightRenderEnabled(checked)\n window.localStorage.setItem("docx-night-render", String(checked))\n }, [])\n\n return {\n nightRenderEnabled,\n nightRenderPrefLoaded,\n setNightRenderEnabled: updateNightRenderEnabled,\n }\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 DocxToolbar({\n activePage,\n controlsDisabled,\n isDark,\n onIsDarkChange,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showNightRenderToggle,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n isDark: boolean\n onIsDarkChange: (checked: boolean) => 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 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 items-center justify-between gap-3 overflow-x-auto overflow-y-hidden border-b bg-background px-3">\n <TooltipProvider>\n <div className="flex 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 <div className="text-sm whitespace-nowrap text-primary">\n Page {pageCount ? activePage : 1} of {pageCount || "-"}\n </div>\n </div>\n <div className="ml-auto flex shrink-0 items-center gap-1">\n {showNightRenderToggle ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\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={\n isDark ? "Use light document" : "Use dark document"\n }\n onClick={() => onIsDarkChange(!isDark)}\n >\n <HugeiconsIcon\n icon={isDark ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </>\n ) : null}\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\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 >\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">\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 <Separator orientation="vertical" className="mx-1 h-4 self-center" />\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 </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="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 renderDocumentPreview={false}\n isLoading={isLoading}\n hasError={hasError}\n showMetadata={false}\n className={cn(\n "w-full rounded-sm border shadow-xs transition-[border-color,box-shadow] duration-150",\n isActive && "border-primary shadow-sm"\n )}\n />\n )\n}\n\nexport function DocxViewerPreview({\n className,\n defaultThumbnailSidebarOpen = true,\n fileName,\n rounded = false,\n src,\n}: {\n className?: string\n defaultThumbnailSidebarOpen?: boolean\n fileName?: string\n rounded?: boolean\n src?: string\n}) {\n const { resolvedTheme } = useTheme()\n const { nightRenderEnabled, nightRenderPrefLoaded, setNightRenderEnabled } =\n useDocumentNightRenderPreference()\n const isViewerHydrated = resolvedTheme !== undefined && nightRenderPrefLoaded\n const shouldShowHydrationSpinner = useDelayedLoadingIndicator(\n !isViewerHydrated,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n\n if (!isViewerHydrated) {\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 <div\n className={cn(\n "min-h-0 flex-1 overflow-hidden bg-muted/30 p-4",\n rounded && "rounded-b-lg"\n )}\n >\n <ViewerLoadingSurface showSpinner={shouldShowHydrationSpinner} />\n </div>\n </div>\n )\n }\n\n const shouldRenderNightMode = resolvedTheme === "dark"\n const effectiveIsDark = shouldRenderNightMode && nightRenderEnabled\n\n return (\n <DocxViewerContent\n className={className}\n defaultThumbnailSidebarOpen={defaultThumbnailSidebarOpen}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={setNightRenderEnabled}\n shouldRenderNightMode={shouldRenderNightMode}\n url={src}\n />\n )\n}\n\nfunction DocxViewerContent({\n className,\n defaultThumbnailSidebarOpen,\n effectiveIsDark,\n fileName,\n rounded,\n setNightRenderEnabled,\n shouldRenderNightMode,\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 url?: string\n}) {\n const fileInputRef = 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(\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 cacheKey = React.useMemo(\n () =>\n uploadedDocxFile?.identity ??\n (url ? getDocumentCacheKey(url, displayFileName) : "docx-empty"),\n [displayFileName, uploadedDocxFile?.identity, 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 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(editor, thumbnailOptions)\n const [zoomScale, setZoomScale] = React.useState(50)\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\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, editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(50)\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 React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n if (!uploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url\n ? await loadCachedDocxFile(url, displayFileName, cacheKey)\n : 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 }, [cacheKey, 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(50)\n setActivePage(1)\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 <DocxToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n isDark={effectiveIsDark}\n onIsDarkChange={setNightRenderEnabled}\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 <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 rounded-sm border 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 text-muted-foreground shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent"\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 <div\n ref={viewportRef}\n className={cn(\n "min-h-0 flex-1 overflow-auto p-4",\n rounded && "rounded-b-lg"\n )}\n style={{ backgroundColor: viewerBackgroundColor }}\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={{ enabled: false }}\n deferInitialPaginationPaint={false}\n />\n </div>\n </div>\n )}\n </div>\n </div>\n </div>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport {\n DocxEditorViewer,\n useDocxEditor,\n useDocxViewerThumbnails,\n type DocxDocumentTheme,\n} from "@extend-ai/react-docx"\nimport {\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n SidebarLeftIcon,\n Sun03Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { useTheme } from "next-themes"\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 { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Spinner } from "@/components/ui/spinner"\nimport { Separator } from "@/registry/new-york-v4/ui/separator"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_SOURCE_CACHE_LIMIT = 3\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\nconst docxFileCache = new Map<string, File>()\nconst docxFilePromiseCache = new Map<string, Promise<File>>()\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n}\n\nfunction getDocumentCacheKey(url: string, fileName?: string) {\n return `${url.split("?")[0] ?? url}::${fileName ?? ""}`\n}\n\nfunction rememberDocxFile(cacheKey: string, file: File) {\n if (docxFileCache.has(cacheKey)) {\n docxFileCache.delete(cacheKey)\n }\n\n docxFileCache.set(cacheKey, file)\n\n while (docxFileCache.size > DOCX_SOURCE_CACHE_LIMIT) {\n const oldestKey = docxFileCache.keys().next().value\n if (!oldestKey) break\n docxFileCache.delete(oldestKey)\n }\n}\n\nasync function loadCachedDocxFile(\n url: string,\n displayFileName: string,\n cacheKey: string\n): Promise<File> {\n const cachedFile = docxFileCache.get(cacheKey)\n if (cachedFile) return cachedFile\n\n const pendingRequest = docxFilePromiseCache.get(cacheKey)\n if (pendingRequest) return pendingRequest\n\n const nextRequest = fetch(url)\n .then(async (response) => {\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n const docxFile = new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n\n rememberDocxFile(cacheKey, docxFile)\n return docxFile\n })\n .finally(() => {\n docxFilePromiseCache.delete(cacheKey)\n })\n\n docxFilePromiseCache.set(cacheKey, nextRequest)\n return nextRequest\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 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 useDocumentNightRenderPreference() {\n const [nightRenderEnabled, setNightRenderEnabled] = React.useState(false)\n const [nightRenderPrefLoaded, setNightRenderPrefLoaded] =\n React.useState(false)\n\n React.useEffect(() => {\n const storedValue = window.localStorage.getItem("docx-night-render")\n setNightRenderEnabled(storedValue === "true")\n setNightRenderPrefLoaded(true)\n }, [])\n\n const updateNightRenderEnabled = React.useCallback((checked: boolean) => {\n setNightRenderEnabled(checked)\n window.localStorage.setItem("docx-night-render", String(checked))\n }, [])\n\n return {\n nightRenderEnabled,\n nightRenderPrefLoaded,\n setNightRenderEnabled: updateNightRenderEnabled,\n }\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 DocxToolbar({\n activePage,\n controlsDisabled,\n isDark,\n onIsDarkChange,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showNightRenderToggle,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n isDark: boolean\n onIsDarkChange: (checked: boolean) => 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 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 items-center justify-between gap-3 overflow-x-auto overflow-y-hidden border-b bg-background px-3">\n <TooltipProvider>\n <div className="flex 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 <div className="text-sm whitespace-nowrap text-primary">\n Page {pageCount ? activePage : 1} of {pageCount || "-"}\n </div>\n </div>\n <div className="ml-auto flex shrink-0 items-center gap-1">\n {showNightRenderToggle ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\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={\n isDark ? "Use light document" : "Use dark document"\n }\n onClick={() => onIsDarkChange(!isDark)}\n >\n <HugeiconsIcon\n icon={isDark ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </>\n ) : null}\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\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 >\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">\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 <Separator orientation="vertical" className="mx-1 h-4 self-center" />\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 </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="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 renderDocumentPreview={false}\n isLoading={isLoading}\n hasError={hasError}\n showMetadata={false}\n className={cn(\n "w-full rounded-sm border shadow-xs transition-[border-color,box-shadow] duration-150",\n isActive && "border-primary shadow-sm"\n )}\n />\n )\n}\n\nexport function DocxViewerPreview({\n className,\n defaultThumbnailSidebarOpen = true,\n fileName,\n rounded = false,\n src,\n}: {\n className?: string\n defaultThumbnailSidebarOpen?: boolean\n fileName?: string\n rounded?: boolean\n src?: string\n}) {\n const { resolvedTheme } = useTheme()\n const { nightRenderEnabled, nightRenderPrefLoaded, setNightRenderEnabled } =\n useDocumentNightRenderPreference()\n const isViewerHydrated = resolvedTheme !== undefined && nightRenderPrefLoaded\n const shouldShowHydrationSpinner = useDelayedLoadingIndicator(\n !isViewerHydrated,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n\n if (!isViewerHydrated) {\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 <div\n className={cn(\n "min-h-0 flex-1 overflow-hidden bg-muted/30 p-4",\n rounded && "rounded-b-lg"\n )}\n >\n <ViewerLoadingSurface showSpinner={shouldShowHydrationSpinner} />\n </div>\n </div>\n )\n }\n\n const shouldRenderNightMode = resolvedTheme === "dark"\n const effectiveIsDark = shouldRenderNightMode && nightRenderEnabled\n\n return (\n <DocxViewerContent\n className={className}\n defaultThumbnailSidebarOpen={defaultThumbnailSidebarOpen}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={setNightRenderEnabled}\n shouldRenderNightMode={shouldRenderNightMode}\n url={src}\n />\n )\n}\n\nfunction DocxViewerContent({\n className,\n defaultThumbnailSidebarOpen,\n effectiveIsDark,\n fileName,\n rounded,\n setNightRenderEnabled,\n shouldRenderNightMode,\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 url?: string\n}) {\n const fileInputRef = 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(\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 cacheKey = React.useMemo(\n () =>\n uploadedDocxFile?.identity ??\n (url ? getDocumentCacheKey(url, displayFileName) : "docx-empty"),\n [displayFileName, uploadedDocxFile?.identity, 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 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(editor, thumbnailOptions)\n const [zoomScale, setZoomScale] = React.useState(50)\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\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, editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(50)\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 React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n if (!uploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url\n ? await loadCachedDocxFile(url, displayFileName, cacheKey)\n : 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 }, [cacheKey, 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(50)\n setActivePage(1)\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 <DocxToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n isDark={effectiveIsDark}\n onIsDarkChange={setNightRenderEnabled}\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 <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 rounded-sm border 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 text-muted-foreground shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent"\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 <div\n ref={viewportRef}\n className={cn(\n "min-h-0 flex-1 overflow-auto p-4",\n rounded && "rounded-b-lg"\n )}\n style={{ backgroundColor: viewerBackgroundColor }}\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={{ enabled: false }}\n deferInitialPaginationPaint={false}\n />\n </div>\n </div>\n )}\n </div>\n </div>\n </div>\n )\n}\n'export function DocxViewerSource() {return <HighlightedCodeBlock code={docxViewerSourceCode} />diff --git a/apps/v4/components/file-thumbnail-docs.tsx b/apps/v4/components/file-thumbnail-docs.tsxindex 62a9572..0c12d9a 100644--- a/apps/v4/components/file-thumbnail-docs.tsx+++ b/apps/v4/components/file-thumbnail-docs.tsx@@ -912,7 +912,7 @@ function XlsxThumbnailContent({ file }: { file: DemoFile }) {}`const fileThumbnailSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n DocxEditorViewer,\n useDocxEditor,\n useDocxViewerThumbnails,\n} from "@extend-ai/react-docx"\nimport {\n useXlsxViewer,\n useXlsxViewerController,\n useXlsxViewerThumbnails,\n XlsxViewerProvider,\n} from "@extend-ai/react-xlsx"\nimport { File01Icon, FileImageIcon } from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport type * as ReactPdf from "react-pdf"\n\nimport { cn } from "@/lib/utils"\n\nexport type ThumbnailSource = string | File | Blob\n\nexport type ThumbnailFile = {\n name: string\n type: string\n size?: string | number\n source?: ThumbnailSource\n url?: string\n}\n\nexport type FileThumbnailProps = {\n file: ThumbnailFile | File\n className?: string\n previewAspectRatio?: number\n previewClassName?: string\n previewContent?: React.ReactNode\n previewImageUrl?: string | null\n source?: ThumbnailSource\n thumbnailWidth?: number\n generationDelayMs?: number\n renderDocumentPreview?: boolean\n isLoading?: boolean\n hasError?: boolean\n showMetadata?: boolean\n}\n\ntype NormalizedThumbnailFile = {\n name: string\n type: string\n size?: string | number\n source?: ThumbnailSource\n url?: string\n}\n\ntype ReactPdfModule = typeof ReactPdf\n\nfunction isBlobLike(value: unknown): value is Blob {\n return typeof Blob !== "undefined" && value instanceof Blob\n}\n\nfunction isFileLike(value: unknown): value is File {\n return typeof File !== "undefined" && value instanceof File\n}\n\nfunction normalizeFile(file: ThumbnailFile | File): NormalizedThumbnailFile {\n return {\n name: file.name,\n size:\n typeof file.size === "number"\n ? formatBytes(file.size)\n : (file.size as string | undefined),\n source: isFileLike(file) ? file : (file as ThumbnailFile).source,\n type: file.type,\n url: (file as ThumbnailFile).url,\n }\n}\n\nfunction getThumbnailSource(\n file: NormalizedThumbnailFile,\n source?: ThumbnailSource\n): ThumbnailSource | undefined {\n return source ?? file.source ?? file.url\n}\n\nfunction formatBytes(bytes: number) {\n if (!Number.isFinite(bytes) || bytes <= 0) return undefined\n\n const units = ["B", "KB", "MB", "GB"]\n let value = bytes\n let unitIndex = 0\n\n while (value >= 1024 && unitIndex < units.length - 1) {\n value /= 1024\n unitIndex += 1\n }\n\n const formatted =\n value >= 10 || unitIndex === 0 ? Math.round(value) : value.toFixed(1)\n return `${formatted} ${units[unitIndex]}`\n}\n\nfunction isImageFile(file: NormalizedThumbnailFile) {\n return file.type.startsWith("image/")\n}\n\nfunction isPdfFile(file: NormalizedThumbnailFile) {\n return (\n file.type === "application/pdf" || file.name.toLowerCase().endsWith(".pdf")\n )\n}\n\nfunction isDocxFile(file: NormalizedThumbnailFile) {\n return (\n file.type ===\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||\n file.name.toLowerCase().endsWith(".docx")\n )\n}\n\nfunction isXlsxFile(file: NormalizedThumbnailFile) {\n const fileName = file.name.toLowerCase()\n\n return (\n file.type ===\n "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||\n file.type === "application/vnd.ms-excel" ||\n fileName.endsWith(".xlsx") ||\n fileName.endsWith(".xls")\n )\n}\n\nfunction FileKindIcon({ file }: { file: NormalizedThumbnailFile }) {\n const icon = isImageFile(file) ? FileImageIcon : File01Icon\n\n return <HugeiconsIcon icon={icon} className="size-4" />\n}\n\nfunction useThumbnailActivation(delayMs: number) {\n const [isActive, setIsActive] = React.useState(delayMs <= 0)\n\n React.useEffect(() => {\n if (delayMs <= 0) {\n setIsActive(true)\n return\n }\n\n setIsActive(false)\n const timeout = window.setTimeout(() => {\n setIsActive(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeout)\n }, [delayMs])\n\n return isActive\n}\n\nfunction useObjectUrl() {\n const [objectUrl, setObjectUrl] = React.useState<string | null>(null)\n\n const updateObjectUrl = React.useCallback((blob: Blob) => {\n const nextUrl = URL.createObjectURL(blob)\n setObjectUrl((currentUrl) => {\n if (currentUrl) URL.revokeObjectURL(currentUrl)\n return nextUrl\n })\n }, [])\n\n React.useEffect(() => {\n return () => {\n if (objectUrl) URL.revokeObjectURL(objectUrl)\n }\n }, [objectUrl])\n\n return { objectUrl, updateObjectUrl }\n}\n\nfunction useSourceObjectUrl(source: ThumbnailSource | undefined) {\n const [objectUrl, setObjectUrl] = React.useState<string | null>(null)\n\n React.useEffect(() => {\n if (!source || typeof source === "string") {\n setObjectUrl(null)\n return\n }\n\n const nextUrl = URL.createObjectURL(source)\n setObjectUrl(nextUrl)\n\n return () => URL.revokeObjectURL(nextUrl)\n }, [source])\n\n if (!source) return undefined\n return typeof source === "string" ? source : (objectUrl ?? undefined)\n}\n\nasync function sourceToFile(\n source: ThumbnailSource,\n file: NormalizedThumbnailFile\n) {\n if (isFileLike(source)) return source\n\n if (isBlobLike(source)) {\n return new File([source], file.name, {\n type: source.type || file.type,\n })\n }\n\n const response = await fetch(source)\n if (!response.ok) {\n throw new Error(`Failed to fetch ${file.name} (${response.status})`)\n }\n\n const blob = await response.blob()\n\n return new File([blob], file.name, {\n type: blob.type || file.type,\n })\n}\n\nfunction canvasToBlob(canvas: HTMLCanvasElement | null) {\n if (!canvas) return Promise.resolve<Blob | null>(null)\n\n return new Promise<Blob | null>((resolve) => {\n const blobFromDataUrl = async () => {\n try {\n const dataUrl = canvas.toDataURL("image/png")\n const response = await fetch(dataUrl)\n return await response.blob()\n } catch {\n return null\n }\n }\n\n try {\n if (typeof canvas.toBlob === "function") {\n canvas.toBlob((blob) => {\n if (blob) {\n resolve(blob)\n return\n }\n\n void blobFromDataUrl().then(resolve)\n }, "image/png")\n return\n }\n\n void blobFromDataUrl().then(resolve)\n } catch {\n resolve(null)\n }\n })\n}\n\nexport function FileThumbnailLoadingOverlay() {\n return (\n <div\n aria-hidden="true"\n className="absolute inset-0 z-10 overflow-hidden bg-muted"\n >\n <div className="absolute inset-0 bg-muted" />\n <div className="absolute inset-0 animate-pulse bg-background/55 motion-reduce:animate-none" />\n </div>\n )\n}\n\nfunction FileThumbnailShell({\n file,\n className,\n previewAspectRatio,\n previewClassName,\n previewContent,\n previewImageUrl,\n isLoading = false,\n hasError = false,\n showMetadata = true,\n}: {\n file: NormalizedThumbnailFile\n className?: string\n previewAspectRatio?: number\n previewClassName?: string\n previewContent?: React.ReactNode\n previewImageUrl?: string | null\n isLoading?: boolean\n hasError?: boolean\n showMetadata?: boolean\n}) {\n const imageRef = React.useRef<HTMLImageElement | null>(null)\n const [isImageLoading, setIsImageLoading] = React.useState(\n Boolean(previewImageUrl)\n )\n const [imageFailed, setImageFailed] = React.useState(false)\n const showLoading = isLoading || isImageLoading\n const hasPreviewContent = Boolean(previewContent)\n const showFallback =\n hasError || imageFailed || (!previewImageUrl && !hasPreviewContent)\n const markImageLoaded = React.useCallback((image: HTMLImageElement) => {\n const didLoad = image.naturalWidth > 0 && image.naturalHeight > 0\n\n setImageFailed(!didLoad)\n setIsImageLoading(false)\n }, [])\n\n React.useEffect(() => {\n setIsImageLoading(Boolean(previewImageUrl))\n setImageFailed(false)\n }, [previewImageUrl])\n\n React.useEffect(() => {\n const image = imageRef.current\n\n if (!image || !previewImageUrl) return\n\n if (image.complete) {\n markImageLoaded(image)\n }\n }, [markImageLoaded, previewImageUrl])\n\n return (\n <div\n className={cn(\n "group overflow-hidden rounded-lg border bg-background text-foreground",\n className\n )}\n >\n <div\n className={cn(\n "relative aspect-square overflow-hidden bg-muted",\n previewClassName\n )}\n style={\n previewAspectRatio\n ? { aspectRatio: String(previewAspectRatio) }\n : undefined\n }\n >\n {previewImageUrl ? (\n <img\n ref={imageRef}\n src={previewImageUrl}\n alt=""\n draggable={false}\n loading="lazy"\n decoding="async"\n className={cn(\n "size-full object-cover transition-[opacity,filter,transform] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",\n showLoading\n ? "scale-[1.01] opacity-0 blur-sm"\n : "blur-0 scale-100 opacity-100"\n )}\n onLoad={(event) => {\n markImageLoaded(event.currentTarget)\n }}\n onError={() => {\n setImageFailed(true)\n setIsImageLoading(false)\n }}\n />\n ) : null}\n {previewContent ? (\n <div\n className={cn(\n "size-full transition-[opacity,filter,transform] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",\n showLoading\n ? "scale-[1.01] opacity-0 blur-sm"\n : "blur-0 scale-100 opacity-100"\n )}\n >\n {previewContent}\n </div>\n ) : null}\n {showLoading ? <FileThumbnailLoadingOverlay /> : null}\n {showFallback ? (\n <div className="absolute inset-0 grid place-items-center bg-muted text-muted-foreground">\n <FileKindIcon file={file} />\n </div>\n ) : null}\n </div>\n {showMetadata ? (\n <div className="flex items-center gap-2 border-t px-3 py-2">\n <div className="flex size-7 shrink-0 items-center justify-center rounded-md border bg-muted text-muted-foreground">\n <FileKindIcon file={file} />\n </div>\n <div className="min-w-0">\n <div className="truncate text-sm font-medium">{file.name}</div>\n <div className="truncate text-xs text-muted-foreground">\n {file.size ?? file.type}\n </div>\n </div>\n </div>\n ) : null}\n </div>\n )\n}\n\nfunction ImageFileThumbnail({\n className,\n file,\n hasError,\n isLoading,\n previewClassName,\n previewAspectRatio,\n showMetadata,\n source,\n}: {\n className?: string\n file: NormalizedThumbnailFile\n hasError?: boolean\n isLoading?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n showMetadata?: boolean\n source: ThumbnailSource\n}) {\n const imageUrl = useSourceObjectUrl(source)\n\n return (\n <FileThumbnailShell\n file={file}\n previewImageUrl={imageUrl}\n isLoading={isLoading || !imageUrl}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n )\n}\n\nfunction PdfFileThumbnail({\n file,\n className,\n hasError: externalHasError,\n isActive,\n isLoading: externalIsLoading,\n previewClassName,\n previewAspectRatio,\n showMetadata,\n source,\n thumbnailWidth,\n}: {\n file: NormalizedThumbnailFile\n className?: string\n hasError?: boolean\n isActive: boolean\n isLoading?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n showMetadata: boolean\n source: ThumbnailSource\n thumbnailWidth: number\n}) {\n const sourceUrl = useSourceObjectUrl(source)\n const [reactPdf, setReactPdf] = React.useState<ReactPdfModule | null>(null)\n const [isLoading, setIsLoading] = React.useState(true)\n const [hasError, setHasError] = React.useState(false)\n const rootRef = React.useRef<HTMLDivElement | null>(null)\n const { objectUrl, updateObjectUrl } = useObjectUrl()\n const shouldRenderPdf =\n isActive && sourceUrl && reactPdf && !objectUrl && !hasError\n const capturePdfCanvas = React.useCallback(() => {\n const canvas = rootRef.current?.querySelector("canvas") ?? null\n\n void canvasToBlob(canvas).then((blob) => {\n if (!blob) {\n setHasError(true)\n setIsLoading(false)\n return\n }\n\n updateObjectUrl(blob)\n setHasError(false)\n setIsLoading(false)\n })\n }, [updateObjectUrl])\n\n React.useEffect(() => {\n setIsLoading(true)\n setHasError(false)\n }, [sourceUrl])\n\n React.useEffect(() => {\n if (!isActive || reactPdf || objectUrl) return\n\n let isMounted = true\n setIsLoading(true)\n setHasError(false)\n\n void import("react-pdf")\n .then((module) => {\n module.pdfjs.GlobalWorkerOptions.workerSrc = `https://unpkg.com/pdfjs-dist@${module.pdfjs.version}/legacy/build/pdf.worker.min.mjs`\n if (isMounted) setReactPdf(module)\n })\n .catch(() => {\n if (isMounted) {\n setHasError(true)\n setIsLoading(false)\n }\n })\n\n return () => {\n isMounted = false\n }\n }, [isActive, objectUrl, reactPdf])\n\n return (\n <>\n <FileThumbnailShell\n file={file}\n previewImageUrl={objectUrl}\n isLoading={Boolean(externalIsLoading || (isLoading && !objectUrl))}\n hasError={Boolean(externalHasError || hasError)}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n {shouldRenderPdf ? (\n <div\n ref={rootRef}\n aria-hidden="true"\n className="pointer-events-none fixed top-0 left-[-10000px] w-[560px] overflow-hidden bg-white"\n >\n <reactPdf.Document\n file={sourceUrl}\n loading={null}\n error={null}\n noData={null}\n onLoadError={() => {\n setHasError(true)\n setIsLoading(false)\n }}\n >\n <reactPdf.Thumbnail\n pageNumber={1}\n width={thumbnailWidth}\n loading={null}\n error={null}\n onRenderSuccess={() => {\n window.requestAnimationFrame(() => {\n capturePdfCanvas()\n })\n }}\n onRenderError={() => {\n setHasError(true)\n setIsLoading(false)\n }}\n />\n </reactPdf.Document>\n </div>\n ) : null}\n </>\n )\n}\n\nfunction DocxFileThumbnail({\n file,\n className,\n hasError: externalHasError,\n isActive,\n isLoading: externalIsLoading,\n previewClassName,\n previewAspectRatio,\n showMetadata,\n source,\n thumbnailWidth,\n}: {\n file: NormalizedThumbnailFile\n className?: string\n hasError?: boolean\n isActive: boolean\n isLoading?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n showMetadata: boolean\n source: ThumbnailSource\n thumbnailWidth: number\n}) {\n const editor = useDocxEditor({\n initialDocumentTheme: "light",\n initialFileName: file.name,\n })\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: thumbnailWidth,\n maxWidth: thumbnailWidth,\n },\n }),\n [thumbnailWidth]\n )\n const { thumbnails } = useDocxViewerThumbnails(editor, thumbnailOptions)\n const firstThumbnail = thumbnails[0]\n const [hasError, setHasError] = React.useState(false)\n const [isReady, setIsReady] = React.useState(false)\n const [thumbnailSize, setThumbnailSize] = React.useState<{\n height: number\n width: number\n } | null>(null)\n const [thumbnailCanvas, setThumbnailCanvas] =\n React.useState<HTMLCanvasElement | null>(null)\n const editorRef = React.useRef(editor)\n const importedDocxKeyRef = React.useRef<string | null>(null)\n const hiddenDocxViewerRef = React.useRef<HTMLDivElement | null>(null)\n\n React.useEffect(() => {\n editorRef.current = editor\n }, [editor])\n\n React.useEffect(() => {\n if (!isActive) return\n\n const docxKey =\n typeof source === "string"\n ? `${file.name}:${source}`\n : `${file.name}:${source.size}:${source.type}`\n\n if (importedDocxKeyRef.current === docxKey) return\n\n let isCurrent = true\n importedDocxKeyRef.current = docxKey\n setHasError(false)\n setIsReady(false)\n\n async function loadDocx() {\n try {\n const docxFile = await sourceToFile(source, file)\n await editorRef.current.importDocxFile(docxFile)\n } catch {\n if (isCurrent && importedDocxKeyRef.current === docxKey) {\n setHasError(true)\n }\n }\n }\n\n void loadDocx()\n\n return () => {\n isCurrent = false\n }\n }, [file, isActive, source])\n\n React.useEffect(() => {\n if (!firstThumbnail) {\n setThumbnailSize(null)\n return\n }\n\n setThumbnailSize((currentSize) => {\n if (\n currentSize?.height === firstThumbnail.pixelHeightPx &&\n currentSize.width === firstThumbnail.pixelWidthPx\n ) {\n return currentSize\n }\n\n return {\n height: firstThumbnail.pixelHeightPx,\n width: firstThumbnail.pixelWidthPx,\n }\n })\n\n if (firstThumbnail?.status === "error") {\n setHasError(true)\n }\n }, [\n firstThumbnail,\n firstThumbnail?.pixelHeightPx,\n firstThumbnail?.pixelWidthPx,\n firstThumbnail?.status,\n ])\n\n const attachThumbnailCanvas = React.useCallback(\n (canvas: HTMLCanvasElement | null) => {\n setThumbnailCanvas(canvas)\n },\n []\n )\n\n React.useEffect(() => {\n if (\n !isActive ||\n !firstThumbnail ||\n !thumbnailCanvas ||\n isReady ||\n hasError\n ) {\n return\n }\n\n let isCurrent = true\n let timeoutId: number | undefined\n let animationFrameId: number | undefined\n let nestedAnimationFrameId: number | undefined\n let attempts = 0\n\n const getRenderedPageSurface = () => {\n const pageSurface = hiddenDocxViewerRef.current?.querySelector(\n \'[data-docx-page-surface="true"]\'\n )\n\n if (!pageSurface) return null\n\n const hasText = Boolean(pageSurface.textContent?.trim())\n const hasEmbeddedContent = Boolean(\n pageSurface.querySelector("canvas,img,svg,table")\n )\n\n return hasText || hasEmbeddedContent ? pageSurface : null\n }\n\n const renderThumbnail = () => {\n if (!isCurrent) return\n\n if (!getRenderedPageSurface()) {\n attempts += 1\n\n if (attempts > 50) {\n setHasError(true)\n return\n }\n\n timeoutId = window.setTimeout(renderThumbnail, 100)\n return\n }\n\n animationFrameId = window.requestAnimationFrame(() => {\n nestedAnimationFrameId = window.requestAnimationFrame(() => {\n void firstThumbnail\n .renderToCanvas(thumbnailCanvas)\n .then(() => {\n if (isCurrent) setIsReady(true)\n })\n .catch(() => {\n if (isCurrent) setHasError(true)\n })\n })\n })\n }\n\n renderThumbnail()\n\n return () => {\n isCurrent = false\n if (timeoutId !== undefined) window.clearTimeout(timeoutId)\n if (animationFrameId !== undefined) {\n window.cancelAnimationFrame(animationFrameId)\n }\n if (nestedAnimationFrameId !== undefined) {\n window.cancelAnimationFrame(nestedAnimationFrameId)\n }\n }\n }, [firstThumbnail, hasError, isActive, isReady, thumbnailCanvas])\n\n const previewContent = thumbnailSize ? (\n <canvas\n ref={attachThumbnailCanvas}\n width={thumbnailSize.width}\n height={thumbnailSize.height}\n className="!size-full bg-white object-cover object-top"\n />\n ) : null\n\n return (\n <>\n <FileThumbnailShell\n file={file}\n previewContent={previewContent}\n isLoading={Boolean(externalIsLoading || (!isReady && !hasError))}\n hasError={Boolean(externalHasError || hasError)}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={cn("bg-white", previewClassName)}\n showMetadata={showMetadata}\n />\n {isActive && !hasError && !isReady ? (\n <div\n ref={hiddenDocxViewerRef}\n aria-hidden="true"\n className="pointer-events-none fixed top-0 left-[-10000px] w-[816px] overflow-hidden bg-white"\n >\n <div className="w-[816px]">\n <DocxEditorViewer\n editor={editor}\n mode="read-only"\n pageBackgroundColor="#ffffff"\n pageGapBackgroundColor="transparent"\n visiblePageRange={{ endPageIndex: 0, startPageIndex: 0 }}\n pageVirtualization={{ enabled: false }}\n deferInitialPaginationPaint={false}\n />\n </div>\n </div>\n ) : null}\n </>\n )\n}\n\nfunction XlsxFileThumbnail({\n file,\n className,\n hasError: externalHasError,\n isActive,\n isLoading: externalIsLoading,\n previewClassName,\n previewAspectRatio,\n showMetadata,\n source,\n thumbnailWidth,\n}: {\n file: NormalizedThumbnailFile\n className?: string\n hasError?: boolean\n isActive: boolean\n isLoading?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n showMetadata: boolean\n source: ThumbnailSource\n thumbnailWidth: number\n}) {\n const sourceUrl = useSourceObjectUrl(source)\n const [imageUrl, setImageUrl] = React.useState<string | null>(null)\n const [hasError, setHasError] = React.useState(false)\n\n React.useEffect(() => {\n setImageUrl(null)\n setHasError(false)\n }, [sourceUrl])\n\n return (\n <>\n <FileThumbnailShell\n file={file}\n previewImageUrl={imageUrl}\n isLoading={Boolean(\n externalIsLoading || (isActive && !imageUrl && !hasError)\n )}\n hasError={Boolean(externalHasError || hasError)}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={cn(\n "bg-white [&>img]:object-left-top",\n previewClassName\n )}\n showMetadata={showMetadata}\n />\n {isActive && sourceUrl && !imageUrl && !hasError ? (\n <XlsxThumbnailGenerator\n file={file}\n sourceUrl={sourceUrl}\n thumbnailWidth={thumbnailWidth}\n onError={() => setHasError(true)}\n onImageUrl={setImageUrl}\n />\n ) : null}\n </>\n )\n}\n\nfunction XlsxThumbnailGenerator({\n file,\n onError,\n onImageUrl,\n sourceUrl,\n thumbnailWidth,\n}: {\n file: NormalizedThumbnailFile\n onError: () => void\n onImageUrl: (url: string) => void\n sourceUrl: string\n thumbnailWidth: number\n}) {\n const controller = useXlsxViewerController(\n React.useMemo(\n () => ({\n fileName: file.name,\n readOnly: true,\n src: sourceUrl,\n useWorker: true,\n }),\n [file.name, sourceUrl]\n )\n )\n\n return (\n <XlsxViewerProvider controller={controller}>\n <XlsxThumbnailGeneratorContent\n thumbnailWidth={thumbnailWidth}\n onError={onError}\n onImageUrl={onImageUrl}\n />\n </XlsxViewerProvider>\n )\n}\n\nfunction XlsxThumbnailGeneratorContent({\n onError,\n onImageUrl,\n thumbnailWidth,\n}: {\n onError: () => void\n onImageUrl: (url: string) => void\n thumbnailWidth: number\n}) {\n const controller = useXlsxViewer()\n const { thumbnails } = useXlsxViewerThumbnails({\n includeHeaders: true,\n resolution: {\n maxHeight: thumbnailWidth,\n maxWidth: thumbnailWidth,\n },\n })\n const firstThumbnail = thumbnails[0]\n\n React.useEffect(() => {\n if (controller.error) {\n onError()\n return\n }\n\n if (!firstThumbnail) return\n\n const canvas = document.createElement("canvas")\n\n if (!firstThumbnail.paint(canvas)) return\n\n onImageUrl(canvas.toDataURL("image/png"))\n }, [controller.error, firstThumbnail, onError, onImageUrl])\n\n return null\n}\n\nexport function FileThumbnail({\n file: rawFile,\n className,\n previewAspectRatio,\n previewClassName,\n previewContent,\n previewImageUrl,\n source: explicitSource,\n thumbnailWidth,\n generationDelayMs = 0,\n renderDocumentPreview = true,\n isLoading = false,\n hasError = false,\n showMetadata = true,\n}: FileThumbnailProps) {\n const file = React.useMemo(() => normalizeFile(rawFile), [rawFile])\n const source = getThumbnailSource(file, explicitSource)\n const isActive = useThumbnailActivation(generationDelayMs)\n\n if (previewImageUrl || previewContent || !renderDocumentPreview || !source) {\n return (\n <FileThumbnailShell\n file={file}\n previewImageUrl={previewImageUrl}\n previewContent={previewContent}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n )\n }\n\n if (isImageFile(file)) {\n return (\n <ImageFileThumbnail\n file={file}\n source={source}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n )\n }\n\n if (isPdfFile(file)) {\n return (\n <PdfFileThumbnail\n file={file}\n source={source}\n isActive={isActive}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n thumbnailWidth={thumbnailWidth ?? 520}\n />\n )\n }\n\n if (isDocxFile(file)) {\n return (\n <DocxFileThumbnail\n file={file}\n source={source}\n isActive={isActive}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n thumbnailWidth={thumbnailWidth ?? 520}\n />\n )\n }\n\n if (isXlsxFile(file)) {\n return (\n <XlsxFileThumbnail\n file={file}\n source={source}\n isActive={isActive}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n thumbnailWidth={thumbnailWidth ?? 680}\n />\n )\n }\n\n return (\n <FileThumbnailShell\n file={file}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n )\n}'+ "\"use client\"\n\nimport * as React from \"react\"\nimport {\n DocxEditorViewer,\n useDocxEditor,\n useDocxViewerThumbnails,\n} from \"@extend-ai/react-docx\"\nimport {\n useXlsxViewer,\n useXlsxViewerController,\n useXlsxViewerThumbnails,\n XlsxViewerProvider,\n} from \"@extend-ai/react-xlsx\"\nimport { File01Icon, FileImageIcon } from \"@hugeicons/core-free-icons\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport type * as ReactPdf from \"react-pdf\"\n\nimport { cn } from \"@/lib/utils\"\n\nexport type ThumbnailSource = string | File | Blob\n\nexport type ThumbnailFile = {\n name: string\n type: string\n size?: string | number\n source?: ThumbnailSource\n url?: string\n}\n\nexport type FileThumbnailProps = {\n file: ThumbnailFile | File\n className?: string\n previewAspectRatio?: number\n previewClassName?: string\n previewContent?: React.ReactNode\n previewImageUrl?: string | null\n source?: ThumbnailSource\n thumbnailWidth?: number\n generationDelayMs?: number\n renderDocumentPreview?: boolean\n isLoading?: boolean\n hasError?: boolean\n showMetadata?: boolean\n}\n\ntype NormalizedThumbnailFile = {\n name: string\n type: string\n size?: string | number\n source?: ThumbnailSource\n url?: string\n}\n\ntype ReactPdfModule = typeof ReactPdf\nconst PDF_WORKER_URL = new URL(\n \"pdfjs-dist/legacy/build/pdf.worker.min.mjs\",\n import.meta.url\n).toString()\n\nfunction isBlobLike(value: unknown): value is Blob {\n return typeof Blob !== \"undefined\" && value instanceof Blob\n}\n\nfunction isFileLike(value: unknown): value is File {\n return typeof File !== \"undefined\" && value instanceof File\n}\n\nfunction normalizeFile(file: ThumbnailFile | File): NormalizedThumbnailFile {\n return {\n name: file.name,\n size:\n typeof file.size === \"number\"\n ? formatBytes(file.size)\n : (file.size as string | undefined),\n source: isFileLike(file) ? file : (file as ThumbnailFile).source,\n type: file.type,\n url: (file as ThumbnailFile).url,\n }\n}\n\nfunction getThumbnailSource(\n file: NormalizedThumbnailFile,\n source?: ThumbnailSource\n): ThumbnailSource | undefined {\n return source ?? file.source ?? file.url\n}\n\nfunction formatBytes(bytes: number) {\n if (!Number.isFinite(bytes) || bytes <= 0) return undefined\n\n const units = [\"B\", \"KB\", \"MB\", \"GB\"]\n let value = bytes\n let unitIndex = 0\n\n while (value >= 1024 && unitIndex < units.length - 1) {\n value /= 1024\n unitIndex += 1\n }\n\n const formatted =\n value >= 10 || unitIndex === 0 ? Math.round(value) : value.toFixed(1)\n return `${formatted} ${units[unitIndex]}`\n}\n\nfunction isImageFile(file: NormalizedThumbnailFile) {\n return file.type.startsWith(\"image/\")\n}\n\nfunction isPdfFile(file: NormalizedThumbnailFile) {\n return (\n file.type === \"application/pdf\" || file.name.toLowerCase().endsWith(\".pdf\")\n )\n}\n\nfunction isDocxFile(file: NormalizedThumbnailFile) {\n return (\n file.type ===\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\" ||\n file.name.toLowerCase().endsWith(\".docx\")\n )\n}\n\nfunction isXlsxFile(file: NormalizedThumbnailFile) {\n const fileName = file.name.toLowerCase()\n\n return (\n file.type ===\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\" ||\n file.type === \"application/vnd.ms-excel\" ||\n fileName.endsWith(\".xlsx\") ||\n fileName.endsWith(\".xls\")\n )\n}\n\nfunction FileKindIcon({ file }: { file: NormalizedThumbnailFile }) {\n const icon = isImageFile(file) ? FileImageIcon : File01Icon\n\n return <HugeiconsIcon icon={icon} className=\"size-4\" />\n}\n\nfunction useThumbnailActivation(delayMs: number) {\n const [isActive, setIsActive] = React.useState(delayMs <= 0)\n\n React.useEffect(() => {\n if (delayMs <= 0) {\n setIsActive(true)\n return\n }\n\n setIsActive(false)\n const timeout = window.setTimeout(() => {\n setIsActive(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeout)\n }, [delayMs])\n\n return isActive\n}\n\nfunction useObjectUrl() {\n const [objectUrl, setObjectUrl] = React.useState<string | null>(null)\n\n const updateObjectUrl = React.useCallback((blob: Blob) => {\n const nextUrl = URL.createObjectURL(blob)\n setObjectUrl((currentUrl) => {\n if (currentUrl) URL.revokeObjectURL(currentUrl)\n return nextUrl\n })\n }, [])\n\n React.useEffect(() => {\n return () => {\n if (objectUrl) URL.revokeObjectURL(objectUrl)\n }\n }, [objectUrl])\n\n return { objectUrl, updateObjectUrl }\n}\n\nfunction useSourceObjectUrl(source: ThumbnailSource | undefined) {\n const [objectUrl, setObjectUrl] = React.useState<string | null>(null)\n\n React.useEffect(() => {\n if (!source || typeof source === \"string\") {\n setObjectUrl(null)\n return\n }\n\n const nextUrl = URL.createObjectURL(source)\n setObjectUrl(nextUrl)\n\n return () => URL.revokeObjectURL(nextUrl)\n }, [source])\n\n if (!source) return undefined\n return typeof source === \"string\" ? source : (objectUrl ?? undefined)\n}\n\nasync function sourceToFile(\n source: ThumbnailSource,\n file: NormalizedThumbnailFile\n) {\n if (isFileLike(source)) return source\n\n if (isBlobLike(source)) {\n return new File([source], file.name, {\n type: source.type || file.type,\n })\n }\n\n const response = await fetch(source)\n if (!response.ok) {\n throw new Error(`Failed to fetch ${file.name} (${response.status})`)\n }\n\n const blob = await response.blob()\n\n return new File([blob], file.name, {\n type: blob.type || file.type,\n })\n}\n\nfunction canvasToBlob(canvas: HTMLCanvasElement | null) {\n if (!canvas) return Promise.resolve<Blob | null>(null)\n\n return new Promise<Blob | null>((resolve) => {\n const blobFromDataUrl = async () => {\n try {\n const dataUrl = canvas.toDataURL(\"image/png\")\n const response = await fetch(dataUrl)\n return await response.blob()\n } catch {\n return null\n }\n }\n\n try {\n if (typeof canvas.toBlob === \"function\") {\n canvas.toBlob((blob) => {\n if (blob) {\n resolve(blob)\n return\n }\n\n void blobFromDataUrl().then(resolve)\n }, \"image/png\")\n return\n }\n\n void blobFromDataUrl().then(resolve)\n } catch {\n resolve(null)\n }\n })\n}\n\nexport function FileThumbnailLoadingOverlay() {\n return (\n <div\n aria-hidden=\"true\"\n className=\"absolute inset-0 z-10 overflow-hidden bg-muted\"\n >\n <div className=\"absolute inset-0 bg-muted\" />\n <div className=\"absolute inset-0 animate-pulse bg-background/55 motion-reduce:animate-none\" />\n </div>\n )\n}\n\nfunction FileThumbnailShell({\n file,\n className,\n previewAspectRatio,\n previewClassName,\n previewContent,\n previewImageUrl,\n isLoading = false,\n hasError = false,\n showMetadata = true,\n}: {\n file: NormalizedThumbnailFile\n className?: string\n previewAspectRatio?: number\n previewClassName?: string\n previewContent?: React.ReactNode\n previewImageUrl?: string | null\n isLoading?: boolean\n hasError?: boolean\n showMetadata?: boolean\n}) {\n const imageRef = React.useRef<HTMLImageElement | null>(null)\n const [isImageLoading, setIsImageLoading] = React.useState(\n Boolean(previewImageUrl)\n )\n const [imageFailed, setImageFailed] = React.useState(false)\n const showLoading = isLoading || isImageLoading\n const hasPreviewContent = Boolean(previewContent)\n const showFallback =\n hasError || imageFailed || (!previewImageUrl && !hasPreviewContent)\n const markImageLoaded = React.useCallback((image: HTMLImageElement) => {\n const didLoad = image.naturalWidth > 0 && image.naturalHeight > 0\n\n setImageFailed(!didLoad)\n setIsImageLoading(false)\n }, [])\n\n React.useEffect(() => {\n setIsImageLoading(Boolean(previewImageUrl))\n setImageFailed(false)\n }, [previewImageUrl])\n\n React.useEffect(() => {\n const image = imageRef.current\n\n if (!image || !previewImageUrl) return\n\n if (image.complete) {\n markImageLoaded(image)\n }\n }, [markImageLoaded, previewImageUrl])\n\n return (\n <div\n className={cn(\n \"group overflow-hidden rounded-lg border bg-background text-foreground\",\n className\n )}\n >\n <div\n className={cn(\n \"relative aspect-square overflow-hidden bg-muted\",\n previewClassName\n )}\n style={\n previewAspectRatio\n ? { aspectRatio: String(previewAspectRatio) }\n : undefined\n }\n >\n {previewImageUrl ? (\n <img\n ref={imageRef}\n src={previewImageUrl}\n alt=\"\"\n draggable={false}\n loading=\"lazy\"\n decoding=\"async\"\n className={cn(\n \"size-full object-cover transition-[opacity,filter,transform] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none\",\n showLoading\n ? \"scale-[1.01] opacity-0 blur-sm\"\n : \"blur-0 scale-100 opacity-100\"\n )}\n onLoad={(event) => {\n markImageLoaded(event.currentTarget)\n }}\n onError={() => {\n setImageFailed(true)\n setIsImageLoading(false)\n }}\n />\n ) : null}\n {previewContent ? (\n <div\n className={cn(\n \"size-full transition-[opacity,filter,transform] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none\",\n showLoading\n ? \"scale-[1.01] opacity-0 blur-sm\"\n : \"blur-0 scale-100 opacity-100\"\n )}\n >\n {previewContent}\n </div>\n ) : null}\n {showLoading ? <FileThumbnailLoadingOverlay /> : null}\n {showFallback ? (\n <div className=\"absolute inset-0 grid place-items-center bg-muted text-muted-foreground\">\n <FileKindIcon file={file} />\n </div>\n ) : null}\n </div>\n {showMetadata ? (\n <div className=\"flex items-center gap-2 border-t px-3 py-2\">\n <div className=\"flex size-7 shrink-0 items-center justify-center rounded-md border bg-muted text-muted-foreground\">\n <FileKindIcon file={file} />\n </div>\n <div className=\"min-w-0\">\n <div className=\"truncate text-sm font-medium\">{file.name}</div>\n <div className=\"truncate text-xs text-muted-foreground\">\n {file.size ?? file.type}\n </div>\n </div>\n </div>\n ) : null}\n </div>\n )\n}\n\nfunction ImageFileThumbnail({\n className,\n file,\n hasError,\n isLoading,\n previewClassName,\n previewAspectRatio,\n showMetadata,\n source,\n}: {\n className?: string\n file: NormalizedThumbnailFile\n hasError?: boolean\n isLoading?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n showMetadata?: boolean\n source: ThumbnailSource\n}) {\n const imageUrl = useSourceObjectUrl(source)\n\n return (\n <FileThumbnailShell\n file={file}\n previewImageUrl={imageUrl}\n isLoading={isLoading || !imageUrl}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n )\n}\n\nfunction PdfFileThumbnail({\n file,\n className,\n hasError: externalHasError,\n isActive,\n isLoading: externalIsLoading,\n previewClassName,\n previewAspectRatio,\n showMetadata,\n source,\n thumbnailWidth,\n}: {\n file: NormalizedThumbnailFile\n className?: string\n hasError?: boolean\n isActive: boolean\n isLoading?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n showMetadata: boolean\n source: ThumbnailSource\n thumbnailWidth: number\n}) {\n const sourceUrl = useSourceObjectUrl(source)\n const [reactPdf, setReactPdf] = React.useState<ReactPdfModule | null>(null)\n const [isLoading, setIsLoading] = React.useState(true)\n const [hasError, setHasError] = React.useState(false)\n const rootRef = React.useRef<HTMLDivElement | null>(null)\n const { objectUrl, updateObjectUrl } = useObjectUrl()\n const shouldRenderPdf =\n isActive && sourceUrl && reactPdf && !objectUrl && !hasError\n const capturePdfCanvas = React.useCallback(() => {\n const canvas = rootRef.current?.querySelector(\"canvas\") ?? null\n\n void canvasToBlob(canvas).then((blob) => {\n if (!blob) {\n setHasError(true)\n setIsLoading(false)\n return\n }\n\n updateObjectUrl(blob)\n setHasError(false)\n setIsLoading(false)\n })\n }, [updateObjectUrl])\n\n React.useEffect(() => {\n setIsLoading(true)\n setHasError(false)\n }, [sourceUrl])\n\n React.useEffect(() => {\n if (!isActive || reactPdf || objectUrl) return\n\n let isMounted = true\n setIsLoading(true)\n setHasError(false)\n\n void import(\"react-pdf\")\n .then((module) => {\n module.pdfjs.GlobalWorkerOptions.workerSrc = PDF_WORKER_URL\n if (isMounted) setReactPdf(module)\n })\n .catch(() => {\n if (isMounted) {\n setHasError(true)\n setIsLoading(false)\n }\n })\n\n return () => {\n isMounted = false\n }\n }, [isActive, objectUrl, reactPdf])\n\n return (\n <>\n <FileThumbnailShell\n file={file}\n previewImageUrl={objectUrl}\n isLoading={Boolean(externalIsLoading || (isLoading && !objectUrl))}\n hasError={Boolean(externalHasError || hasError)}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n {shouldRenderPdf ? (\n <div\n ref={rootRef}\n aria-hidden=\"true\"\n className=\"pointer-events-none fixed top-0 left-[-10000px] w-[560px] overflow-hidden bg-white\"\n >\n <reactPdf.Document\n file={sourceUrl}\n loading={null}\n error={null}\n noData={null}\n onLoadError={() => {\n setHasError(true)\n setIsLoading(false)\n }}\n >\n <reactPdf.Thumbnail\n pageNumber={1}\n width={thumbnailWidth}\n loading={null}\n error={null}\n onRenderSuccess={() => {\n window.requestAnimationFrame(() => {\n capturePdfCanvas()\n })\n }}\n onRenderError={() => {\n setHasError(true)\n setIsLoading(false)\n }}\n />\n </reactPdf.Document>\n </div>\n ) : null}\n </>\n )\n}\n\nfunction DocxFileThumbnail({\n file,\n className,\n hasError: externalHasError,\n isActive,\n isLoading: externalIsLoading,\n previewClassName,\n previewAspectRatio,\n showMetadata,\n source,\n thumbnailWidth,\n}: {\n file: NormalizedThumbnailFile\n className?: string\n hasError?: boolean\n isActive: boolean\n isLoading?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n showMetadata: boolean\n source: ThumbnailSource\n thumbnailWidth: number\n}) {\n const editor = useDocxEditor({\n initialDocumentTheme: \"light\",\n initialFileName: file.name,\n })\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: thumbnailWidth,\n maxWidth: thumbnailWidth,\n },\n }),\n [thumbnailWidth]\n )\n const { thumbnails } = useDocxViewerThumbnails(editor, thumbnailOptions)\n const firstThumbnail = thumbnails[0]\n const [hasError, setHasError] = React.useState(false)\n const [isReady, setIsReady] = React.useState(false)\n const [thumbnailSize, setThumbnailSize] = React.useState<{\n height: number\n width: number\n } | null>(null)\n const [thumbnailCanvas, setThumbnailCanvas] =\n React.useState<HTMLCanvasElement | null>(null)\n const editorRef = React.useRef(editor)\n const importedDocxKeyRef = React.useRef<string | null>(null)\n const hiddenDocxViewerRef = React.useRef<HTMLDivElement | null>(null)\n\n React.useEffect(() => {\n editorRef.current = editor\n }, [editor])\n\n React.useEffect(() => {\n if (!isActive) return\n\n const docxKey =\n typeof source === \"string\"\n ? `${file.name}:${source}`\n : `${file.name}:${source.size}:${source.type}`\n\n if (importedDocxKeyRef.current === docxKey) return\n\n let isCurrent = true\n importedDocxKeyRef.current = docxKey\n setHasError(false)\n setIsReady(false)\n\n async function loadDocx() {\n try {\n const docxFile = await sourceToFile(source, file)\n await editorRef.current.importDocxFile(docxFile)\n } catch {\n if (isCurrent && importedDocxKeyRef.current === docxKey) {\n setHasError(true)\n }\n }\n }\n\n void loadDocx()\n\n return () => {\n isCurrent = false\n }\n }, [file, isActive, source])\n\n React.useEffect(() => {\n if (!firstThumbnail) {\n setThumbnailSize(null)\n return\n }\n\n setThumbnailSize((currentSize) => {\n if (\n currentSize?.height === firstThumbnail.pixelHeightPx &&\n currentSize.width === firstThumbnail.pixelWidthPx\n ) {\n return currentSize\n }\n\n return {\n height: firstThumbnail.pixelHeightPx,\n width: firstThumbnail.pixelWidthPx,\n }\n })\n\n if (firstThumbnail?.status === \"error\") {\n setHasError(true)\n }\n }, [\n firstThumbnail,\n firstThumbnail?.pixelHeightPx,\n firstThumbnail?.pixelWidthPx,\n firstThumbnail?.status,\n ])\n\n const attachThumbnailCanvas = React.useCallback(\n (canvas: HTMLCanvasElement | null) => {\n setThumbnailCanvas(canvas)\n },\n []\n )\n\n React.useEffect(() => {\n if (\n !isActive ||\n !firstThumbnail ||\n !thumbnailCanvas ||\n isReady ||\n hasError\n ) {\n return\n }\n\n let isCurrent = true\n let timeoutId: number | undefined\n let animationFrameId: number | undefined\n let nestedAnimationFrameId: number | undefined\n let attempts = 0\n\n const getRenderedPageSurface = () => {\n const pageSurface = hiddenDocxViewerRef.current?.querySelector(\n '[data-docx-page-surface=\"true\"]'\n )\n\n if (!pageSurface) return null\n\n const hasText = Boolean(pageSurface.textContent?.trim())\n const hasEmbeddedContent = Boolean(\n pageSurface.querySelector(\"canvas,img,svg,table\")\n )\n\n return hasText || hasEmbeddedContent ? pageSurface : null\n }\n\n const renderThumbnail = () => {\n if (!isCurrent) return\n\n if (!getRenderedPageSurface()) {\n attempts += 1\n\n if (attempts > 50) {\n setHasError(true)\n return\n }\n\n timeoutId = window.setTimeout(renderThumbnail, 100)\n return\n }\n\n animationFrameId = window.requestAnimationFrame(() => {\n nestedAnimationFrameId = window.requestAnimationFrame(() => {\n void firstThumbnail\n .renderToCanvas(thumbnailCanvas)\n .then(() => {\n if (isCurrent) setIsReady(true)\n })\n .catch(() => {\n if (isCurrent) setHasError(true)\n })\n })\n })\n }\n\n renderThumbnail()\n\n return () => {\n isCurrent = false\n if (timeoutId !== undefined) window.clearTimeout(timeoutId)\n if (animationFrameId !== undefined) {\n window.cancelAnimationFrame(animationFrameId)\n }\n if (nestedAnimationFrameId !== undefined) {\n window.cancelAnimationFrame(nestedAnimationFrameId)\n }\n }\n }, [firstThumbnail, hasError, isActive, isReady, thumbnailCanvas])\n\n const previewContent = thumbnailSize ? (\n <canvas\n ref={attachThumbnailCanvas}\n width={thumbnailSize.width}\n height={thumbnailSize.height}\n className=\"!size-full bg-white object-cover object-top\"\n />\n ) : null\n\n return (\n <>\n <FileThumbnailShell\n file={file}\n previewContent={previewContent}\n isLoading={Boolean(externalIsLoading || (!isReady && !hasError))}\n hasError={Boolean(externalHasError || hasError)}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={cn(\"bg-white\", previewClassName)}\n showMetadata={showMetadata}\n />\n {isActive && !hasError && !isReady ? (\n <div\n ref={hiddenDocxViewerRef}\n aria-hidden=\"true\"\n className=\"pointer-events-none fixed top-0 left-[-10000px] w-[816px] overflow-hidden bg-white\"\n >\n <div className=\"w-[816px]\">\n <DocxEditorViewer\n editor={editor}\n mode=\"read-only\"\n pageBackgroundColor=\"#ffffff\"\n pageGapBackgroundColor=\"transparent\"\n visiblePageRange={{ endPageIndex: 0, startPageIndex: 0 }}\n pageVirtualization={{ enabled: false }}\n deferInitialPaginationPaint={false}\n />\n </div>\n </div>\n ) : null}\n </>\n )\n}\n\nfunction XlsxFileThumbnail({\n file,\n className,\n hasError: externalHasError,\n isActive,\n isLoading: externalIsLoading,\n previewClassName,\n previewAspectRatio,\n showMetadata,\n source,\n thumbnailWidth,\n}: {\n file: NormalizedThumbnailFile\n className?: string\n hasError?: boolean\n isActive: boolean\n isLoading?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n showMetadata: boolean\n source: ThumbnailSource\n thumbnailWidth: number\n}) {\n const sourceUrl = useSourceObjectUrl(source)\n const [imageUrl, setImageUrl] = React.useState<string | null>(null)\n const [hasError, setHasError] = React.useState(false)\n\n React.useEffect(() => {\n setImageUrl(null)\n setHasError(false)\n }, [sourceUrl])\n\n return (\n <>\n <FileThumbnailShell\n file={file}\n previewImageUrl={imageUrl}\n isLoading={Boolean(\n externalIsLoading || (isActive && !imageUrl && !hasError)\n )}\n hasError={Boolean(externalHasError || hasError)}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={cn(\n \"bg-white [&>img]:object-left-top\",\n previewClassName\n )}\n showMetadata={showMetadata}\n />\n {isActive && sourceUrl && !imageUrl && !hasError ? (\n <XlsxThumbnailGenerator\n file={file}\n sourceUrl={sourceUrl}\n thumbnailWidth={thumbnailWidth}\n onError={() => setHasError(true)}\n onImageUrl={setImageUrl}\n />\n ) : null}\n </>\n )\n}\n\nfunction XlsxThumbnailGenerator({\n file,\n onError,\n onImageUrl,\n sourceUrl,\n thumbnailWidth,\n}: {\n file: NormalizedThumbnailFile\n onError: () => void\n onImageUrl: (url: string) => void\n sourceUrl: string\n thumbnailWidth: number\n}) {\n const controller = useXlsxViewerController(\n React.useMemo(\n () => ({\n fileName: file.name,\n readOnly: true,\n src: sourceUrl,\n useWorker: true,\n }),\n [file.name, sourceUrl]\n )\n )\n\n return (\n <XlsxViewerProvider controller={controller}>\n <XlsxThumbnailGeneratorContent\n thumbnailWidth={thumbnailWidth}\n onError={onError}\n onImageUrl={onImageUrl}\n />\n </XlsxViewerProvider>\n )\n}\n\nfunction XlsxThumbnailGeneratorContent({\n onError,\n onImageUrl,\n thumbnailWidth,\n}: {\n onError: () => void\n onImageUrl: (url: string) => void\n thumbnailWidth: number\n}) {\n const controller = useXlsxViewer()\n const { thumbnails } = useXlsxViewerThumbnails({\n includeHeaders: true,\n resolution: {\n maxHeight: thumbnailWidth,\n maxWidth: thumbnailWidth,\n },\n })\n const firstThumbnail = thumbnails[0]\n\n React.useEffect(() => {\n if (controller.error) {\n onError()\n return\n }\n\n if (!firstThumbnail) return\n\n const canvas = document.createElement(\"canvas\")\n\n if (!firstThumbnail.paint(canvas)) return\n\n onImageUrl(canvas.toDataURL(\"image/png\"))\n }, [controller.error, firstThumbnail, onError, onImageUrl])\n\n return null\n}\n\nexport function FileThumbnail({\n file: rawFile,\n className,\n previewAspectRatio,\n previewClassName,\n previewContent,\n previewImageUrl,\n source: explicitSource,\n thumbnailWidth,\n generationDelayMs = 0,\n renderDocumentPreview = true,\n isLoading = false,\n hasError = false,\n showMetadata = true,\n}: FileThumbnailProps) {\n const file = React.useMemo(() => normalizeFile(rawFile), [rawFile])\n const source = getThumbnailSource(file, explicitSource)\n const isActive = useThumbnailActivation(generationDelayMs)\n\n if (previewImageUrl || previewContent || !renderDocumentPreview || !source) {\n return (\n <FileThumbnailShell\n file={file}\n previewImageUrl={previewImageUrl}\n previewContent={previewContent}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n )\n }\n\n if (isImageFile(file)) {\n return (\n <ImageFileThumbnail\n file={file}\n source={source}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n )\n }\n\n if (isPdfFile(file)) {\n return (\n <PdfFileThumbnail\n file={file}\n source={source}\n isActive={isActive}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n thumbnailWidth={thumbnailWidth ?? 520}\n />\n )\n }\n\n if (isDocxFile(file)) {\n return (\n <DocxFileThumbnail\n file={file}\n source={source}\n isActive={isActive}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n thumbnailWidth={thumbnailWidth ?? 520}\n />\n )\n }\n\n if (isXlsxFile(file)) {\n return (\n <XlsxFileThumbnail\n file={file}\n source={source}\n isActive={isActive}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n thumbnailWidth={thumbnailWidth ?? 680}\n />\n )\n }\n\n return (\n <FileThumbnailShell\n file={file}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n )\n}"export function FileThumbnailSource() {return <HighlightedCodeBlock code={fileThumbnailSourceCode} />diff --git a/apps/v4/components/file-upload-docs.tsx b/apps/v4/components/file-upload-docs.tsxindex c5f5fa0..0d25d3f 100644--- a/apps/v4/components/file-upload-docs.tsx+++ b/apps/v4/components/file-upload-docs.tsx@@ -378,234 +378,7 @@ export function FileUploadExample() {);}`-const fileUploadUsageCode = `"use client";--import * as React from "react";-import { BorderBeam } from "border-beam";-import {- FileImageIcon,- FileSpreadsheetIcon,- FileUploadIcon,- Upload01Icon,-} from "@hugeicons/core-free-icons";-import { HugeiconsIcon } from "@hugeicons/react";--import { cn } from "@/lib/utils";-import { Card } from "@/components/ui/card";-import { FileThumbnail } from "@/components/ui/file-thumbnail";--type FileUploadItem = {- id: string;- name: string;- type: string;- size: number;- url: string;-};--type FileUploadProps = {- borderBeamTheme?: React.ComponentProps<typeof BorderBeam>["theme"];- className?: string;- onFilesChange?: (files: FileUploadItem[]) => void;-};--const ACCEPTED_FILE_TYPES = [- { label: "Image", icon: FileImageIcon },- { label: "PDF", icon: FileUploadIcon },- { label: "Sheet", icon: FileSpreadsheetIcon },-];-const ICON_TRANSFORMS = [- {- idle: "translate(-78%, -50%) rotate(-8deg)",- active: "translate(-114%, -50%) rotate(-12deg) scale(1.08)",- },- {- idle: "translate(-50%, -50%) rotate(0deg)",- active: "translate(-50%, -50%) rotate(0deg) scale(1.18)",- },- {- idle: "translate(-22%, -50%) rotate(8deg)",- active: "translate(14%, -50%) rotate(12deg) scale(1.08)",- },-];--function formatBytes(bytes: number) {- if (bytes === 0) return "0 B";-- const units = ["B", "KB", "MB", "GB"];- const index = Math.min(- Math.floor(Math.log(bytes) / Math.log(1024)),- units.length - 1,- );-- return \`\${(bytes / 1024 ** index).toFixed(index === 0 ? 0 : 1)} \${units[index]}\`;-}--function toUploadItems(files: FileList | File[]): FileUploadItem[] {- return Array.from(files).map((file) => ({- id: \`\${file.name}-\${file.size}-\${file.lastModified}\`,- name: file.name,- type: file.type || "Unknown type",- size: file.size,- url: URL.createObjectURL(file),- }));-}--function UploadIconCluster({ isDragging }: { isDragging: boolean }) {- return (- <div className="relative h-14 w-36">- {ACCEPTED_FILE_TYPES.map((item, index) => (- <Card- key={item.label}- className={cn(- "absolute top-1/2 left-1/2 grid size-12 place-items-center rounded-xl bg-background text-muted-foreground transition-[transform,color,background-color] duration-500 ease-[cubic-bezier(0.22,1,0.36,1)] before:rounded-[calc(var(--radius-xl)-1px)]",- "motion-reduce:transition-none",- index === 1 && "z-10",- isDragging && "bg-accent text-foreground",- )}- style={{- transform: isDragging- ? ICON_TRANSFORMS[index]?.active- : ICON_TRANSFORMS[index]?.idle,- }}- >- <HugeiconsIcon icon={item.icon} className="size-5" />- </Card>- ))}- </div>- );-}--export function FileUpload({- borderBeamTheme = "light",- className,- onFilesChange,-}: FileUploadProps) {- const dragDepthRef = React.useRef(0);- const [isDragging, setIsDragging] = React.useState(false);- const [files, setFiles] = React.useState<FileUploadItem[]>([]);-- const commitFiles = React.useCallback(- (nextFiles: FileList | File[]) => {- const items = toUploadItems(nextFiles);- setFiles((previousFiles) => {- previousFiles.forEach((file) => URL.revokeObjectURL(file.url));- return items;- });- onFilesChange?.(items);- },- [onFilesChange],- );-- React.useEffect(() => {- return () => {- files.forEach((file) => URL.revokeObjectURL(file.url));- };- }, [files]);-- return (- <div className={cn("space-y-3", className)}>- <BorderBeam- active={isDragging}- borderRadius={18}- brightness={2.4}- className="rounded-[1.125rem]"- colorVariant="ocean"- duration={2.4}- size="md"- strength={1}- theme={borderBeamTheme}- >- <label- className={cn(- "relative flex min-h-64 cursor-pointer flex-col items-center justify-center gap-5 overflow-hidden rounded-[1.125rem] border border-dashed bg-background px-6 py-10 text-center transition-[border-color,background-color] duration-200 ease-out",- "motion-reduce:transition-none",- isDragging- ? "border-foreground/40 bg-accent/35"- : "border-border hover:border-foreground/30 hover:bg-muted/35",- )}- onDragEnter={(event) => {- event.preventDefault();- dragDepthRef.current += 1;- setIsDragging(true);- }}- onDragLeave={(event) => {- event.preventDefault();- dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);- if (dragDepthRef.current === 0) {- setIsDragging(false);- }- }}- onDragOver={(event) => {- event.preventDefault();- }}- onDrop={(event) => {- event.preventDefault();- dragDepthRef.current = 0;- setIsDragging(false);-- if (event.dataTransfer.files.length > 0) {- commitFiles(event.dataTransfer.files);- }- }}- >- <input- type="file"- multiple- className="sr-only"- onChange={(event) => {- if (event.target.files) {- commitFiles(event.target.files);- }- }}- />- <UploadIconCluster isDragging={isDragging} />- <div className="space-y-1">- <div className="text-sm font-medium">- Click to upload or drop files- </div>- <div className="text-xs text-muted-foreground">- PDF, DOCX, XLSX, CSV, PNG, or JPG- </div>- </div>- <div className="inline-flex items-center gap-2 rounded-full border bg-background px-3 py-1 text-xs text-muted-foreground">- <HugeiconsIcon icon={Upload01Icon} className="size-3.5" />- <span>{isDragging ? "Drop to add" : "Browse files"}</span>- </div>- </label>- </BorderBeam>- {files.length > 0 ? (- <div className="rounded-xl border bg-background">- {files.map((file) => (- <div- key={file.id}- className="flex items-center gap-3 border-b px-3 py-2.5 last:border-b-0"- >- <FileThumbnail- file={{- name: file.name,- type: file.type,- size: formatBytes(file.size),- }}- previewImageUrl={file.type.startsWith("image/") ? file.url : null}- className="size-10 shrink-0 rounded-lg"- showMetadata={false}- />- <div className="min-w-0 flex-1">- <div className="truncate text-sm font-medium">{file.name}</div>- <div className="truncate text-xs text-muted-foreground">- {file.type} - {formatBytes(file.size)}- </div>- </div>- <div className="rounded-full bg-muted px-2 py-1 text-xs text-muted-foreground">- Ready- </div>- </div>- ))}- </div>- ) : null}- </div>- );-}`+const fileUploadUsageCode = "\"use client\"\n\nimport * as React from \"react\"\nimport {\n FileImageIcon,\n FileSpreadsheetIcon,\n FileUploadIcon,\n Upload01Icon,\n} from \"@hugeicons/core-free-icons\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { BorderBeam } from \"border-beam\"\n\nimport { cn } from \"@/lib/utils\"\nimport { FileThumbnail } from \"@/components/ui/file-thumbnail\"\nimport { Card } from \"@/registry/new-york-v4/ui/card\"\n\ntype FileUploadItem = {\n id: string\n name: string\n type: string\n size: number\n url: string\n}\n\ntype AcceptedFileType = {\n label: string\n icon: React.ComponentProps<typeof HugeiconsIcon>[\"icon\"]\n}\n\ntype FileUploadProps = {\n accept?: string\n acceptedFileTypes?: AcceptedFileType[]\n borderBeamTheme?: React.ComponentProps<typeof BorderBeam>[\"theme\"]\n browseLabel?: string\n className?: string\n description?: string\n draggingLabel?: string\n multiple?: boolean\n showBorderBeam?: boolean\n showFileList?: boolean\n title?: string\n onFilesAccepted?: (files: File[]) => void\n onFilesChange?: (files: FileUploadItem[]) => void\n}\n\nconst ACCEPTED_FILE_TYPES: AcceptedFileType[] = [\n { label: \"Image\", icon: FileImageIcon },\n { label: \"PDF\", icon: FileUploadIcon },\n { label: \"Sheet\", icon: FileSpreadsheetIcon },\n]\nconst ICON_TRANSFORMS = [\n {\n idle: \"translate(-78%, -50%) rotate(-8deg)\",\n active: \"translate(-114%, -50%) rotate(-12deg) scale(1.08)\",\n },\n {\n idle: \"translate(-50%, -50%) rotate(0deg)\",\n active: \"translate(-50%, -50%) rotate(0deg) scale(1.18)\",\n },\n {\n idle: \"translate(-22%, -50%) rotate(8deg)\",\n active: \"translate(14%, -50%) rotate(12deg) scale(1.08)\",\n },\n]\n\nfunction formatBytes(bytes: number) {\n if (bytes === 0) return \"0 B\"\n\n const units = [\"B\", \"KB\", \"MB\", \"GB\"]\n const index = Math.min(\n Math.floor(Math.log(bytes) / Math.log(1024)),\n units.length - 1\n )\n\n return `${(bytes / 1024 ** index).toFixed(index === 0 ? 0 : 1)} ${\n units[index]\n }`\n}\n\nfunction matchesAccept(file: File, accept?: string) {\n if (!accept) return true\n\n return accept.split(\",\").some((rawToken) => {\n const token = rawToken.trim().toLowerCase()\n\n if (!token) return false\n if (token.startsWith(\".\")) return file.name.toLowerCase().endsWith(token)\n if (token.endsWith(\"/*\")) {\n return file.type.toLowerCase().startsWith(token.slice(0, -1))\n }\n\n return file.type.toLowerCase() === token\n })\n}\n\nfunction toUploadItems(files: FileList | File[]): FileUploadItem[] {\n return Array.from(files).map((file) => ({\n id: `${file.name}-${file.size}-${file.lastModified}`,\n name: file.name,\n type: file.type || \"Unknown type\",\n size: file.size,\n url: URL.createObjectURL(file),\n }))\n}\n\nfunction UploadIconCluster({\n acceptedFileTypes,\n isDragging,\n}: {\n acceptedFileTypes: AcceptedFileType[]\n isDragging: boolean\n}) {\n const singleIcon = acceptedFileTypes.length === 1\n\n return (\n <div className=\"relative h-14 w-36\">\n {acceptedFileTypes.map((item, index) => (\n <Card\n key={item.label}\n className={cn(\n \"absolute top-1/2 left-1/2 grid size-12 place-items-center rounded-xl bg-background text-muted-foreground transition-[transform,color,background-color] duration-500 ease-[cubic-bezier(0.22,1,0.36,1)] before:rounded-[calc(var(--radius-xl)-1px)]\",\n \"motion-reduce:transition-none\",\n index === 1 && \"z-10\",\n isDragging && \"bg-accent text-foreground\"\n )}\n style={{\n transform: singleIcon\n ? `translate(-50%, -50%) scale(${isDragging ? 1.14 : 1})`\n : isDragging\n ? ICON_TRANSFORMS[index]?.active\n : ICON_TRANSFORMS[index]?.idle,\n }}\n >\n <HugeiconsIcon icon={item.icon} className=\"size-5\" />\n </Card>\n ))}\n </div>\n )\n}\n\nexport function FileUpload({\n accept,\n acceptedFileTypes = ACCEPTED_FILE_TYPES,\n borderBeamTheme = \"light\",\n browseLabel = \"Browse files\",\n className,\n description = \"PDF, DOCX, XLSX, CSV, PNG, or JPG\",\n draggingLabel = \"Drop to add\",\n multiple = true,\n showBorderBeam = true,\n showFileList = true,\n title = \"Click to upload or drop files\",\n onFilesAccepted,\n onFilesChange,\n}: FileUploadProps) {\n const dragDepthRef = React.useRef(0)\n const [isDragging, setIsDragging] = React.useState(false)\n const [files, setFiles] = React.useState<FileUploadItem[]>([])\n const [rejectionMessage, setRejectionMessage] = React.useState<string | null>(\n null\n )\n\n const commitFiles = React.useCallback(\n (nextFiles: FileList | File[]) => {\n const acceptedFiles = Array.from(nextFiles)\n .filter((file) => matchesAccept(file, accept))\n .slice(0, multiple ? undefined : 1)\n\n if (acceptedFiles.length === 0) {\n setRejectionMessage(\"This file type is not supported here.\")\n return\n }\n\n setRejectionMessage(null)\n onFilesAccepted?.(acceptedFiles)\n\n const items = toUploadItems(acceptedFiles)\n setFiles((previousFiles) => {\n previousFiles.forEach((file) => URL.revokeObjectURL(file.url))\n return items\n })\n onFilesChange?.(items)\n },\n [accept, multiple, onFilesAccepted, onFilesChange]\n )\n\n React.useEffect(() => {\n return () => {\n files.forEach((file) => URL.revokeObjectURL(file.url))\n }\n }, [files])\n\n const dropzone = (\n <label\n className={cn(\n \"relative flex min-h-64 cursor-pointer flex-col items-center justify-center gap-5 overflow-hidden rounded-[1.125rem] border border-dashed bg-background px-6 py-10 text-center transition-[border-color,background-color] duration-200 ease-out\",\n \"motion-reduce:transition-none\",\n isDragging\n ? \"border-foreground/40 bg-accent/35\"\n : \"border-border hover:border-foreground/30 hover:bg-muted/35\"\n )}\n onDragEnter={(event) => {\n event.preventDefault()\n dragDepthRef.current += 1\n setIsDragging(true)\n }}\n onDragLeave={(event) => {\n event.preventDefault()\n dragDepthRef.current = Math.max(0, dragDepthRef.current - 1)\n if (dragDepthRef.current === 0) setIsDragging(false)\n }}\n onDragOver={(event) => event.preventDefault()}\n onDrop={(event) => {\n event.preventDefault()\n dragDepthRef.current = 0\n setIsDragging(false)\n if (event.dataTransfer.files.length > 0) {\n commitFiles(event.dataTransfer.files)\n }\n }}\n >\n <UploadIconCluster\n acceptedFileTypes={acceptedFileTypes}\n isDragging={isDragging}\n />\n <div className=\"space-y-1\">\n <div className=\"text-sm font-medium\">{title}</div>\n <div className=\"text-xs text-muted-foreground\">{description}</div>\n {rejectionMessage ? (\n <div className=\"text-xs text-destructive\">{rejectionMessage}</div>\n ) : null}\n </div>\n <div className=\"inline-flex items-center gap-2 rounded-full border bg-background px-3 py-1 text-xs text-muted-foreground\">\n <HugeiconsIcon icon={Upload01Icon} className=\"size-3.5\" />\n <span>{isDragging ? draggingLabel : browseLabel}</span>\n </div>\n <input\n type=\"file\"\n accept={accept}\n multiple={multiple}\n className=\"sr-only\"\n onChange={(event) => {\n if (event.target.files) {\n commitFiles(event.target.files)\n event.currentTarget.value = \"\"\n }\n }}\n />\n </label>\n )\n\n return (\n <div className={cn(\"space-y-3\", className)}>\n {showBorderBeam ? (\n <BorderBeam\n active={isDragging}\n borderRadius={18}\n brightness={2.4}\n className=\"rounded-[1.125rem]\"\n colorVariant=\"ocean\"\n duration={2.4}\n size=\"md\"\n strength={1}\n theme={borderBeamTheme}\n >\n {dropzone}\n </BorderBeam>\n ) : (\n dropzone\n )}\n {showFileList && files.length > 0 ? (\n <div className=\"rounded-xl border bg-background\">\n {files.map((file) => (\n <div\n key={file.id}\n className=\"flex items-center gap-3 border-b px-3 py-2.5 last:border-b-0\"\n >\n <FileThumbnail\n file={{\n name: file.name,\n type: file.type,\n size: formatBytes(file.size),\n }}\n previewImageUrl={\n file.type.startsWith(\"image/\") ? file.url : null\n }\n className=\"size-10 shrink-0 rounded-lg\"\n showMetadata={false}\n />\n <div className=\"min-w-0 flex-1\">\n <div className=\"truncate text-sm font-medium\">{file.name}</div>\n <div className=\"truncate text-xs text-muted-foreground\">\n {file.type} - {formatBytes(file.size)}\n </div>\n </div>\n <div className=\"rounded-full bg-muted px-2 py-1 text-xs text-muted-foreground\">\n Ready\n </div>\n </div>\n ))}\n </div>\n ) : null}\n </div>\n )\n}"export function FileUploadSource() {return <HighlightedCodeBlock code={fileUploadUsageCode} />diff --git a/apps/v4/components/human-review-docs.tsx b/apps/v4/components/human-review-docs.tsxindex dd8940f..2307f4c 100644--- a/apps/v4/components/human-review-docs.tsx+++ b/apps/v4/components/human-review-docs.tsx@@ -517,8 +517,8 @@ function HumanReviewFieldCard({{formatValue(field.actual)}</div></div>- <div className="rounded-md border border-blue-500/30 bg-blue-500/5 p-2">- <div className="mb-1 text-[11px] font-medium text-blue-700 dark:text-blue-300">+ <div className="rounded-md border bg-muted/30 p-2">+ <div className="mb-1 text-[11px] font-medium text-muted-foreground">Expected</div><HumanReviewValueInput@@ -1168,8 +1168,8 @@ export function HumanReviewFieldCard({{formatValue(field.actual)}</div></div>- <div className="rounded-md border border-blue-500/30 bg-blue-500/5 p-2">- <div className="mb-1 text-[11px] font-medium text-blue-700 dark:text-blue-300">+ <div className="rounded-md border bg-muted/30 p-2">+ <div className="mb-1 text-[11px] font-medium text-muted-foreground">Expected</div><ReviewValueInputdiff --git a/apps/v4/components/pdf-viewer-blocks.tsx b/apps/v4/components/pdf-viewer-blocks.tsxindex 5cc0c1a..63241fa 100644--- a/apps/v4/components/pdf-viewer-blocks.tsx+++ b/apps/v4/components/pdf-viewer-blocks.tsx@@ -365,7 +365,6 @@ function PdfViewerBlockPreview({<div className="absolute inset-0 right-4 bg-[radial-gradient(var(--border)_1px,transparent_1px)] bg-[size:20px_20px]" /><ResizablePanelGroupdirection="horizontal"- autoSaveId={`blocks-${block.id}-viewport`}className="relative z-10 h-full"><ResizablePaneldiff --git a/apps/v4/components/ui/csv-viewer.tsx b/apps/v4/components/ui/csv-viewer.tsxindex b8c3898..8f8b364 100644--- a/apps/v4/components/ui/csv-viewer.tsx+++ b/apps/v4/components/ui/csv-viewer.tsx@@ -141,26 +141,6 @@ function parseDelimitedText(text: string): {}}-function useIsDarkTheme() {- const [isDark, setIsDark] = React.useState(false)-- React.useEffect(() => {- const update = () =>- setIsDark(document.documentElement.classList.contains("dark"))- update()-- const observer = new MutationObserver(update)- observer.observe(document.documentElement, {- attributeFilter: ["class"],- attributes: true,- })-- return () => observer.disconnect()- }, [])-- return isDark-}-function ToolbarTooltip({label,children,@@ -180,7 +160,7 @@ function ToolbarTooltip({export function CsvViewer({ className, data }: CsvViewerProps) {const inputRef = React.useRef<HTMLInputElement | null>(null)- const isDark = useIsDarkTheme()+ const isDark = falseconst [glide, setGlide] = React.useState<GlideDataGridModule | null>(null)const [zoom, setZoom] = React.useState<(typeof ZOOM_OPTIONS)[number]>(1)const [parsed, setParsed] = React.useState(() =>@@ -327,6 +307,7 @@ export function CsvViewer({ className, data }: CsvViewerProps) {onValueChange={(value) =>setZoom(Number(value) as (typeof ZOOM_OPTIONS)[number])}+ modal={false}><SelectTriggersize="sm"@@ -335,7 +316,7 @@ export function CsvViewer({ className, data }: CsvViewerProps) {><SelectValue>{Math.round(zoom * 100)}%</SelectValue></SelectTrigger>- <SelectContent align="end">+ <SelectContent align="end" alignItemWithTrigger={false}>{ZOOM_OPTIONS.map((option) => (<SelectItem key={option} value={option.toString()}>{Math.round(option * 100)}%diff --git a/apps/v4/components/ui/docx-editor.tsx b/apps/v4/components/ui/docx-editor.tsxindex f8e646a..01db2c3 100644--- a/apps/v4/components/ui/docx-editor.tsx+++ b/apps/v4/components/ui/docx-editor.tsx@@ -322,7 +322,7 @@ function useDocumentNightRenderPreference() {React.useEffect(() => {const storedValue = window.localStorage.getItem("docx-editor-night-render")- setNightRenderEnabled(storedValue !== "false")+ setNightRenderEnabled(storedValue === "true")setNightRenderPrefLoaded(true)}, [])@@ -1134,6 +1134,7 @@ function DocxEditorToolbar({value={zoomScale.toString()}onValueChange={(value) => setZoomScale(Number(value))}disabled={controlsDisabled}+ modal={false}><SelectTriggersize="sm"@@ -1142,7 +1143,11 @@ function DocxEditorToolbar({><SelectValue>{Math.round(zoomScale)}%</SelectValue></SelectTrigger>- <SelectContent align="end" className="z-[100010]">+ <SelectContent+ align="end"+ alignItemWithTrigger={false}+ className="z-[100010]"+ >{ZOOM_OPTIONS.map((value) => (<SelectItem key={value} value={value.toString()}>{value}%diff --git a/apps/v4/components/ui/docx-viewer.tsx b/apps/v4/components/ui/docx-viewer.tsxindex ac23e5a..95c0479 100644--- a/apps/v4/components/ui/docx-viewer.tsx+++ b/apps/v4/components/ui/docx-viewer.tsx@@ -177,7 +177,7 @@ function useDocumentNightRenderPreference() {React.useEffect(() => {const storedValue = window.localStorage.getItem("docx-night-render")- setNightRenderEnabled(storedValue !== "false")+ setNightRenderEnabled(storedValue === "true")setNightRenderPrefLoaded(true)}, [])@@ -342,6 +342,7 @@ function DocxToolbar({value={zoomScale.toString()}onValueChange={(value) => setZoomScale(Number(value))}disabled={controlsDisabled}+ modal={false}><SelectTriggersize="sm"@@ -350,7 +351,7 @@ function DocxToolbar({><SelectValue>{Math.round(zoomScale)}%</SelectValue></SelectTrigger>- <SelectContent align="end">+ <SelectContent align="end" alignItemWithTrigger={false}>{ZOOM_OPTIONS.map((value) => (<SelectItem key={value} value={value.toString()}>{value}%diff --git a/apps/v4/components/ui/group.tsx b/apps/v4/components/ui/group.tsxnew file mode 100644index 0000000..1ec0a34--- /dev/null+++ b/apps/v4/components/ui/group.tsx@@ -0,0 +1,94 @@+"use client"++import type * as React from "react"+import { mergeProps } from "@base-ui/react/merge-props"+import { useRender } from "@base-ui/react/use-render"+import { cva, type VariantProps } from "class-variance-authority"++import { cn } from "@/lib/utils"+import { Separator } from "@/registry/new-york-v4/ui/separator"++export const groupVariants = cva(+ "flex w-fit *:focus-visible:z-1 *:has-focus-visible:z-1 has-[>[data-slot=group]]:gap-2 dark:*:[[data-slot=separator]:has(~button:hover):not(:has(~[data-slot=separator]~[data-slot]:hover)),[data-slot=separator]:has(~[data-slot][data-pressed]):not(:has(~[data-slot=separator]~[data-slot][data-pressed]))]:before:bg-input/64 dark:*:[button:hover~[data-slot=separator]:not([data-slot]:hover~[data-slot=separator]~[data-slot=separator]),[data-slot][data-pressed]~[data-slot=separator]:not([data-slot][data-pressed]~[data-slot=separator]~[data-slot=separator])]:before:bg-input/64",+ {+ defaultVariants: {+ orientation: "horizontal",+ },+ variants: {+ orientation: {+ horizontal:+ "*:data-slot:has-[~[data-slot]]:rounded-e-none *:data-slot:has-[~[data-slot]]:border-e-0 *:data-slot:has-[~[data-slot]]:before:rounded-e-none *:data-slot:not-data-[slot=separator]:has-[~[data-slot]]:before:-end-[0.5px] *:pointer-coarse:after:min-w-auto *:[[data-slot]~[data-slot]]:rounded-s-none *:[[data-slot]~[data-slot]]:border-s-0 *:[[data-slot]~[data-slot]]:before:rounded-s-none *:[[data-slot]~[data-slot]:not([data-slot=separator])]:before:-start-[0.5px]",+ vertical:+ "flex-col *:data-slot:has-[~[data-slot]]:rounded-b-none *:data-slot:has-[~[data-slot]]:border-b-0 *:data-slot:has-[~[data-slot]]:before:rounded-b-none *:data-slot:not-data-[slot=separator]:has-[~[data-slot]]:before:-bottom-[0.5px] *:data-slot:not-data-[slot=separator]:has-[~[data-slot]]:before:hidden dark:*:first:before:block dark:*:last:before:hidden *:pointer-coarse:after:min-h-auto *:[[data-slot]~[data-slot]]:rounded-t-none *:[[data-slot]~[data-slot]]:border-t-0 *:[[data-slot]~[data-slot]]:before:rounded-t-none *:[[data-slot]~[data-slot]:not([data-slot=separator])]:before:-top-[0.5px]",+ },+ },+ }+)++export function Group({+ className,+ orientation,+ children,+ ...props+}: {+ className?: string+ orientation?: VariantProps<typeof groupVariants>["orientation"]+ children: React.ReactNode+} & React.ComponentProps<"div">): React.ReactElement {+ return (+ <div+ className={cn(groupVariants({ orientation }), className)}+ data-orientation={orientation}+ data-slot="group"+ role="group"+ {...props}+ >+ {children}+ </div>+ )+}++export function GroupText({+ className,+ render,+ ...props+}: useRender.ComponentProps<"div">): React.ReactElement {+ const defaultProps = {+ className: cn(+ "relative inline-flex items-center gap-2 rounded-lg border border-input bg-muted px-[calc(--spacing(3)-1px)] text-base whitespace-nowrap text-muted-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)] before:shadow-[0_1px_--theme(--color-black/6%)] sm:text-sm dark:bg-input/64 dark:before:shadow-[0_-1px_--theme(--color-white/6%)] [&_svg]:-mx-0.5 [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4",+ className+ ),+ "data-slot": "group-text",+ }++ return useRender({+ defaultTagName: "div",+ props: mergeProps(defaultProps, props),+ render,+ })+}++export function GroupSeparator({+ className,+ orientation = "vertical",+ ...props+}: {+ className?: string+} & React.ComponentProps<typeof Separator>): React.ReactElement {+ return (+ <Separator+ className={cn(+ "pointer-events-none relative z-2 bg-input before:absolute before:inset-0 has-[+[data-slot=input-control]:focus-within,+[data-slot=input-group]:focus-within,+[data-slot=select-trigger]:focus-visible+*,+[data-slot=number-field]:focus-within]:translate-x-px has-[+[data-slot=input-control]:focus-within,+[data-slot=input-group]:focus-within,+[data-slot=select-trigger]:focus-visible+*,+[data-slot=number-field]:focus-within]:bg-ring dark:before:bg-input/32 [[data-slot=input-control]:focus-within+&,[data-slot=input-group]:focus-within+&,[data-slot=select-trigger]:focus-visible+*+&,[data-slot=number-field]:focus-within+&,[data-slot=number-field]:focus-within+input+&]:bg-ring [[data-slot=input-control]:focus-within+&,[data-slot=input-group]:focus-within+&,[data-slot=select-trigger]:focus-visible+*+&,[data-slot=number-field]:focus-within+input+&]:-translate-x-px",+ className+ )}+ orientation={orientation}+ {...props}+ />+ )+}++export {+ Group as ButtonGroup,+ GroupSeparator as ButtonGroupSeparator,+ GroupText as ButtonGroupText,+}diff --git a/apps/v4/components/ui/pdf-viewer.tsx b/apps/v4/components/ui/pdf-viewer.tsxindex 2458c46..7924569 100644--- a/apps/v4/components/ui/pdf-viewer.tsx+++ b/apps/v4/components/ui/pdf-viewer.tsx@@ -815,13 +815,14 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(value={String(zoom)}onValueChange={(value) => setZoom(Number(value))}disabled={controlsDisabled}+ modal={false}><SelectTrigger size="sm" className="w-[84px] min-w-[84px]"><SelectValue placeholder="Zoom">{Math.round(zoom * 100)}%</SelectValue></SelectTrigger>- <SelectContent>+ <SelectContent alignItemWithTrigger={false}>{ZOOM_OPTIONS.map((option) => (<SelectItem key={option} value={String(option)}>{Math.round(option * 100)}%diff --git a/apps/v4/components/ui/xlsx-editor.tsx b/apps/v4/components/ui/xlsx-editor.tsxindex 16ffa49..1912255 100644--- a/apps/v4/components/ui/xlsx-editor.tsx+++ b/apps/v4/components/ui/xlsx-editor.tsx@@ -28,6 +28,7 @@ import { useTheme } from "next-themes"import { cn } from "@/lib/utils"import { Button } from "@/components/ui/button"+import { Group, GroupText } from "@/components/ui/group"import { Input } from "@/components/ui/input"import { ScrollArea } from "@/components/ui/scroll-area"import {@@ -55,8 +56,6 @@ const XLSX_LOADING_INDICATOR_DELAY_MS = 300const XLSX_EDITOR_READ_ONLY_THRESHOLD_BYTES = 5 * 1024 * 1024const XLSX_DROPDOWN_Z_INDEX_CLASS = "z-[100010]"const ZOOM_OPTIONS = [50, 75, 100, 125, 150, 200, 400] as const-const XLSX_EDITOR_INPUT_CHROME_CLASS =- "shadow-none before:shadow-none not-has-disabled:not-has-focus-visible:not-has-aria-invalid:before:shadow-none dark:not-has-disabled:not-has-focus-visible:not-has-aria-invalid:before:shadow-none"const XLSX_EDITOR_SELECT_CHROME_CLASS ="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"@@ -370,6 +369,7 @@ function EditorToolbar({value={currentZoom.toString()}onValueChange={(value) => setZoomScale(Number(value))}disabled={!hasWorkbook}+ modal={false}><SelectTriggersize="sm"@@ -383,6 +383,7 @@ function EditorToolbar({</SelectTrigger><SelectContentalign="end"+ alignItemWithTrigger={false}className={XLSX_DROPDOWN_Z_INDEX_CLASS}>{ZOOM_OPTIONS.map((value) => (@@ -406,44 +407,40 @@ function EditorToolbar({</ToolbarTooltip></div></div>- <div className="flex items-center gap-0 border-t bg-background px-2 py-1">- <Input- className={cn(- "h-8 w-[92px] shrink-0 rounded-r-none border-r-0 font-mono text-xs",- XLSX_EDITOR_INPUT_CHROME_CLASS- )}- readOnly- value={activeCellAddress ?? ""}- />- <div className="-mx-px flex h-8 w-9 shrink-0 items-center justify-center border border-input bg-muted/30 text-[11px] font-semibold text-muted-foreground italic">- fx- </div>- <Input- className={cn(- "h-8 flex-1 rounded-l-none border-l-0",- XLSX_EDITOR_INPUT_CHROME_CLASS- )}- disabled={!hasActiveCell || readOnly}- value={formulaDraft}- onBlur={() => {- commitFormula()- setFormulaFocused(false)- }}- onChange={(event) => setFormulaDraft(event.target.value)}- onFocus={() => {- formulaEditCellRef.current = activeCell- formulaInitialValueRef.current = formulaDraft- setFormulaFocused(true)- }}- onKeyDown={(event) => {- if (event.key === "Enter") {- event.preventDefault()+ <div className="border-t bg-background px-2 py-1">+ <Group className="w-full">+ <Input+ className="h-8 w-[92px] shrink-0 font-mono text-xs"+ readOnly+ value={activeCellAddress ?? ""}+ />+ <GroupText className="h-8 w-9 shrink-0 justify-center px-0 text-[11px] font-semibold italic">+ fx+ </GroupText>+ <Input+ className="h-8 flex-1"+ disabled={!hasActiveCell || readOnly}+ value={formulaDraft}+ onBlur={() => {commitFormula()setFormulaFocused(false)- }- }}- placeholder="Select a cell, then enter a value or formula"- />+ }}+ onChange={(event) => setFormulaDraft(event.target.value)}+ onFocus={() => {+ formulaEditCellRef.current = activeCell+ formulaInitialValueRef.current = formulaDraft+ setFormulaFocused(true)+ }}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ event.preventDefault()+ commitFormula()+ setFormulaFocused(false)+ }+ }}+ placeholder="Select a cell, then enter a value or formula"+ />+ </Group></div></TooltipProvider></div>diff --git a/apps/v4/components/ui/xlsx-viewer.tsx b/apps/v4/components/ui/xlsx-viewer.tsxindex 6d71cb7..e7e4b30 100644--- a/apps/v4/components/ui/xlsx-viewer.tsx+++ b/apps/v4/components/ui/xlsx-viewer.tsx@@ -149,7 +149,7 @@ export function useWorkbookNightRenderPreference() {React.useEffect(() => {const storedValue = window.localStorage.getItem("xlsx-night-render")- setNightRenderEnabled(storedValue !== "false")+ setNightRenderEnabled(storedValue === "true")setNightRenderPrefLoaded(true)}, [])@@ -317,6 +317,7 @@ function WorkbookToolbar({<Selectvalue={currentZoom.toString()}onValueChange={(value) => setZoomScale(Number(value))}+ modal={false}><SelectTriggersize="sm"@@ -325,7 +326,11 @@ function WorkbookToolbar({><SelectValue>{currentZoom}%</SelectValue></SelectTrigger>- <SelectContent align="end" className={XLSX_DROPDOWN_Z_INDEX_CLASS}>+ <SelectContent+ align="end"+ alignItemWithTrigger={false}+ className={XLSX_DROPDOWN_Z_INDEX_CLASS}+ >{ZOOM_OPTIONS.map((value) => (<SelectItem key={value} value={value.toString()}>{value}%diff --git a/apps/v4/components/xlsx-editor-docs.tsx b/apps/v4/components/xlsx-editor-docs.tsxindex b56caae..0aea1d4 100644--- a/apps/v4/components/xlsx-editor-docs.tsx+++ b/apps/v4/components/xlsx-editor-docs.tsx@@ -115,6 +115,7 @@ import { useTheme } from "next-themes"import { cn } from "@/lib/utils"import { Button } from "@/components/ui/button"+import { Group, GroupText } from "@/components/ui/group"import { Input } from "@/components/ui/input"import { ScrollArea } from "@/components/ui/scroll-area"import {@@ -142,8 +143,6 @@ const XLSX_LOADING_INDICATOR_DELAY_MS = 300const XLSX_EDITOR_READ_ONLY_THRESHOLD_BYTES = 5 * 1024 * 1024const XLSX_DROPDOWN_Z_INDEX_CLASS = "z-[100010]"const ZOOM_OPTIONS = [50, 75, 100, 125, 150, 200, 400] as const-const XLSX_EDITOR_INPUT_CHROME_CLASS =- "shadow-none before:shadow-none not-has-disabled:not-has-focus-visible:not-has-aria-invalid:before:shadow-none dark:not-has-disabled:not-has-focus-visible:not-has-aria-invalid:before:shadow-none"const XLSX_EDITOR_SELECT_CHROME_CLASS ="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"@@ -493,44 +492,40 @@ function EditorToolbar({</ToolbarTooltip></div></div>- <div className="flex items-center gap-0 border-t bg-background px-2 py-1">- <Input- className={cn(- "h-8 w-[92px] shrink-0 rounded-r-none border-r-0 font-mono text-xs",- XLSX_EDITOR_INPUT_CHROME_CLASS- )}- readOnly- value={activeCellAddress ?? ""}- />- <div className="-mx-px flex h-8 w-9 shrink-0 items-center justify-center border border-input bg-muted/30 text-[11px] font-semibold text-muted-foreground italic">- fx- </div>- <Input- className={cn(- "h-8 flex-1 rounded-l-none border-l-0",- XLSX_EDITOR_INPUT_CHROME_CLASS- )}- disabled={!hasActiveCell || readOnly}- value={formulaDraft}- onBlur={() => {- commitFormula()- setFormulaFocused(false)- }}- onChange={(event) => setFormulaDraft(event.target.value)}- onFocus={() => {- formulaEditCellRef.current = activeCell- formulaInitialValueRef.current = formulaDraft- setFormulaFocused(true)- }}- onKeyDown={(event) => {- if (event.key === "Enter") {- event.preventDefault()+ <div className="border-t bg-background px-2 py-1">+ <Group className="w-full">+ <Input+ className="h-8 w-[92px] shrink-0 font-mono text-xs"+ readOnly+ value={activeCellAddress ?? ""}+ />+ <GroupText className="h-8 w-9 shrink-0 justify-center px-0 text-[11px] font-semibold italic">+ fx+ </GroupText>+ <Input+ className="h-8 flex-1"+ disabled={!hasActiveCell || readOnly}+ value={formulaDraft}+ onBlur={() => {commitFormula()setFormulaFocused(false)- }- }}- placeholder="Select a cell, then enter a value or formula"- />+ }}+ onChange={(event) => setFormulaDraft(event.target.value)}+ onFocus={() => {+ formulaEditCellRef.current = activeCell+ formulaInitialValueRef.current = formulaDraft+ setFormulaFocused(true)+ }}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ event.preventDefault()+ commitFormula()+ setFormulaFocused(false)+ }+ }}+ placeholder="Select a cell, then enter a value or formula"+ />+ </Group></div></TooltipProvider></div>diff --git a/apps/v4/components/xlsx-viewer-docs.tsx b/apps/v4/components/xlsx-viewer-docs.tsxindex fba183f..7cf8d54 100644--- a/apps/v4/components/xlsx-viewer-docs.tsx+++ b/apps/v4/components/xlsx-viewer-docs.tsx@@ -236,7 +236,7 @@ export function useWorkbookNightRenderPreference() {React.useEffect(() => {const storedValue = window.localStorage.getItem("xlsx-night-render")- setNightRenderEnabled(storedValue !== "false")+ setNightRenderEnabled(storedValue === "true")setNightRenderPrefLoaded(true)}, [])diff --git a/apps/v4/content/docs/components/csv-tsv-viewer.mdx b/apps/v4/content/docs/components/csv-tsv-viewer.mdxindex 8ff2055..2ab7e41 100644--- a/apps/v4/content/docs/components/csv-tsv-viewer.mdx+++ b/apps/v4/content/docs/components/csv-tsv-viewer.mdx@@ -31,7 +31,7 @@ npx shadcn@latest add http://localhost:4000/r/csv-viewer.json<Step>Install the following dependencies:</Step>```bash-npm install @glideapps/[email protected] papaparse lodash+npm install @glideapps/[email protected] @hugeicons/core-free-icons @hugeicons/react papaparse```<Step>Copy and paste the following code into your project.</Step>@@ -67,4 +67,5 @@ The CsvViewer component renders its built-in CSV/TSV upload flow, parser state,| Prop | Type | Default | Required || ---- | ---- | ------- | -------- |-| `-` | `-` | `-` | No |+| `className` | `string` | `-` | No |+| `data` | `string` | `-` | No |diff --git a/apps/v4/content/docs/components/document-splits.mdx b/apps/v4/content/docs/components/document-splits.mdxindex f04fdb3..0ce1e82 100644--- a/apps/v4/content/docs/components/document-splits.mdx+++ b/apps/v4/content/docs/components/document-splits.mdx@@ -33,7 +33,7 @@ npx shadcn@latest add http://localhost:4000/r/document-splits.json<Step>Install the following dependencies:</Step>```bash-npm install react-pdf pdfjs-dist @dnd-kit/core @dnd-kit/sortable @dnd-kit/utilities+npm install @dnd-kit/core @dnd-kit/sortable @dnd-kit/utilities @hugeicons/core-free-icons @hugeicons/react```<Step>Copy and paste the following code into your project.</Step>@@ -61,21 +61,20 @@ npm install react-pdf pdfjs-dist @dnd-kit/core @dnd-kit/sortable @dnd-kit/utilitThe DocumentSplits component renders controlled split groups and paints cached page images through FileThumbnail.-| Prop | Type | Default | Required |-| ------------------ | ------------------------------------------------ | ------- | -------- |-| `splits` | `DocumentSplit[]` | `-` | Yes |-| `thumbnailImages` | `Record<DocumentSplitItemId, string>` | `{}` | No |-| `onSplitsChange` | `(splits: DocumentSplit[]) => void` | `-` | Yes |-| `activePage` | `number` | `-` | No |-| `activeItemId` | `DocumentSplitItemId` | `-` | No |-| `onSelectPage` | `(pageNumber: number) => void` | `-` | No |-| `onSelectItem` | `(itemId: DocumentSplitItemId) => void` | `-` | No |-| `getItemFile` | `(itemId: DocumentSplitItemId) => ThumbnailFile` | PDF | No |-| `getItemLabel` | `(itemId: DocumentSplitItemId) => ReactNode` | page # | No |-| `getSplitLabel` | `(split: DocumentSplit) => string` | pages | No |-| `thumbnailSize` | `{ width: number; height: number }` | PDF | No |-| `labelPlacement` | `"corner" \| "bottom"` | corner | No |-| `onAddSplit` | `() => void` | `-` | No |-| `onRemoveSplit` | `(groupId: string) => void` | `-` | No |-| `withFrameDivider` | `boolean` | `true` | No |-| `className` | `string` | `-` | No |+| Prop | Type | Default | Required |+| ------------------ | ------------------------------------- | ------- | -------- |+| `activePage` | `number` | `-` | Yes |+| `className` | `string` | `-` | No |+| `splits` | `DocumentSplit[]` | `-` | Yes |+| `thumbnailImages` | `Record<DocumentSplitPageId, string>` | `{}` | No |+| `withFrameDivider` | `boolean` | `true` | No |+| `onSelectPage` | `(pageNumber: number) => void` | `-` | Yes |+| `onSplitsChange` | `(splits: DocumentSplit[]) => void` | `-` | Yes |++### DocumentSplit++| Prop | Type | Default | Required |+| ------- | ----------------------- | ------- | -------- |+| `id` | `string` | `-` | Yes |+| `title` | `string` | `-` | Yes |+| `pages` | `DocumentSplitPageId[]` | `-` | Yes |diff --git a/apps/v4/content/docs/components/docx-editor.mdx b/apps/v4/content/docs/components/docx-editor.mdxindex be9335c..af3cb8a 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 http://localhost:4000/r/docx-editor.json<Step>Install the following dependencies:</Step>```bash-npm install @extend-ai/react-docx next-themes+npm install @extend-ai/react-docx @hugeicons/core-free-icons @hugeicons/react next-themes```<Step>diff --git a/apps/v4/content/docs/components/docx-viewer.mdx b/apps/v4/content/docs/components/docx-viewer.mdxindex fdd51bb..d8b5a84 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 http://localhost:4000/r/docx-viewer.json<Step>Install the following dependencies:</Step>```bash-npm install @extend-ai/react-docx+npm install @extend-ai/react-docx @hugeicons/core-free-icons @hugeicons/react next-themes```<Step>Copy and paste the following code into your project.</Step>@@ -66,4 +66,4 @@ The DocxViewerPreview component renders a DOCX file with upload, theme, and zoom| `defaultThumbnailSidebarOpen` | `boolean` | `true` | No || `fileName` | `string` | `-` | No || `rounded` | `boolean` | `false` | No |-| `src` | `string` | `"/samples/demo.docx"` | No |+| `src` | `string` | `-` | No |diff --git a/apps/v4/content/docs/components/e-signature.mdx b/apps/v4/content/docs/components/e-signature.mdxindex b8b7150..0000f8f 100644--- a/apps/v4/content/docs/components/e-signature.mdx+++ b/apps/v4/content/docs/components/e-signature.mdx@@ -30,12 +30,6 @@ npx shadcn@latest add http://localhost:4000/r/e-signature.json<Steps className="mb-0 pt-2">-<Step>Install the following dependencies:</Step>--```bash-npm install signature_pad-```-<Step>Copy and paste the following code into your project.</Step><ESignatureSource />diff --git a/apps/v4/content/docs/components/file-thumbnail.mdx b/apps/v4/content/docs/components/file-thumbnail.mdxindex a69b888..287d019 100644--- a/apps/v4/content/docs/components/file-thumbnail.mdx+++ b/apps/v4/content/docs/components/file-thumbnail.mdx@@ -76,6 +76,7 @@ The FileThumbnail component renders the reusable thumbnail shell. It accepts ext| ----------------------- | ------------------------ | ------- | -------- || `file` | `ThumbnailFile \| File` | `-` | Yes || `className` | `string` | `-` | No |+| `previewAspectRatio` | `number` | `-` | No || `previewClassName` | `string` | `-` | No || `previewContent` | `React.ReactNode` | `-` | No || `previewImageUrl` | `string \| null` | `-` | No |diff --git a/apps/v4/content/docs/components/file-upload.mdx b/apps/v4/content/docs/components/file-upload.mdxindex ffa7fc9..8914ae8 100644--- a/apps/v4/content/docs/components/file-upload.mdx+++ b/apps/v4/content/docs/components/file-upload.mdx@@ -32,7 +32,16 @@ npx shadcn@latest add http://localhost:4000/r/file-upload.json<Step>Install the following dependencies:</Step>```bash-npm install border-beam+npm install @hugeicons/core-free-icons @hugeicons/react border-beam+```++<Step>+ Install the File Thumbnail component because File Upload uses it for selected+ file rows.+</Step>++```bash+npx shadcn@latest add http://localhost:4000/r/file-thumbnail.json```<Step>Copy and paste the following code into your project.</Step>@@ -65,6 +74,7 @@ The FileUpload component renders a drag-and-drop file picker, validates accepted| ------------------- | ----------------------------------- | ------------------------------------- | -------- || `accept` | `string` | `-` | No || `acceptedFileTypes` | `AcceptedFileType[]` | Image, PDF, and Sheet icons | No |+| `borderBeamTheme` | `React.ComponentProps<typeof BorderBeam>["theme"]` | `"light"` | No || `browseLabel` | `string` | `"Browse files"` | No || `className` | `string` | `-` | No || `description` | `string` | `"PDF, DOCX, XLSX, CSV, PNG, or JPG"` | No |diff --git a/apps/v4/content/docs/components/human-review.mdx b/apps/v4/content/docs/components/human-review.mdxindex b1f8b37..5231000 100644--- a/apps/v4/content/docs/components/human-review.mdx+++ b/apps/v4/content/docs/components/human-review.mdx@@ -33,7 +33,7 @@ npx shadcn@latest add http://localhost:4000/r/human-review.json<Step>Install the following dependencies:</Step>```bash-npm install @pierre/diffs+npm install @hugeicons/core-free-icons @hugeicons/react @pierre/diffs```<Step>Copy and paste the following code into your project.</Step>@@ -62,12 +62,12 @@ npm install @pierre/diffsThe HumanReviewPanel component renders editable review fields and a JSON diff for the same extraction output.-| Prop | Type | Default | Required |-| ---------------- | ------------------------------ | ------- | -------- |-| `fields` | `ReviewField[]` | `-` | Yes |-| `values` | `JsonObject` | `-` | Yes |-| `onValuesChange` | `(values: JsonObject) => void` | `-` | Yes |-| `className` | `string` | `-` | No |+| Prop | Type | Default | Required |+| ---------------- | ----------------------------- | --------------- | -------- |+| `fields` | `ReviewField[]` | sample fields | No |+| `activeFieldKey` | `string` | `-` | No |+| `className` | `string` | `-` | No |+| `onFieldFocus` | `(field: ReviewField) => void` | `-` | No |### ReviewField@@ -77,3 +77,4 @@ The HumanReviewPanel component renders editable review fields and a JSON diff fo| `schema` | `ReviewFieldSchema` | `-` | Yes || `actual` | `JsonValue` | `-` | Yes || `expected` | `JsonValue` | `-` | Yes |+| `location` | `{ page: number; area: HighlightArea }` | `-` | No |diff --git a/apps/v4/content/docs/components/ocr-blocks.mdx b/apps/v4/content/docs/components/ocr-blocks.mdxindex 40d884b..3bbb7c2 100644--- a/apps/v4/content/docs/components/ocr-blocks.mdx+++ b/apps/v4/content/docs/components/ocr-blocks.mdx@@ -30,6 +30,12 @@ npx shadcn@latest add http://localhost:4000/r/ocr-blocks.json<Steps className="mb-0 pt-2">+<Step>Install the following dependencies:</Step>++```bash+npm install @hugeicons/core-free-icons @hugeicons/react react-markdown+```+<Step>Copy and paste the following code into your project.</Step><OcrBlocksSource />diff --git a/apps/v4/content/docs/components/pdf-viewer.mdx b/apps/v4/content/docs/components/pdf-viewer.mdxindex 3d458ec..f87aa4d 100644--- a/apps/v4/content/docs/components/pdf-viewer.mdx+++ b/apps/v4/content/docs/components/pdf-viewer.mdx@@ -32,7 +32,7 @@ npx shadcn@latest add http://localhost:4000/r/pdf-viewer.json<Step>Install the following dependencies:</Step>```bash-npm install react-pdf+npm install @hugeicons/core-free-icons @hugeicons/react react-pdf```<Step>Copy and paste the following code into your project.</Step>@@ -66,25 +66,25 @@ import "react-pdf/dist/Page/TextLayer.css"The PDFViewer component renders a scrollable PDF surface with toolbar controls, lazy page rendering, uploads, and page-level extension hooks.-| Prop | Type | Default | Required |-| ----------------------------- | --------------------------------------------------------- | -------------------------- | -------- |-| `file` | `string` | `"/samples/attention.pdf"` | No |-| `className` | `string` | `-` | No |-| `defaultThumbnailSidebarOpen` | `boolean` | `true` | No |-| `defaultZoom` | `number` | `0.75` | No |-| `pageWidth` | `number` | `612` | No |-| `pageHeight` | `number` | `792` | No |-| `pageNumbers` | `number[]` | `-` | No |-| `pageRenderBuffer` | `number` | `2` | 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, pageNumber: number) => void` | `-` | No |-| `onPagePointerMove` | `(event: React.PointerEvent, pageNumber: number) => void` | `-` | No |-| `onPagePointerUp` | `(event: React.PointerEvent, pageNumber: number) => void` | `-` | No |-| `onPagePointerCancel` | `(event: React.PointerEvent, pageNumber: number) => void` | `-` | No |+| Prop | Type | Default | Required |+| ----------------------------- | ------------------------------------------------------------------------- | ------- | -------- |+| `file` | `string` | `-` | No |+| `className` | `string` | `-` | No |+| `defaultThumbnailSidebarOpen` | `boolean` | `true` | No |+| `defaultZoom` | `number` | `0.75` | No |+| `pageWidth` | `number` | `612` | No |+| `pageHeight` | `number` | `792` | No |+| `pageNumbers` | `number[]` | `-` | No |+| `pageRenderBuffer` | `number` | `2` | 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 d5e392b..9e0d508 100644--- a/apps/v4/content/docs/components/xlsx-editor.mdx+++ b/apps/v4/content/docs/components/xlsx-editor.mdx@@ -32,16 +32,16 @@ npx shadcn@latest add http://localhost:4000/r/xlsx-editor.json<Step>Install the following dependencies:</Step>```bash-npm install @extend-ai/react-xlsx next-themes+npm install @extend-ai/react-xlsx @hugeicons/core-free-icons @hugeicons/react next-themes```<Step>Install the Excel Viewer component because the editor reuses its sheet tabs- and table header menu.+ and table header menu, plus the Group primitive used by the formula bar.</Step>```bash-npx shadcn@latest add http://localhost:4000/r/xlsx-viewer.json+npx shadcn@latest add http://localhost:4000/r/xlsx-viewer.json http://localhost:4000/r/group.json```<Step>Copy and paste the following code into your project.</Step>diff --git a/apps/v4/content/docs/components/xlsx-viewer.mdx b/apps/v4/content/docs/components/xlsx-viewer.mdxindex 116b611..fbe8b08 100644--- a/apps/v4/content/docs/components/xlsx-viewer.mdx+++ b/apps/v4/content/docs/components/xlsx-viewer.mdx@@ -32,7 +32,7 @@ npx shadcn@latest add http://localhost:4000/r/xlsx-viewer.json<Step>Install the following dependencies:</Step>```bash-npm install @extend-ai/react-xlsx+npm install @extend-ai/react-xlsx @hugeicons/core-free-icons @hugeicons/react next-themes```<Step>Copy and paste the following code into your project.</Step>@@ -65,4 +65,4 @@ The XlsxViewerPreview component renders an Excel workbook with upload, theme, zo| `className` | `string` | `-` | No || `fileName` | `string` | `-` | No || `rounded` | `boolean` | `false` | No |-| `src` | `string` | `"/samples/crazy-chart-zoo.xlsx"` | No |+| `src` | `string` | `-` | No |diff --git a/apps/v4/package.json b/apps/v4/package.jsonindex 151137e..e542668 100644--- a/apps/v4/package.json+++ b/apps/v4/package.json@@ -22,7 +22,7 @@"@dnd-kit/core": "^6.3.1","@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2",- "@extend-ai/react-docx": "^0.6.5",+ "@extend-ai/react-docx": "^0.6.6","@extend-ai/react-xlsx": "^0.9.1","@glideapps/glide-data-grid": "6.0.4-alpha24","@hugeicons/core-free-icons": "^4.1.1",diff --git a/apps/v4/registry.json b/apps/v4/registry.jsonindex 77a1cf2..b57c849 100644--- a/apps/v4/registry.json+++ b/apps/v4/registry.json@@ -253,6 +253,24 @@}]},+ {+ "name": "group",+ "type": "registry:ui",+ "title": "Group",+ "description": "A connected control group primitive for buttons, inputs, separators, and text addons.",+ "dependencies": [+ "@base-ui/react@^1.4.1",+ "class-variance-authority@^0.7.1"+ ],+ "registryDependencies": ["separator", "utils"],+ "files": [+ {+ "path": "components/ui/group.tsx",+ "type": "registry:ui",+ "target": "@ui/group.tsx"+ }+ ]+ },{"name": "kbd","type": "registry:ui",@@ -575,7 +593,6 @@"input","popover","scroll-area",- "select","separator","spinner","tooltip",@@ -698,6 +715,7 @@],"registryDependencies": ["button",+ "group","input","scroll-area","select",diff --git a/apps/v4/registry/new-york-v4/blocks/human-review.tsx b/apps/v4/registry/new-york-v4/blocks/human-review.tsxindex 18553f6..e490306 100644--- a/apps/v4/registry/new-york-v4/blocks/human-review.tsx+++ b/apps/v4/registry/new-york-v4/blocks/human-review.tsx@@ -520,8 +520,8 @@ function HumanReviewFieldCard({{formatValue(field.actual)}</div></div>- <div className="rounded-md border border-blue-500/30 bg-blue-500/5 p-2">- <div className="mb-1 text-[11px] font-medium text-blue-700 dark:text-blue-300">+ <div className="rounded-md border bg-muted/30 p-2">+ <div className="mb-1 text-[11px] font-medium text-muted-foreground">Expected</div><HumanReviewValueInputdiff --git a/file-thumbnail-page.png b/file-thumbnail-page.pngnew file mode 100644index 0000000..35a19b3Binary files /dev/null and b/file-thumbnail-page.png differdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1e68e09..a6f873e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -31,8 +31,8 @@ importers:specifier: ^3.2.2version: 3.2.2([email protected])'@extend-ai/react-docx':- specifier: ^0.6.5+ specifier: ^0.6.6'@extend-ai/react-xlsx':specifier: ^0.9.1@@ -833,8 +833,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-ezaELz93wdI5qqQPlVzc0nBI4awhbeBVRbRonJM35l3vVyvJGHbYkpiJKsciDXBFDHjXU51I6sZ7j7MzUbK16A==}+ '@extend-ai/[email protected]':+ resolution: {integrity: sha512-HP6b6QZHiQE/uisx60hnuWZfk8cEHmRfyNqL2hWLNwFMLEtcKpt554iaruSEEhWrzbaJWnmjsSlV45j8HVbdlQ==}peerDependencies:react: '>=18'react-dom: '>=18'@@ -5726,7 +5726,7 @@ snapshots:'@eslint/core': 0.13.0levn: 0.4.1dependencies:'@chenglou/pretext': 0.0.5