TypeScript
Refactor viewer routing and shared document surfaces
Andrew Luo62c87d46bf0b
diff --git a/apps/v4/app/layout.tsx b/apps/v4/app/layout.tsxindex fa046d6..c52a002 100644--- a/apps/v4/app/layout.tsx+++ b/apps/v4/app/layout.tsx@@ -1,4 +1,5 @@import type { Metadata } from "next"+import { Analytics } from "@vercel/analytics/next"import { NuqsAdapter } from "nuqs/adapters/next/app"import { META_THEME_COLORS, siteConfig } from "@/lib/config"@@ -53,8 +54,12 @@ export const metadata: Metadata = {],},icons: {- icon: [{ url: "/extend.svg", type: "image/svg+xml" }],- shortcut: [{ url: "/extend.svg", type: "image/svg+xml" }],+ icon: [+ { url: "/extend.svg", type: "image/svg+xml" },+ { url: "/favicon-32x32.png", sizes: "32x32", type: "image/png" },+ { url: "/favicon-16x16.png", sizes: "16x16", type: "image/png" },+ ],+ shortcut: "/favicon.ico",apple: "/apple-touch-icon.png",},manifest: "/site.webmanifest",@@ -102,6 +107,7 @@ export default function RootLayout({</ActiveThemeProvider></LayoutProvider></ThemeProvider>+ <Analytics /><div id="portal" className="fixed top-0 left-0 z-[9999]" /></body></html>diff --git a/apps/v4/components/docx-editor-docs.tsx b/apps/v4/components/docx-editor-docs.tsxindex f9c66b6..1387bd5 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 { PreviewCard as PreviewCardPrimitive } from "@base-ui/react/preview-card"\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 type ParagraphStyleDefinition,\n} from "@extend-ai/react-docx"\nimport {\n ArrowExpandDiagonal01Icon,\n ArrowExpandDiagonal02Icon,\n BorderAll01Icon,\n BorderBottom01Icon,\n BorderHorizontalIcon,\n BorderInnerIcon,\n BorderLeft01Icon,\n BorderNone01Icon,\n BorderRight01Icon,\n BorderTop01Icon,\n BorderVerticalIcon,\n ColumnsThreeCogIcon,\n Download01Icon,\n EditOffIcon,\n FileDiffIcon,\n HighlighterIcon,\n ImageAdd01Icon,\n LeftToRightListBulletIcon,\n LeftToRightListNumberIcon,\n LineIcon,\n Link02Icon,\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n Redo02Icon,\n SidebarLeftIcon,\n Sun03Icon,\n TableIcon,\n TextAlignCenterIcon,\n TextAlignJustifyLeftIcon,\n TextAlignLeft01Icon,\n TextAlignRight01Icon,\n TextBoldIcon,\n TextColorIcon,\n TextItalicIcon,\n TextStrikethroughIcon,\n TextSubscriptIcon,\n TextSuperscriptIcon,\n TextUnderlineIcon,\n Undo02Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\n\nimport { cn } from "@/lib/utils"\nimport { 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 {\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 HIGHLIGHT_PREVIEW_COLORS: Record<string, string> = {\n black: "#111827",\n white: "#ffffff",\n ...Object.fromEntries(\n HIGHLIGHT_COLORS.map((option) => [option.value, option.color])\n ),\n}\nconst DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\nconst DEFAULT_HEADING_PREVIEW_RUN_STYLES: Record<\n 1 | 2 | 3 | 4 | 5 | 6,\n NonNullable<ParagraphStyleDefinition["runStyle"]>\n> = {\n 1: {\n fontFamily: "Calibri Light",\n fontSizePt: 16,\n bold: true,\n color: "#2f5496",\n },\n 2: {\n fontFamily: "Calibri Light",\n fontSizePt: 13,\n bold: true,\n color: "#2f5496",\n },\n 3: {\n fontFamily: "Calibri",\n fontSizePt: 12,\n bold: true,\n color: "#1f3763",\n },\n 4: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n 5: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n 6: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n}\n\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 useControllableDarkMode({\n defaultIsDark = false,\n isDark,\n onIsDarkChange,\n}: {\n defaultIsDark?: boolean\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n}) {\n const [uncontrolledIsDark, setUncontrolledIsDark] =\n React.useState(defaultIsDark)\n const resolvedIsDark = isDark ?? uncontrolledIsDark\n\n const setIsDark = React.useCallback(\n (nextIsDark: boolean) => {\n if (isDark === undefined) {\n setUncontrolledIsDark(nextIsDark)\n }\n\n onIsDarkChange?.(nextIsDark)\n },\n [isDark, onIsDarkChange]\n )\n\n return [resolvedIsDark, setIsDark] as const\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === "string" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes("padding"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\n}\n\nfunction normalizeHexColor(value?: string, fallback = "#111827") {\n if (!value) return fallback\n\n const trimmed = value.trim()\n const threeDigit = /^#([0-9a-f]{3})$/i.exec(trimmed)\n if (threeDigit?.[1]) {\n const [red, green, blue] = threeDigit[1].split("")\n return `#${red}${red}${green}${green}${blue}${blue}`.toLowerCase()\n }\n\n const sixDigit = /^#([0-9a-f]{6})$/i.exec(trimmed)\n if (sixDigit?.[1]) {\n return `#${sixDigit[1].toLowerCase()}`\n }\n\n return fallback\n}\n\nfunction inferParagraphStyleHeadingLevel(value?: string) {\n if (!value) return undefined\n\n const match = value.match(/(?:^|[\\s_-])(?:heading|h)\\s*([1-6])(?:$|[\\s_-])/i)\n const level = match?.[1] ? Number(match[1]) : NaN\n\n return level >= 1 && level <= 6 ? (level as 1 | 2 | 3 | 4 | 5 | 6) : undefined\n}\n\nfunction resolveParagraphStyleHeadingLevel(option?: ParagraphStyleDefinition) {\n if (\n Number.isFinite(option?.headingLevel) &&\n option?.headingLevel &&\n option.headingLevel >= 1 &&\n option.headingLevel <= 6\n ) {\n return option.headingLevel as 1 | 2 | 3 | 4 | 5 | 6\n }\n\n return (\n inferParagraphStyleHeadingLevel(option?.id) ??\n inferParagraphStyleHeadingLevel(option?.name)\n )\n}\n\nfunction resolveParagraphStyleRunPreview(option?: ParagraphStyleDefinition) {\n if (!option) return undefined\n\n const headingLevel = resolveParagraphStyleHeadingLevel(option)\n const headingRunStyle = headingLevel\n ? DEFAULT_HEADING_PREVIEW_RUN_STYLES[headingLevel]\n : undefined\n\n return headingRunStyle\n ? {\n ...headingRunStyle,\n ...(option.runStyle ?? {}),\n }\n : option.runStyle\n}\n\nfunction resolveHighlightPreview(value?: string) {\n if (!value) return undefined\n\n const normalized = value.trim().toLowerCase()\n if (!normalized) return undefined\n\n const hex = normalizeHexColor(normalized, "")\n if (hex) return hex\n\n return HIGHLIGHT_PREVIEW_COLORS[normalized]\n}\n\nfunction themedPreviewColor(\n color: string | undefined,\n documentTheme: DocxDocumentTheme\n) {\n if (documentTheme !== "dark") return color\n if (!color) return "#f3f4f6"\n\n const normalized = color.trim().toLowerCase()\n if (\n normalized === "#000" ||\n normalized === "#000000" ||\n normalized === "#111111" ||\n normalized === "#111827" ||\n normalized === "black" ||\n normalized === "rgb(0,0,0)" ||\n normalized === "rgb(0, 0, 0)"\n ) {\n return "#f3f4f6"\n }\n\n return color\n}\n\nfunction paragraphStylePreviewStyle(\n option: ParagraphStyleDefinition,\n documentTheme: DocxDocumentTheme\n): React.CSSProperties {\n const runStyle = resolveParagraphStyleRunPreview(option)\n const textDecoration = [\n runStyle?.underline ? "underline" : "",\n runStyle?.strike ? "line-through" : "",\n ]\n .filter(Boolean)\n .join(" ")\n\n return {\n textAlign: option.align ?? "left",\n fontFamily: runStyle?.fontFamily,\n fontSize: runStyle?.fontSizePt ? `${runStyle.fontSizePt}pt` : "11pt",\n fontWeight:\n runStyle?.bold !== undefined ? (runStyle.bold ? 700 : 400) : undefined,\n fontStyle: runStyle?.italic ? "italic" : undefined,\n textDecoration: textDecoration || undefined,\n color:\n runStyle?.color !== undefined\n ? themedPreviewColor(normalizeHexColor(runStyle.color), documentTheme)\n : undefined,\n backgroundColor: resolveHighlightPreview(runStyle?.highlight),\n lineHeight: 1,\n whiteSpace: "pre-wrap",\n }\n}\n\nfunction paragraphStylePreviewTriggerId(prefix: string, styleId: string) {\n return `${prefix}-paragraph-style-preview-${styleId.replace(\n /[^a-zA-Z0-9_-]/g,\n "_"\n )}`\n}\n\nfunction parseToolbarSectionColumns(\n sectionPropertiesXml?: string\n): { count: number; gapPx: number } | undefined {\n if (!sectionPropertiesXml) return undefined\n\n const columnsTag = sectionPropertiesXml.match(/<w:cols\\b[^>]*\\/?>/i)?.[0]\n if (!columnsTag) return undefined\n\n const countRaw = columnsTag.match(/\\bw:num="(\\d+)"/i)?.[1]\n const count = countRaw ? Number(countRaw) : 1\n if (!Number.isFinite(count) || count <= 1) return undefined\n\n const gapRaw = columnsTag.match(/\\bw:space="(\\d+)"/i)?.[1]\n const gapTwips = gapRaw ? Number(gapRaw) : 720\n const gapPx = Math.max(0, Math.round((gapTwips * 96) / 1440))\n\n return {\n count: Math.max(2, Math.round(count)),\n gapPx,\n }\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction EditorLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction ToolbarIconButton({\n active,\n children,\n label,\n ...props\n}: React.ComponentProps<typeof Button> & {\n active?: boolean\n label: string\n}) {\n return (\n <ToolbarTooltip label={label}>\n <Button\n type="button"\n variant={active ? "secondary" : "ghost"}\n size="icon-sm"\n aria-label={label}\n data-pressed={active ? "" : undefined}\n {...props}\n >\n {children}\n </Button>\n </ToolbarTooltip>\n )\n}\n\nfunction ToolbarColorInput({\n color,\n disabled,\n icon,\n label,\n onChange,\n}: {\n color: string\n disabled?: boolean\n icon: typeof TextColorIcon\n label: string\n onChange: (color: string) => void\n}) {\n return (\n <ToolbarTooltip label={label}>\n <label\n className={cn(\n "relative inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-lg border border-transparent text-foreground transition-colors hover:bg-accent",\n disabled && "pointer-events-none opacity-64"\n )}\n aria-label={label}\n >\n <HugeiconsIcon icon={icon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: color }}\n />\n <input\n type="color"\n aria-label={label}\n disabled={disabled}\n value={color}\n className="sr-only"\n onChange={(event) => onChange(event.target.value)}\n />\n </label>\n </ToolbarTooltip>\n )\n}\n\nfunction DocxSidebarThumbnail({\n canvasRef,\n displayFileName,\n hasError,\n isActive,\n isLoading,\n pageNumber,\n pixelHeightPx,\n pixelWidthPx,\n previewAspectRatio,\n}: {\n canvasRef: React.RefCallback<HTMLCanvasElement>\n displayFileName: string\n hasError: boolean\n isActive: boolean\n isLoading: boolean\n pageNumber: number\n pixelHeightPx: number\n pixelWidthPx: number\n previewAspectRatio: number\n}) {\n return (\n <FileThumbnail\n file={{\n name: `${displayFileName} page ${pageNumber}`,\n type: DOCX_MIME_TYPE,\n }}\n previewAspectRatio={previewAspectRatio}\n previewClassName="rounded-md bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n renderDocumentPreview={false}\n isLoading={isLoading}\n hasError={hasError}\n className={cn(\n "w-[92px] rounded-md border-0 shadow-xs ring-0 transition-shadow duration-150",\n isActive && "shadow-sm"\n )}\n />\n )\n}\n\nfunction ParagraphStylePreviewCard({\n documentTheme,\n option,\n}: {\n documentTheme: DocxDocumentTheme\n option: ParagraphStyleDefinition\n}) {\n const surfaceStyle: React.CSSProperties =\n documentTheme === "dark"\n ? {\n backgroundColor: "#111827",\n borderColor: "#374151",\n color: "#f3f4f6",\n }\n : {\n backgroundColor: "#ffffff",\n borderColor: "#d4d4d8",\n color: "#111827",\n }\n const secondaryTextColor = documentTheme === "dark" ? "#9ca3af" : "#6b7280"\n\n return (\n <div className="w-[260px] p-3">\n <p className="text-[10px] font-medium tracking-wide text-muted-foreground uppercase">\n Style Preview\n </p>\n <div className="mt-2 rounded-sm border p-2.5" style={surfaceStyle}>\n <p style={paragraphStylePreviewStyle(option, documentTheme)}>\n {option.name}\n </p>\n <p\n className="mt-1 text-[11px]"\n style={{\n color: secondaryTextColor,\n textAlign: option.align ?? "left",\n }}\n >\n The quick brown fox jumps over the lazy dog.\n </p>\n </div>\n </div>\n )\n}\n\nfunction DocxEditorToolbar({\n activePage,\n controlsDisabled,\n editor,\n isReadOnly,\n onImageUploadClick,\n onIsDarkChange,\n onIsReadOnlyChange,\n onOpenLinkEditor,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showNightRenderToggle,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n editor: DocxEditorController\n isReadOnly: boolean\n onImageUploadClick: () => void\n onIsDarkChange: (checked: boolean) => void\n onIsReadOnlyChange: (checked: boolean) => void\n onOpenLinkEditor: () => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showNightRenderToggle: boolean\n zoomScale: number\n}) {\n const { documentTheme, setDocumentTheme } = useDocxDocumentTheme(editor)\n const { layout: pageLayout } = useDocxPageLayout(editor)\n const { paragraphStyles, selectedParagraphStyleId, setParagraphStyle } =\n useDocxParagraphStyles(editor)\n const { lineSpacing, setLineSpacing } = useDocxLineSpacing(editor)\n const { borderContext, activeBorderPresets, applyBorderPreset } =\n useDocxBorders(editor)\n const { showTrackedChanges, setShowTrackedChanges } =\n useDocxTrackChanges(editor)\n const selectedRunStyle = editor.selectedRunStyle\n const selectedParagraph = editor.selectedParagraph\n const paragraphStyleOptions: ParagraphStyleDefinition[] =\n paragraphStyles.length > 0\n ? paragraphStyles\n : [...FALLBACK_PARAGRAPH_STYLE_OPTIONS]\n const selectedParagraphStyleValue =\n selectedParagraphStyleId ??\n paragraphStyleOptions.find((option) => "isDefault" in option)?.id ??\n paragraphStyleOptions[0]?.id ??\n "Normal"\n const selectedParagraphStyleOption =\n paragraphStyleOptions.find(\n (option) => option.id === selectedParagraphStyleValue\n ) ??\n paragraphStyleOptions[0] ??\n FALLBACK_PARAGRAPH_STYLE_OPTIONS[0]\n const paragraphStylePreviewHandle = React.useMemo(\n () => PreviewCardPrimitive.createHandle<ParagraphStyleDefinition>(),\n []\n )\n const paragraphStylePreviewIdPrefix = React.useId()\n const [isParagraphStyleMenuOpen, setIsParagraphStyleMenuOpen] =\n React.useState(false)\n const openParagraphStylePreview = React.useCallback(\n (styleId: string) => {\n paragraphStylePreviewHandle.open(\n paragraphStylePreviewTriggerId(paragraphStylePreviewIdPrefix, styleId)\n )\n },\n [paragraphStylePreviewHandle, paragraphStylePreviewIdPrefix]\n )\n const selectedLineSpacingValue = React.useMemo(() => {\n const current = Number.isFinite(lineSpacing.multiple)\n ? lineSpacing.multiple\n : 1\n const nearest = LINE_SPACING_OPTIONS.reduce((closest, candidate) => {\n return Math.abs(candidate - current) < Math.abs(closest - current)\n ? candidate\n : closest\n }, LINE_SPACING_OPTIONS[0])\n return String(nearest)\n }, [lineSpacing.multiple])\n const textColorValue = normalizeHexColor(selectedRunStyle?.color)\n const highlightColor =\n HIGHLIGHT_COLORS.find(\n (option) => option.value === selectedRunStyle?.highlight\n )?.color ?? "#fff59d"\n const activeNodeIndex =\n editor.selection.kind === "paragraph"\n ? editor.selection.nodeIndex\n : editor.selection.tableIndex\n const letterheadColumns =\n editor.selection.kind === "paragraph" &&\n paragraphLetterheadFloatSideAtNodeIndex(\n editor.model.nodes,\n editor.selection.nodeIndex\n )\n ? { count: 2, gapPx: 28 }\n : undefined\n const sections = editor.model.metadata.sections ?? []\n const activeSection = sections\n .filter((section) => section.startNodeIndex <= activeNodeIndex)\n .at(-1)\n const activeColumns =\n letterheadColumns ??\n parseToolbarSectionColumns(activeSection?.sectionPropertiesXml) ??\n parseToolbarSectionColumns(editor.model.metadata.sectionPropertiesXml) ??\n pageLayout.columns\n const activeBorderControlOptions = BORDER_CONTROL_OPTIONS.filter(\n (option) => activeBorderPresets[option.id]\n )\n const borderTriggerLabel =\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].label\n : "Borders"\n const borderTriggerIcon = borderControlOptionIcon(\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].id\n : "all"\n )\n const canEdit = !controlsDisabled && !isReadOnly\n const canZoomIn = zoomScale < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n const canZoomOut = zoomScale > ZOOM_OPTIONS[0]\n\n const preserveTextSelection = React.useCallback(\n (event: React.MouseEvent<HTMLElement> | React.PointerEvent<HTMLElement>) =>\n event.preventDefault(),\n []\n )\n\n return (\n <div className="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 const nextIsDark = documentTheme !== "dark"\n setDocumentTheme(nextIsDark ? "dark" : "light")\n onIsDarkChange(nextIsDark)\n }}\n >\n <HugeiconsIcon\n icon={documentTheme === "dark" ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </ToolbarIconButton>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <ToolbarIconButton\n label="Show tracked changes"\n active={showTrackedChanges}\n disabled={controlsDisabled}\n onClick={() => setShowTrackedChanges(!showTrackedChanges)}\n >\n <HugeiconsIcon icon={FileDiffIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label={isReadOnly ? "Switch to edit mode" : "Switch to read-only"}\n active={isReadOnly}\n disabled={controlsDisabled}\n onClick={() => onIsReadOnlyChange(!isReadOnly)}\n >\n <HugeiconsIcon icon={EditOffIcon} className="size-4" />\n </ToolbarIconButton>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <ToolbarIconButton\n label="Import DOCX"\n disabled={editor.isImporting}\n onClick={onUploadClick}\n >\n {editor.isImporting ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n )}\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Download DOCX"\n disabled={controlsDisabled || editor.isImporting}\n onClick={editor.exportDocx}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex min-h-12 flex-wrap items-center gap-2 border-b px-3 py-2">\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Undo"\n disabled={!editor.canUndo || isReadOnly}\n onClick={editor.undo}\n >\n <HugeiconsIcon icon={Undo02Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Redo"\n disabled={!editor.canRedo || isReadOnly}\n onClick={editor.redo}\n >\n <HugeiconsIcon icon={Redo02Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <PreviewCardPrimitive.Root handle={paragraphStylePreviewHandle}>\n {({ payload }) => {\n const previewOption = payload ?? selectedParagraphStyleOption\n\n return (\n <>\n <Select\n value={selectedParagraphStyleValue}\n onOpenChange={(open) => {\n setIsParagraphStyleMenuOpen(open)\n\n if (!open) {\n paragraphStylePreviewHandle.close()\n return\n }\n\n window.requestAnimationFrame(() => {\n openParagraphStylePreview(selectedParagraphStyleValue)\n })\n }}\n onValueChange={(value) => {\n if (value) {\n setParagraphStyle(value)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[136px] min-w-[136px]"\n aria-label="Paragraph style"\n >\n <SelectValue placeholder="Style" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010] min-w-[210px]"\n >\n {paragraphStyleOptions.map((option) => {\n const previewTriggerId = paragraphStylePreviewTriggerId(\n paragraphStylePreviewIdPrefix,\n option.id\n )\n\n return (\n <SelectItem\n key={option.id}\n value={option.id}\n label={option.name}\n className="relative min-w-[190px]"\n onFocus={() => openParagraphStylePreview(option.id)}\n onPointerEnter={() =>\n openParagraphStylePreview(option.id)\n }\n >\n <span className="block truncate">\n {option.name}\n </span>\n <PreviewCardPrimitive.Trigger\n id={previewTriggerId}\n handle={paragraphStylePreviewHandle}\n payload={option}\n delay={0}\n closeDelay={120}\n render={\n <span\n aria-hidden="true"\n className="pointer-events-none absolute inset-0 block"\n />\n }\n />\n </SelectItem>\n )\n })}\n </SelectContent>\n </Select>\n {isParagraphStyleMenuOpen && previewOption ? (\n <PreviewCardPrimitive.Portal>\n <PreviewCardPrimitive.Positioner\n side="right"\n align="start"\n sideOffset={10}\n alignOffset={-4}\n className="z-[100020] transition-[top,left,right,bottom,transform] duration-100 ease-out data-instant:transition-none"\n >\n <PreviewCardPrimitive.Popup\n data-slot="paragraph-style-preview-card"\n className="origin-(--transform-origin) rounded-lg border bg-popover text-popover-foreground shadow-lg/5 transition-opacity duration-100 outline-none not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:opacity-0 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]"\n >\n <ParagraphStylePreviewCard\n documentTheme={documentTheme}\n option={previewOption}\n />\n </PreviewCardPrimitive.Popup>\n </PreviewCardPrimitive.Positioner>\n </PreviewCardPrimitive.Portal>\n ) : null}\n </>\n )\n }}\n </PreviewCardPrimitive.Root>\n\n <Select\n value={selectedRunStyle?.fontFamily ?? "Calibri"}\n onValueChange={(value) => {\n if (value) {\n editor.setFontFamily(value)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[156px] min-w-[156px]"\n aria-label="Font family"\n >\n <SelectValue placeholder="Font" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {FONT_FAMILIES.map((fontFamily) => (\n <SelectItem key={fontFamily} value={fontFamily}>\n <span style={{ fontFamily }}>{fontFamily}</span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={String(Math.round(selectedRunStyle?.fontSizePt ?? 12))}\n onValueChange={(value) => {\n const nextSize = Number(value)\n if (Number.isFinite(nextSize)) {\n editor.setFontSize(nextSize)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[86px] min-w-[86px]"\n aria-label="Font size"\n >\n <SelectValue placeholder="Size" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {FONT_SIZE_OPTIONS.map((size) => (\n <SelectItem key={size} value={String(size)}>\n {size} pt\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={selectedLineSpacingValue}\n onValueChange={(value) => {\n const nextSpacing = Number(value)\n if (Number.isFinite(nextSpacing)) {\n setLineSpacing(nextSpacing)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[94px] min-w-[94px]"\n aria-label="Line spacing"\n >\n <SelectValue placeholder="Spacing" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {LINE_SPACING_OPTIONS.map((spacing) => (\n <SelectItem key={spacing} value={String(spacing)}>\n {spacing}x\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Bold"\n active={Boolean(selectedRunStyle?.bold)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleBold}\n >\n <HugeiconsIcon icon={TextBoldIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Italic"\n active={Boolean(selectedRunStyle?.italic)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleItalic}\n >\n <HugeiconsIcon icon={TextItalicIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Underline"\n active={Boolean(selectedRunStyle?.underline)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleUnderline}\n >\n <HugeiconsIcon icon={TextUnderlineIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Strikethrough"\n active={Boolean(selectedRunStyle?.strike)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleStrike}\n >\n <HugeiconsIcon icon={TextStrikethroughIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Superscript"\n active={selectedRunStyle?.verticalAlign === "superscript"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleSuperscript}\n >\n <HugeiconsIcon icon={TextSuperscriptIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Subscript"\n active={selectedRunStyle?.verticalAlign === "subscript"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleSubscript}\n >\n <HugeiconsIcon icon={TextSubscriptIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarColorInput\n label="Text color"\n icon={TextColorIcon}\n color={textColorValue}\n disabled={!canEdit}\n onChange={(color) =>\n editor.setTextColor(normalizeHexColor(color))\n }\n />\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={!canEdit}\n aria-label="Highlight color"\n className="relative"\n >\n <HugeiconsIcon icon={HighlighterIcon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: highlightColor }}\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="z-[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 modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(zoomScale)}%</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="end"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarIconButton\n label="Zoom in"\n disabled={controlsDisabled || !canZoomIn}\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, 1)\n )\n }\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nexport function DocxEditorPreview({\n className,\n defaultIsDark = false,\n fileName,\n isDark: controlledIsDark,\n onIsDarkChange,\n rounded = false,\n src,\n}: {\n className?: string\n defaultIsDark?: boolean\n fileName?: string\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n rounded?: boolean\n src?: string\n}) {\n const [effectiveIsDark, setIsDark] = useControllableDarkMode({\n defaultIsDark,\n isDark: controlledIsDark,\n onIsDarkChange,\n })\n\n return (\n <DocxEditorContent\n className={className}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setIsDark={setIsDark}\n shouldRenderNightMode\n url={src}\n />\n )\n}\n\nfunction DocxEditorContent({\n className,\n effectiveIsDark,\n fileName,\n rounded,\n setIsDark,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n effectiveIsDark: boolean\n fileName?: string\n rounded: boolean\n setIsDark: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const imageInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [activePage, setActivePage] = React.useState(1)\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const [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 [reportedPageCount, setReportedPageCount] = React.useState(0)\n const thumbnailEditor = React.useMemo<DocxEditorController>(\n () => ({\n ...editor,\n totalPages: Math.max(editor.totalPages, reportedPageCount),\n }),\n [editor, editor.totalPages, reportedPageCount]\n )\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n []\n )\n const { thumbnails } = useDocxViewerThumbnails(\n thumbnailEditor,\n thumbnailOptions\n )\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <EditorLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const hasDocument = Boolean(url || uploadedDocxFile)\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, reportedPageCount || editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(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 setReportedPageCount(0)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n setReportedPageCount(0)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url\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 setReportedPageCount(0)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n async function handleImageUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n await editor.insertImageFile(file)\n }\n\n function openLinkEditor() {\n setLinkDraft(editor.selectedLink ?? "")\n setLinkEditorOpen(true)\n }\n\n function applyLink() {\n editor.setLink(linkDraft.trim() || undefined)\n setLinkEditorOpen(false)\n }\n\n return (\n <div\n className={cn(\n "flex h-[720px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n <input\n ref={imageInputRef}\n type="file"\n accept="image/*"\n className="hidden"\n onChange={handleImageUpload}\n />\n <DocxEditorToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n editor={editor}\n isReadOnly={isReadOnly}\n onImageUploadClick={() => imageInputRef.current?.click()}\n onIsDarkChange={setIsDark}\n onIsReadOnlyChange={setIsReadOnly}\n onOpenLinkEditor={openLinkEditor}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showNightRenderToggle={shouldRenderNightMode}\n zoomScale={zoomScale}\n />\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {linkEditorOpen ? (\n <div className="absolute top-3 left-1/2 z-50 flex w-[min(420px,calc(100%-2rem))] -translate-x-1/2 items-center gap-2 rounded-lg border bg-background p-2 shadow-lg">\n <Input\n value={linkDraft}\n onChange={(event) => setLinkDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === "Enter") {\n event.preventDefault()\n applyLink()\n }\n if (event.key === "Escape") {\n setLinkEditorOpen(false)\n }\n }}\n placeholder="https://example.com"\n aria-label="Link URL"\n />\n <Button type="button" size="sm" onClick={applyLink}>\n Apply\n </Button>\n <Button\n type="button"\n size="sm"\n variant="ghost"\n onClick={() => {\n editor.setLink(undefined)\n setLinkEditorOpen(false)\n }}\n >\n Clear\n </Button>\n </div>\n ) : null}\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}\n >\n <div className="h-full overflow-auto">\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </>\n ) : (\n <div className="flex flex-col items-center gap-3">\n {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (\n <Button\n key={thumbnail.pageIndex}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent text-foreground",\n thumbnail.pageNumber !== activePage &&\n "text-muted-foreground"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => scrollToPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n !thumbnail.isMounted &&\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n ))}\n </div>\n )}\n </div>\n </div>\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 onPageCountChange={handlePageCountChange}\n />\n </div>\n </div>\n )}\n </div>\n </div>\n </div>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport { PreviewCard as PreviewCardPrimitive } from "@base-ui/react/preview-card"\nimport {\n DocxEditorViewer,\n paragraphLetterheadFloatSideAtNodeIndex,\n useDocxBorders,\n 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 type ParagraphStyleDefinition,\n} from "@extend-ai/react-docx"\nimport {\n ArrowExpandDiagonal01Icon,\n ArrowExpandDiagonal02Icon,\n BorderAll01Icon,\n BorderBottom01Icon,\n BorderHorizontalIcon,\n BorderInnerIcon,\n BorderLeft01Icon,\n BorderNone01Icon,\n BorderRight01Icon,\n BorderTop01Icon,\n BorderVerticalIcon,\n ColumnsThreeCogIcon,\n Download01Icon,\n EditOffIcon,\n FileDiffIcon,\n HighlighterIcon,\n ImageAdd01Icon,\n LeftToRightListBulletIcon,\n LeftToRightListNumberIcon,\n LineIcon,\n Link02Icon,\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n Redo02Icon,\n SidebarLeftIcon,\n Sun03Icon,\n TableIcon,\n TextAlignCenterIcon,\n TextAlignJustifyLeftIcon,\n TextAlignLeft01Icon,\n TextAlignRight01Icon,\n TextBoldIcon,\n TextColorIcon,\n TextItalicIcon,\n TextStrikethroughIcon,\n TextSubscriptIcon,\n TextSuperscriptIcon,\n TextUnderlineIcon,\n Undo02Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\n\nimport { cn } from "@/lib/utils"\nimport { 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 {\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 HIGHLIGHT_PREVIEW_COLORS: Record<string, string> = {\n black: "#111827",\n white: "#ffffff",\n ...Object.fromEntries(\n HIGHLIGHT_COLORS.map((option) => [option.value, option.color])\n ),\n}\nconst DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\nconst DEFAULT_HEADING_PREVIEW_RUN_STYLES: Record<\n 1 | 2 | 3 | 4 | 5 | 6,\n NonNullable<ParagraphStyleDefinition["runStyle"]>\n> = {\n 1: {\n fontFamily: "Calibri Light",\n fontSizePt: 16,\n bold: true,\n color: "#2f5496",\n },\n 2: {\n fontFamily: "Calibri Light",\n fontSizePt: 13,\n bold: true,\n color: "#2f5496",\n },\n 3: {\n fontFamily: "Calibri",\n fontSizePt: 12,\n bold: true,\n color: "#1f3763",\n },\n 4: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n 5: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n 6: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n}\n\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 useControllableDarkMode({\n defaultIsDark = false,\n isDark,\n onIsDarkChange,\n}: {\n defaultIsDark?: boolean\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n}) {\n const [uncontrolledIsDark, setUncontrolledIsDark] =\n React.useState(defaultIsDark)\n const resolvedIsDark = isDark ?? uncontrolledIsDark\n\n const setIsDark = React.useCallback(\n (nextIsDark: boolean) => {\n if (isDark === undefined) {\n setUncontrolledIsDark(nextIsDark)\n }\n\n onIsDarkChange?.(nextIsDark)\n },\n [isDark, onIsDarkChange]\n )\n\n return [resolvedIsDark, setIsDark] as const\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === "string" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes("padding"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\n}\n\nfunction normalizeHexColor(value?: string, fallback = "#111827") {\n if (!value) return fallback\n\n const trimmed = value.trim()\n const threeDigit = /^#([0-9a-f]{3})$/i.exec(trimmed)\n if (threeDigit?.[1]) {\n const [red, green, blue] = threeDigit[1].split("")\n return `#${red}${red}${green}${green}${blue}${blue}`.toLowerCase()\n }\n\n const sixDigit = /^#([0-9a-f]{6})$/i.exec(trimmed)\n if (sixDigit?.[1]) {\n return `#${sixDigit[1].toLowerCase()}`\n }\n\n return fallback\n}\n\nfunction inferParagraphStyleHeadingLevel(value?: string) {\n if (!value) return undefined\n\n const match = value.match(/(?:^|[\\s_-])(?:heading|h)\\s*([1-6])(?:$|[\\s_-])/i)\n const level = match?.[1] ? Number(match[1]) : NaN\n\n return level >= 1 && level <= 6 ? (level as 1 | 2 | 3 | 4 | 5 | 6) : undefined\n}\n\nfunction resolveParagraphStyleHeadingLevel(option?: ParagraphStyleDefinition) {\n if (\n Number.isFinite(option?.headingLevel) &&\n option?.headingLevel &&\n option.headingLevel >= 1 &&\n option.headingLevel <= 6\n ) {\n return option.headingLevel as 1 | 2 | 3 | 4 | 5 | 6\n }\n\n return (\n inferParagraphStyleHeadingLevel(option?.id) ??\n inferParagraphStyleHeadingLevel(option?.name)\n )\n}\n\nfunction resolveParagraphStyleRunPreview(option?: ParagraphStyleDefinition) {\n if (!option) return undefined\n\n const headingLevel = resolveParagraphStyleHeadingLevel(option)\n const headingRunStyle = headingLevel\n ? DEFAULT_HEADING_PREVIEW_RUN_STYLES[headingLevel]\n : undefined\n\n return headingRunStyle\n ? {\n ...headingRunStyle,\n ...(option.runStyle ?? {}),\n }\n : option.runStyle\n}\n\nfunction resolveHighlightPreview(value?: string) {\n if (!value) return undefined\n\n const normalized = value.trim().toLowerCase()\n if (!normalized) return undefined\n\n const hex = normalizeHexColor(normalized, "")\n if (hex) return hex\n\n return HIGHLIGHT_PREVIEW_COLORS[normalized]\n}\n\nfunction themedPreviewColor(\n color: string | undefined,\n documentTheme: DocxDocumentTheme\n) {\n if (documentTheme !== "dark") return color\n if (!color) return "#f3f4f6"\n\n const normalized = color.trim().toLowerCase()\n if (\n normalized === "#000" ||\n normalized === "#000000" ||\n normalized === "#111111" ||\n normalized === "#111827" ||\n normalized === "black" ||\n normalized === "rgb(0,0,0)" ||\n normalized === "rgb(0, 0, 0)"\n ) {\n return "#f3f4f6"\n }\n\n return color\n}\n\nfunction paragraphStylePreviewStyle(\n option: ParagraphStyleDefinition,\n documentTheme: DocxDocumentTheme\n): React.CSSProperties {\n const runStyle = resolveParagraphStyleRunPreview(option)\n const textDecoration = [\n runStyle?.underline ? "underline" : "",\n runStyle?.strike ? "line-through" : "",\n ]\n .filter(Boolean)\n .join(" ")\n\n return {\n textAlign: option.align ?? "left",\n fontFamily: runStyle?.fontFamily,\n fontSize: runStyle?.fontSizePt ? `${runStyle.fontSizePt}pt` : "11pt",\n fontWeight:\n runStyle?.bold !== undefined ? (runStyle.bold ? 700 : 400) : undefined,\n fontStyle: runStyle?.italic ? "italic" : undefined,\n textDecoration: textDecoration || undefined,\n color:\n runStyle?.color !== undefined\n ? themedPreviewColor(normalizeHexColor(runStyle.color), documentTheme)\n : undefined,\n backgroundColor: resolveHighlightPreview(runStyle?.highlight),\n lineHeight: 1,\n whiteSpace: "pre-wrap",\n }\n}\n\nfunction paragraphStylePreviewTriggerId(prefix: string, styleId: string) {\n return `${prefix}-paragraph-style-preview-${styleId.replace(\n /[^a-zA-Z0-9_-]/g,\n "_"\n )}`\n}\n\nfunction parseToolbarSectionColumns(\n sectionPropertiesXml?: string\n): { count: number; gapPx: number } | undefined {\n if (!sectionPropertiesXml) return undefined\n\n const columnsTag = sectionPropertiesXml.match(/<w:cols\\b[^>]*\\/?>/i)?.[0]\n if (!columnsTag) return undefined\n\n const countRaw = columnsTag.match(/\\bw:num="(\\d+)"/i)?.[1]\n const count = countRaw ? Number(countRaw) : 1\n if (!Number.isFinite(count) || count <= 1) return undefined\n\n const gapRaw = columnsTag.match(/\\bw:space="(\\d+)"/i)?.[1]\n const gapTwips = gapRaw ? Number(gapRaw) : 720\n const gapPx = Math.max(0, Math.round((gapTwips * 96) / 1440))\n\n return {\n count: Math.max(2, Math.round(count)),\n gapPx,\n }\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction EditorLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction ToolbarIconButton({\n active,\n children,\n label,\n ...props\n}: React.ComponentProps<typeof Button> & {\n active?: boolean\n label: string\n}) {\n return (\n <ToolbarTooltip label={label}>\n <Button\n type="button"\n variant={active ? "secondary" : "ghost"}\n size="icon-sm"\n aria-label={label}\n data-pressed={active ? "" : undefined}\n {...props}\n >\n {children}\n </Button>\n </ToolbarTooltip>\n )\n}\n\nfunction ToolbarColorInput({\n color,\n disabled,\n icon,\n label,\n onChange,\n}: {\n color: string\n disabled?: boolean\n icon: typeof TextColorIcon\n label: string\n onChange: (color: string) => void\n}) {\n return (\n <ToolbarTooltip label={label}>\n <label\n className={cn(\n "relative inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-lg border border-transparent text-foreground transition-colors hover:bg-accent",\n disabled && "pointer-events-none opacity-64"\n )}\n aria-label={label}\n >\n <HugeiconsIcon icon={icon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: color }}\n />\n <input\n type="color"\n aria-label={label}\n disabled={disabled}\n value={color}\n className="sr-only"\n onChange={(event) => onChange(event.target.value)}\n />\n </label>\n </ToolbarTooltip>\n )\n}\n\nfunction DocxSidebarThumbnail({\n canvasRef,\n displayFileName,\n hasError,\n isActive,\n isLoading,\n pageNumber,\n pixelHeightPx,\n pixelWidthPx,\n previewAspectRatio,\n}: {\n canvasRef: React.RefCallback<HTMLCanvasElement>\n displayFileName: string\n hasError: boolean\n isActive: boolean\n isLoading: boolean\n pageNumber: number\n pixelHeightPx: number\n pixelWidthPx: number\n previewAspectRatio: number\n}) {\n return (\n <FileThumbnail\n file={{\n name: `${displayFileName} page ${pageNumber}`,\n type: DOCX_MIME_TYPE,\n }}\n previewAspectRatio={previewAspectRatio}\n previewClassName="rounded-md bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n isLoading={isLoading}\n hasError={hasError}\n className={cn(\n "w-[92px] rounded-md border-0 shadow-xs ring-0 transition-shadow duration-150",\n isActive && "shadow-sm"\n )}\n />\n )\n}\n\nfunction ParagraphStylePreviewCard({\n documentTheme,\n option,\n}: {\n documentTheme: DocxDocumentTheme\n option: ParagraphStyleDefinition\n}) {\n const surfaceStyle: React.CSSProperties =\n documentTheme === "dark"\n ? {\n backgroundColor: "#111827",\n borderColor: "#374151",\n color: "#f3f4f6",\n }\n : {\n backgroundColor: "#ffffff",\n borderColor: "#d4d4d8",\n color: "#111827",\n }\n const secondaryTextColor = documentTheme === "dark" ? "#9ca3af" : "#6b7280"\n\n return (\n <div className="w-[260px] p-3">\n <p className="text-[10px] font-medium tracking-wide text-muted-foreground uppercase">\n Style Preview\n </p>\n <div className="mt-2 rounded-sm border p-2.5" style={surfaceStyle}>\n <p style={paragraphStylePreviewStyle(option, documentTheme)}>\n {option.name}\n </p>\n <p\n className="mt-1 text-[11px]"\n style={{\n color: secondaryTextColor,\n textAlign: option.align ?? "left",\n }}\n >\n The quick brown fox jumps over the lazy dog.\n </p>\n </div>\n </div>\n )\n}\n\nfunction DocxEditorToolbar({\n activePage,\n controlsDisabled,\n editor,\n isReadOnly,\n onImageUploadClick,\n onIsDarkChange,\n onIsReadOnlyChange,\n onOpenLinkEditor,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showNightRenderToggle,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n editor: DocxEditorController\n isReadOnly: boolean\n onImageUploadClick: () => void\n onIsDarkChange: (checked: boolean) => void\n onIsReadOnlyChange: (checked: boolean) => void\n onOpenLinkEditor: () => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showNightRenderToggle: boolean\n zoomScale: number\n}) {\n const { documentTheme, setDocumentTheme } = useDocxDocumentTheme(editor)\n const { layout: pageLayout } = useDocxPageLayout(editor)\n const { paragraphStyles, selectedParagraphStyleId, setParagraphStyle } =\n useDocxParagraphStyles(editor)\n const { lineSpacing, setLineSpacing } = useDocxLineSpacing(editor)\n const { borderContext, activeBorderPresets, applyBorderPreset } =\n useDocxBorders(editor)\n const { showTrackedChanges, setShowTrackedChanges } =\n useDocxTrackChanges(editor)\n const selectedRunStyle = editor.selectedRunStyle\n const selectedParagraph = editor.selectedParagraph\n const paragraphStyleOptions: ParagraphStyleDefinition[] =\n paragraphStyles.length > 0\n ? paragraphStyles\n : [...FALLBACK_PARAGRAPH_STYLE_OPTIONS]\n const selectedParagraphStyleValue =\n selectedParagraphStyleId ??\n paragraphStyleOptions.find((option) => "isDefault" in option)?.id ??\n paragraphStyleOptions[0]?.id ??\n "Normal"\n const selectedParagraphStyleOption =\n paragraphStyleOptions.find(\n (option) => option.id === selectedParagraphStyleValue\n ) ??\n paragraphStyleOptions[0] ??\n FALLBACK_PARAGRAPH_STYLE_OPTIONS[0]\n const paragraphStylePreviewHandle = React.useMemo(\n () => PreviewCardPrimitive.createHandle<ParagraphStyleDefinition>(),\n []\n )\n const paragraphStylePreviewIdPrefix = React.useId()\n const [isParagraphStyleMenuOpen, setIsParagraphStyleMenuOpen] =\n React.useState(false)\n const openParagraphStylePreview = React.useCallback(\n (styleId: string) => {\n paragraphStylePreviewHandle.open(\n paragraphStylePreviewTriggerId(paragraphStylePreviewIdPrefix, styleId)\n )\n },\n [paragraphStylePreviewHandle, paragraphStylePreviewIdPrefix]\n )\n const selectedLineSpacingValue = React.useMemo(() => {\n const current = Number.isFinite(lineSpacing.multiple)\n ? lineSpacing.multiple\n : 1\n const nearest = LINE_SPACING_OPTIONS.reduce((closest, candidate) => {\n return Math.abs(candidate - current) < Math.abs(closest - current)\n ? candidate\n : closest\n }, LINE_SPACING_OPTIONS[0])\n return String(nearest)\n }, [lineSpacing.multiple])\n const textColorValue = normalizeHexColor(selectedRunStyle?.color)\n const highlightColor =\n HIGHLIGHT_COLORS.find(\n (option) => option.value === selectedRunStyle?.highlight\n )?.color ?? "#fff59d"\n const activeNodeIndex =\n editor.selection.kind === "paragraph"\n ? editor.selection.nodeIndex\n : editor.selection.tableIndex\n const letterheadColumns =\n editor.selection.kind === "paragraph" &&\n paragraphLetterheadFloatSideAtNodeIndex(\n editor.model.nodes,\n editor.selection.nodeIndex\n )\n ? { count: 2, gapPx: 28 }\n : undefined\n const sections = editor.model.metadata.sections ?? []\n const activeSection = sections\n .filter((section) => section.startNodeIndex <= activeNodeIndex)\n .at(-1)\n const activeColumns =\n letterheadColumns ??\n parseToolbarSectionColumns(activeSection?.sectionPropertiesXml) ??\n parseToolbarSectionColumns(editor.model.metadata.sectionPropertiesXml) ??\n pageLayout.columns\n const activeBorderControlOptions = BORDER_CONTROL_OPTIONS.filter(\n (option) => activeBorderPresets[option.id]\n )\n const borderTriggerLabel =\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].label\n : "Borders"\n const borderTriggerIcon = borderControlOptionIcon(\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].id\n : "all"\n )\n const canEdit = !controlsDisabled && !isReadOnly\n const canZoomIn = zoomScale < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n const canZoomOut = zoomScale > ZOOM_OPTIONS[0]\n\n const preserveTextSelection = React.useCallback(\n (event: React.MouseEvent<HTMLElement> | React.PointerEvent<HTMLElement>) =>\n event.preventDefault(),\n []\n )\n\n return (\n <div className="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 const nextIsDark = documentTheme !== "dark"\n setDocumentTheme(nextIsDark ? "dark" : "light")\n onIsDarkChange(nextIsDark)\n }}\n >\n <HugeiconsIcon\n icon={documentTheme === "dark" ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </ToolbarIconButton>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <ToolbarIconButton\n label="Show tracked changes"\n active={showTrackedChanges}\n disabled={controlsDisabled}\n onClick={() => setShowTrackedChanges(!showTrackedChanges)}\n >\n <HugeiconsIcon icon={FileDiffIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label={isReadOnly ? "Switch to edit mode" : "Switch to read-only"}\n active={isReadOnly}\n disabled={controlsDisabled}\n onClick={() => onIsReadOnlyChange(!isReadOnly)}\n >\n <HugeiconsIcon icon={EditOffIcon} className="size-4" />\n </ToolbarIconButton>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <ToolbarIconButton\n label="Import DOCX"\n disabled={editor.isImporting}\n onClick={onUploadClick}\n >\n {editor.isImporting ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n )}\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Download DOCX"\n disabled={controlsDisabled || editor.isImporting}\n onClick={editor.exportDocx}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex min-h-12 flex-wrap items-center gap-2 border-b px-3 py-2">\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Undo"\n disabled={!editor.canUndo || isReadOnly}\n onClick={editor.undo}\n >\n <HugeiconsIcon icon={Undo02Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Redo"\n disabled={!editor.canRedo || isReadOnly}\n onClick={editor.redo}\n >\n <HugeiconsIcon icon={Redo02Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <PreviewCardPrimitive.Root handle={paragraphStylePreviewHandle}>\n {({ payload }) => {\n const previewOption = payload ?? selectedParagraphStyleOption\n\n return (\n <>\n <Select\n value={selectedParagraphStyleValue}\n onOpenChange={(open) => {\n setIsParagraphStyleMenuOpen(open)\n\n if (!open) {\n paragraphStylePreviewHandle.close()\n return\n }\n\n window.requestAnimationFrame(() => {\n openParagraphStylePreview(selectedParagraphStyleValue)\n })\n }}\n onValueChange={(value) => {\n if (value) {\n setParagraphStyle(value)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[136px] min-w-[136px]"\n aria-label="Paragraph style"\n >\n <SelectValue placeholder="Style" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010] min-w-[210px]"\n >\n {paragraphStyleOptions.map((option) => {\n const previewTriggerId = paragraphStylePreviewTriggerId(\n paragraphStylePreviewIdPrefix,\n option.id\n )\n\n return (\n <SelectItem\n key={option.id}\n value={option.id}\n label={option.name}\n className="relative min-w-[190px]"\n onFocus={() => openParagraphStylePreview(option.id)}\n onPointerEnter={() =>\n openParagraphStylePreview(option.id)\n }\n >\n <span className="block truncate">\n {option.name}\n </span>\n <PreviewCardPrimitive.Trigger\n id={previewTriggerId}\n handle={paragraphStylePreviewHandle}\n payload={option}\n delay={0}\n closeDelay={120}\n render={\n <span\n aria-hidden="true"\n className="pointer-events-none absolute inset-0 block"\n />\n }\n />\n </SelectItem>\n )\n })}\n </SelectContent>\n </Select>\n {isParagraphStyleMenuOpen && previewOption ? (\n <PreviewCardPrimitive.Portal>\n <PreviewCardPrimitive.Positioner\n side="right"\n align="start"\n sideOffset={10}\n alignOffset={-4}\n className="z-[100020] transition-[top,left,right,bottom,transform] duration-100 ease-out data-instant:transition-none"\n >\n <PreviewCardPrimitive.Popup\n data-slot="paragraph-style-preview-card"\n className="origin-(--transform-origin) rounded-lg border bg-popover text-popover-foreground shadow-lg/5 transition-opacity duration-100 outline-none not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:opacity-0 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]"\n >\n <ParagraphStylePreviewCard\n documentTheme={documentTheme}\n option={previewOption}\n />\n </PreviewCardPrimitive.Popup>\n </PreviewCardPrimitive.Positioner>\n </PreviewCardPrimitive.Portal>\n ) : null}\n </>\n )\n }}\n </PreviewCardPrimitive.Root>\n\n <Select\n value={selectedRunStyle?.fontFamily ?? "Calibri"}\n onValueChange={(value) => {\n if (value) {\n editor.setFontFamily(value)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[156px] min-w-[156px]"\n aria-label="Font family"\n >\n <SelectValue placeholder="Font" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {FONT_FAMILIES.map((fontFamily) => (\n <SelectItem key={fontFamily} value={fontFamily}>\n <span style={{ fontFamily }}>{fontFamily}</span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={String(Math.round(selectedRunStyle?.fontSizePt ?? 12))}\n onValueChange={(value) => {\n const nextSize = Number(value)\n if (Number.isFinite(nextSize)) {\n editor.setFontSize(nextSize)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[86px] min-w-[86px]"\n aria-label="Font size"\n >\n <SelectValue placeholder="Size" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {FONT_SIZE_OPTIONS.map((size) => (\n <SelectItem key={size} value={String(size)}>\n {size} pt\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={selectedLineSpacingValue}\n onValueChange={(value) => {\n const nextSpacing = Number(value)\n if (Number.isFinite(nextSpacing)) {\n setLineSpacing(nextSpacing)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[94px] min-w-[94px]"\n aria-label="Line spacing"\n >\n <SelectValue placeholder="Spacing" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {LINE_SPACING_OPTIONS.map((spacing) => (\n <SelectItem key={spacing} value={String(spacing)}>\n {spacing}x\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Bold"\n active={Boolean(selectedRunStyle?.bold)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleBold}\n >\n <HugeiconsIcon icon={TextBoldIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Italic"\n active={Boolean(selectedRunStyle?.italic)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleItalic}\n >\n <HugeiconsIcon icon={TextItalicIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Underline"\n active={Boolean(selectedRunStyle?.underline)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleUnderline}\n >\n <HugeiconsIcon icon={TextUnderlineIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Strikethrough"\n active={Boolean(selectedRunStyle?.strike)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleStrike}\n >\n <HugeiconsIcon icon={TextStrikethroughIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Superscript"\n active={selectedRunStyle?.verticalAlign === "superscript"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleSuperscript}\n >\n <HugeiconsIcon icon={TextSuperscriptIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Subscript"\n active={selectedRunStyle?.verticalAlign === "subscript"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleSubscript}\n >\n <HugeiconsIcon icon={TextSubscriptIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarColorInput\n label="Text color"\n icon={TextColorIcon}\n color={textColorValue}\n disabled={!canEdit}\n onChange={(color) =>\n editor.setTextColor(normalizeHexColor(color))\n }\n />\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={!canEdit}\n aria-label="Highlight color"\n className="relative"\n >\n <HugeiconsIcon icon={HighlighterIcon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: highlightColor }}\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="z-[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 modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(zoomScale)}%</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="end"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarIconButton\n label="Zoom in"\n disabled={controlsDisabled || !canZoomIn}\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, 1)\n )\n }\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nexport function DocxEditorPreview({\n className,\n defaultIsDark = false,\n fileName,\n isDark: controlledIsDark,\n onIsDarkChange,\n rounded = false,\n src,\n}: {\n className?: string\n defaultIsDark?: boolean\n fileName?: string\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n rounded?: boolean\n src?: string\n}) {\n const [effectiveIsDark, setIsDark] = useControllableDarkMode({\n defaultIsDark,\n isDark: controlledIsDark,\n onIsDarkChange,\n })\n\n return (\n <DocxEditorContent\n className={className}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setIsDark={setIsDark}\n shouldRenderNightMode\n url={src}\n />\n )\n}\n\nfunction DocxEditorContent({\n className,\n effectiveIsDark,\n fileName,\n rounded,\n setIsDark,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n effectiveIsDark: boolean\n fileName?: string\n rounded: boolean\n setIsDark: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const imageInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [activePage, setActivePage] = React.useState(1)\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const [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 [reportedPageCount, setReportedPageCount] = React.useState(0)\n const thumbnailEditor = React.useMemo<DocxEditorController>(\n () => ({\n ...editor,\n totalPages: Math.max(editor.totalPages, reportedPageCount),\n }),\n [editor, editor.totalPages, reportedPageCount]\n )\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n []\n )\n const { thumbnails } = useDocxViewerThumbnails(\n thumbnailEditor,\n thumbnailOptions\n )\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <EditorLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const hasDocument = Boolean(url || uploadedDocxFile)\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, reportedPageCount || editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(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 setReportedPageCount(0)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n setReportedPageCount(0)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url\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 setReportedPageCount(0)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n async function handleImageUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n await editor.insertImageFile(file)\n }\n\n function openLinkEditor() {\n setLinkDraft(editor.selectedLink ?? "")\n setLinkEditorOpen(true)\n }\n\n function applyLink() {\n editor.setLink(linkDraft.trim() || undefined)\n setLinkEditorOpen(false)\n }\n\n return (\n <div\n className={cn(\n "flex h-[720px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n <input\n ref={imageInputRef}\n type="file"\n accept="image/*"\n className="hidden"\n onChange={handleImageUpload}\n />\n <DocxEditorToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n editor={editor}\n isReadOnly={isReadOnly}\n onImageUploadClick={() => imageInputRef.current?.click()}\n onIsDarkChange={setIsDark}\n onIsReadOnlyChange={setIsReadOnly}\n onOpenLinkEditor={openLinkEditor}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showNightRenderToggle={shouldRenderNightMode}\n zoomScale={zoomScale}\n />\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {linkEditorOpen ? (\n <div className="absolute top-3 left-1/2 z-50 flex w-[min(420px,calc(100%-2rem))] -translate-x-1/2 items-center gap-2 rounded-lg border bg-background p-2 shadow-lg">\n <Input\n value={linkDraft}\n onChange={(event) => setLinkDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === "Enter") {\n event.preventDefault()\n applyLink()\n }\n if (event.key === "Escape") {\n setLinkEditorOpen(false)\n }\n }}\n placeholder="https://example.com"\n aria-label="Link URL"\n />\n <Button type="button" size="sm" onClick={applyLink}>\n Apply\n </Button>\n <Button\n type="button"\n size="sm"\n variant="ghost"\n onClick={() => {\n editor.setLink(undefined)\n setLinkEditorOpen(false)\n }}\n >\n Clear\n </Button>\n </div>\n ) : null}\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}\n >\n <div className="h-full overflow-auto">\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </>\n ) : (\n <div className="flex flex-col items-center gap-3">\n {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (\n <Button\n key={thumbnail.pageIndex}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent text-foreground",\n thumbnail.pageNumber !== activePage &&\n "text-muted-foreground"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => scrollToPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n !thumbnail.isMounted &&\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n ))}\n </div>\n )}\n </div>\n </div>\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 onPageCountChange={handlePageCountChange}\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 03e3b08..ecaeb8a 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 type DocxEditorController,\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"\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 {\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 useControllableDarkMode({\n defaultIsDark = false,\n isDark,\n onIsDarkChange,\n}: {\n defaultIsDark?: boolean\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n}) {\n const [uncontrolledIsDark, setUncontrolledIsDark] =\n React.useState(defaultIsDark)\n const resolvedIsDark = isDark ?? uncontrolledIsDark\n\n const setIsDark = React.useCallback(\n (nextIsDark: boolean) => {\n if (isDark === undefined) {\n setUncontrolledIsDark(nextIsDark)\n }\n\n onIsDarkChange?.(nextIsDark)\n },\n [isDark, onIsDarkChange]\n )\n\n return [resolvedIsDark, setIsDark] as const\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 modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(zoomScale)}%</SelectValue>\n </SelectTrigger>\n <SelectContent align="end" alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled || !canZoomIn}\n aria-label="Zoom in"\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, 1)\n )\n }\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <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="rounded-md bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n renderDocumentPreview={false}\n isLoading={isLoading}\n hasError={hasError}\n className={cn(\n "w-[92px] rounded-md border-0 shadow-xs ring-0 transition-shadow duration-150",\n isActive && "shadow-sm"\n )}\n />\n )\n}\n\nexport function DocxViewerPreview({\n className,\n defaultThumbnailSidebarOpen = false,\n defaultIsDark = false,\n fileName,\n isDark: controlledIsDark,\n onIsDarkChange,\n rounded = false,\n src,\n}: {\n className?: string\n defaultThumbnailSidebarOpen?: boolean\n defaultIsDark?: boolean\n fileName?: string\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n rounded?: boolean\n src?: string\n}) {\n const [effectiveIsDark, setIsDark] = useControllableDarkMode({\n defaultIsDark,\n isDark: controlledIsDark,\n onIsDarkChange,\n })\n\n return (\n <DocxViewerContent\n className={className}\n defaultThumbnailSidebarOpen={defaultThumbnailSidebarOpen}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={setIsDark}\n 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 [reportedPageCount, setReportedPageCount] = React.useState(0)\n const thumbnailEditor = React.useMemo<DocxEditorController>(\n () => ({\n ...editor,\n totalPages: Math.max(editor.totalPages, reportedPageCount),\n }),\n [editor, editor.totalPages, reportedPageCount]\n )\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n []\n )\n const { thumbnails } = useDocxViewerThumbnails(\n thumbnailEditor,\n thumbnailOptions\n )\n const [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, reportedPageCount || editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n\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 setReportedPageCount(0)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n setReportedPageCount(0)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url\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 setReportedPageCount(0)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n <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 <div className="h-full overflow-auto">\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </>\n ) : (\n <div className="flex flex-col items-center gap-3">\n {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (\n <Button\n key={thumbnail.pageIndex}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent text-foreground",\n thumbnail.pageNumber !== activePage &&\n "text-muted-foreground"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => scrollToPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n !thumbnail.isMounted &&\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n ))}\n </div>\n )}\n </div>\n </div>\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 onPageCountChange={handlePageCountChange}\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 type DocxEditorController,\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"\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 {\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 useControllableDarkMode({\n defaultIsDark = false,\n isDark,\n onIsDarkChange,\n}: {\n defaultIsDark?: boolean\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n}) {\n const [uncontrolledIsDark, setUncontrolledIsDark] =\n React.useState(defaultIsDark)\n const resolvedIsDark = isDark ?? uncontrolledIsDark\n\n const setIsDark = React.useCallback(\n (nextIsDark: boolean) => {\n if (isDark === undefined) {\n setUncontrolledIsDark(nextIsDark)\n }\n\n onIsDarkChange?.(nextIsDark)\n },\n [isDark, onIsDarkChange]\n )\n\n return [resolvedIsDark, setIsDark] as const\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 modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(zoomScale)}%</SelectValue>\n </SelectTrigger>\n <SelectContent align="end" alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled || !canZoomIn}\n aria-label="Zoom in"\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, 1)\n )\n }\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <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="rounded-md bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n isLoading={isLoading}\n hasError={hasError}\n className={cn(\n "w-[92px] rounded-md border-0 shadow-xs ring-0 transition-shadow duration-150",\n isActive && "shadow-sm"\n )}\n />\n )\n}\n\nexport function DocxViewerPreview({\n className,\n defaultThumbnailSidebarOpen = false,\n defaultIsDark = false,\n fileName,\n isDark: controlledIsDark,\n onIsDarkChange,\n rounded = false,\n src,\n}: {\n className?: string\n defaultThumbnailSidebarOpen?: boolean\n defaultIsDark?: boolean\n fileName?: string\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n rounded?: boolean\n src?: string\n}) {\n const [effectiveIsDark, setIsDark] = useControllableDarkMode({\n defaultIsDark,\n isDark: controlledIsDark,\n onIsDarkChange,\n })\n\n return (\n <DocxViewerContent\n className={className}\n defaultThumbnailSidebarOpen={defaultThumbnailSidebarOpen}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={setIsDark}\n 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 [reportedPageCount, setReportedPageCount] = React.useState(0)\n const thumbnailEditor = React.useMemo<DocxEditorController>(\n () => ({\n ...editor,\n totalPages: Math.max(editor.totalPages, reportedPageCount),\n }),\n [editor, editor.totalPages, reportedPageCount]\n )\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n []\n )\n const { thumbnails } = useDocxViewerThumbnails(\n thumbnailEditor,\n thumbnailOptions\n )\n const [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, reportedPageCount || editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n\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 setReportedPageCount(0)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n setReportedPageCount(0)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url\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 setReportedPageCount(0)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n <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 <div className="h-full overflow-auto">\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </>\n ) : (\n <div className="flex flex-col items-center gap-3">\n {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (\n <Button\n key={thumbnail.pageIndex}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent text-foreground",\n thumbnail.pageNumber !== activePage &&\n "text-muted-foreground"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => scrollToPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n !thumbnail.isMounted &&\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n ))}\n </div>\n )}\n </div>\n </div>\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 onPageCountChange={handlePageCountChange}\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 abdf802..5c849ae 100644--- a/apps/v4/components/file-thumbnail-docs.tsx+++ b/apps/v4/components/file-thumbnail-docs.tsx@@ -1,6 +1,18 @@"use client"import * as React from "react"+import {+ DocxEditorViewer,+ useDocxEditor,+ useDocxViewerThumbnails,+ type DocxEditorController,+} from "@extend-ai/react-docx"+import {+ useXlsxViewerController,+ useXlsxViewerThumbnails,+ XlsxViewerProvider,+} from "@extend-ai/react-xlsx"+import type * as ReactPdf from "react-pdf"import { Button } from "@/components/ui/button"import {@@ -9,98 +21,500 @@ import {} from "@/components/ui/file-thumbnail"import { HighlightedCodeBlock } from "@/components/highlighted-code-block"-export type DemoFile = ThumbnailFile & {+const DOCX_MIME_TYPE =+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document"+const XLSX_MIME_TYPE =+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"+const DOCX_THUMBNAIL_WIDTH = 240+const XLSX_THUMBNAIL_WIDTH = 520++type ReactPdfModule = typeof ReactPdf++type DemoFileKind = "image" | "pdf" | "docx" | "xlsx"++type DemoFile = ThumbnailFile & {+ description: string+ kind: DemoFileKindurl: string}+type DocxThumbnailRenderState = {+ aspectRatio: number+ isMounted: boolean+ pixelHeightPx: number+ pixelWidthPx: number+ status: string+}+export const SAMPLE_FILES: DemoFile[] = [+ {+ name: "invoice-preview.png",+ type: "image/png",+ description: "Image",+ kind: "image",+ url: "/opengraph-image.png",+ },{name: "attention.pdf",type: "application/pdf",+ description: "PDF",+ kind: "pdf",url: "/samples/attention.pdf",},{name: "demo.docx",- type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ type: DOCX_MIME_TYPE,+ description: "DOCX",+ kind: "docx",url: "/samples/demo.docx",},{name: "crazy-chart-zoo.xlsx",- type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ type: XLSX_MIME_TYPE,+ description: "XLSX",+ kind: "xlsx",url: "/samples/crazy-chart-zoo.xlsx",},- {- name: "opengraph-image.png",- type: "image/png",- url: "/opengraph-image.png",- },]-function isPdfFile(file: DemoFile) {+function getPdfWorkerUrl(pdfjsVersion: string) {+ return `//unpkg.com/pdfjs-dist@${pdfjsVersion}/legacy/build/pdf.worker.min.mjs`+}++async function fetchFile(file: DemoFile) {+ const response = await fetch(file.url)++ if (!response.ok) {+ throw new Error(`Failed to fetch ${file.name} (${response.status})`)+ }++ const blob = await response.blob()++ return new File([blob], file.name, {+ type: blob.type || file.type,+ })+}++export function getFileKindLabel(file: ThumbnailFile) {+ if (file.type.startsWith("image/")) return "Image"+ if (file.type === "application/pdf") return "PDF"+ if (file.name.endsWith(".docx")) return "DOCX"+ if (file.name.endsWith(".xlsx")) return "XLSX"++ return "File"+}++function ImageThumbnailPreview({+ file,+ previewAspectRatio,+}: {+ file: DemoFile+ previewAspectRatio?: number+}) {return (- file.type === "application/pdf" || file.name.toLowerCase().endsWith(".pdf")+ <FileThumbnail+ file={file}+ previewImageUrl={file.url}+ previewAspectRatio={previewAspectRatio}+ previewClassName="bg-background"+ />)}-function isImageFile(file: DemoFile) {- return file.type.startsWith("image/")+function PdfThumbnailPreview({+ file,+ previewAspectRatio,+}: {+ file: DemoFile+ previewAspectRatio?: number+}) {+ const [reactPdf, setReactPdf] = React.useState<ReactPdfModule | null>(null)+ const [isReady, setIsReady] = React.useState(false)+ const [hasError, setHasError] = React.useState(false)++ React.useEffect(() => {+ let isMounted = true++ void import("react-pdf")+ .then((module) => {+ module.pdfjs.GlobalWorkerOptions.workerSrc = getPdfWorkerUrl(+ module.pdfjs.version+ )++ if (isMounted) {+ setReactPdf(module)+ }+ })+ .catch(() => {+ if (isMounted) {+ setHasError(true)+ }+ })++ return () => {+ isMounted = false+ }+ }, [])++ return (+ <FileThumbnail+ file={file}+ previewAspectRatio={previewAspectRatio ?? 0.77}+ previewClassName="bg-white"+ previewContent={+ reactPdf && !hasError ? (+ <reactPdf.Document+ file={file.url}+ loading={null}+ error={null}+ onLoadError={() => setHasError(true)}+ >+ <reactPdf.Thumbnail+ pageNumber={1}+ width={DOCX_THUMBNAIL_WIDTH}+ loading={null}+ error={null}+ onRenderSuccess={() => setIsReady(true)}+ onRenderError={() => setHasError(true)}+ className="flex size-full items-center justify-center [&_.react-pdf__Thumbnail__page]:!m-0 [&_.react-pdf__Thumbnail__page]:!h-auto [&_.react-pdf__Thumbnail__page]:!w-full [&_.react-pdf__Thumbnail__page]:overflow-hidden [&_canvas]:!h-auto [&_canvas]:!w-full"+ />+ </reactPdf.Document>+ ) : null+ }+ isLoading={!isReady && !hasError}+ hasError={hasError}+ />+ )}-function isDocxFile(file: DemoFile) {+function DocxThumbnailPreview({+ file,+ previewAspectRatio,+}: {+ file: DemoFile+ previewAspectRatio?: number+}) {+ const editor = useDocxEditor({+ initialDocumentTheme: "light",+ initialFileName: file.name,+ })+ const { importDocxFile } = editor+ const [isLoading, setIsLoading] = React.useState(true)+ const [hasError, setHasError] = React.useState(false)+ const thumbnailEditor = React.useMemo<DocxEditorController>(+ () => ({+ ...editor,+ totalPages: Math.max(editor.totalPages, 1),+ }),+ [editor]+ )+ const { thumbnails } = useDocxViewerThumbnails(+ thumbnailEditor,+ React.useMemo(+ () => ({+ pixelRatio: 2,+ resolution: {+ maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,+ maxWidth: DOCX_THUMBNAIL_WIDTH,+ },+ }),+ []+ )+ )+ const firstThumbnail = thumbnails[0]+ const docxCanvasRef =+ React.useRef<React.RefCallback<HTMLCanvasElement> | null>(null)+ const [thumbnailRenderState, setThumbnailRenderState] =+ React.useState<DocxThumbnailRenderState | null>(null)+ const attachDocxThumbnailCanvas = React.useCallback(+ (canvas: HTMLCanvasElement | null) => {+ docxCanvasRef.current?.(canvas)+ },+ []+ )++ React.useEffect(() => {+ let isCurrent = true++ setIsLoading(true)+ setHasError(false)++ void fetchFile(file)+ .then((docxFile) => importDocxFile(docxFile))+ .then(() => {+ if (isCurrent) {+ setIsLoading(false)+ }+ })+ .catch(() => {+ if (isCurrent) {+ setIsLoading(false)+ setHasError(true)+ }+ })++ return () => {+ isCurrent = false+ }+ }, [file, importDocxFile])++ React.useEffect(() => {+ if (!firstThumbnail) {+ docxCanvasRef.current = null+ setThumbnailRenderState(null)+ return+ }++ docxCanvasRef.current = firstThumbnail.canvasRef+ setThumbnailRenderState({+ aspectRatio: firstThumbnail.aspectRatio,+ isMounted: firstThumbnail.isMounted,+ pixelHeightPx: firstThumbnail.pixelHeightPx,+ pixelWidthPx: firstThumbnail.pixelWidthPx,+ status: firstThumbnail.status,+ })+ }, [firstThumbnail])++ const thumbnailIsLoading =+ isLoading ||+ (!thumbnailRenderState && !hasError) ||+ Boolean(+ thumbnailRenderState &&+ !thumbnailRenderState.isMounted &&+ thumbnailRenderState.status !== "ready" &&+ thumbnailRenderState.status !== "error"+ )+ const thumbnailHasError = hasError || thumbnailRenderState?.status === "error"+return (- file.type ===- "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||- file.name.toLowerCase().endsWith(".docx")+ <>+ <FileThumbnail+ file={file}+ previewAspectRatio={+ previewAspectRatio ?? thumbnailRenderState?.aspectRatio ?? 0.77+ }+ previewClassName="bg-white"+ previewContent={+ thumbnailRenderState ? (+ <canvas+ ref={attachDocxThumbnailCanvas}+ width={thumbnailRenderState.pixelWidthPx}+ height={thumbnailRenderState.pixelHeightPx}+ className="!size-full bg-white object-cover object-top"+ />+ ) : null+ }+ isLoading={thumbnailIsLoading}+ hasError={thumbnailHasError}+ />+ {!thumbnailHasError ? (+ <div+ aria-hidden="true"+ className="pointer-events-none fixed top-0 left-0 -z-10 h-[1056px] w-[816px] overflow-hidden bg-white opacity-0 [contain:layout_paint]"+ >+ <div className="w-[816px]">+ <DocxEditorViewer+ editor={editor}+ mode="read-only"+ pageBackgroundColor="#ffffff"+ pageGapBackgroundColor="transparent"+ visiblePageRange={{ endPageIndex: 0, startPageIndex: 0 }}+ pageVirtualization={{ enabled: false }}+ deferInitialPaginationPaint={false}+ />+ </div>+ </div>+ ) : null}+ </>)}-function isXlsxFile(file: DemoFile) {- const fileName = file.name.toLowerCase()+function XlsxThumbnailPreview({+ file,+ previewAspectRatio,+}: {+ file: DemoFile+ previewAspectRatio?: number+}) {+ const [workbookBuffer, setWorkbookBuffer] =+ React.useState<ArrayBuffer | null>(null)+ const [imageUrl, setImageUrl] = React.useState<string | null>(null)+ const [hasError, setHasError] = React.useState(false)++ React.useEffect(() => {+ let isCurrent = true++ setWorkbookBuffer(null)+ setImageUrl(null)+ setHasError(false)++ void fetch(file.url)+ .then(async (response) => {+ if (!response.ok) {+ throw new Error(`Failed to fetch ${file.name} (${response.status})`)+ }++ return response.arrayBuffer()+ })+ .then((buffer) => {+ if (isCurrent) {+ setWorkbookBuffer(buffer)+ }+ })+ .catch(() => {+ if (isCurrent) {+ setHasError(true)+ }+ })++ return () => {+ isCurrent = false+ }+ }, [file])return (- file.type ===- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||- file.type === "application/vnd.ms-excel" ||- fileName.endsWith(".xlsx") ||- fileName.endsWith(".xls")+ <>+ <FileThumbnail+ file={file}+ previewAspectRatio={previewAspectRatio ?? 11 / 7}+ previewClassName="bg-white [&>img]:object-left-top"+ previewImageUrl={imageUrl}+ isLoading={!imageUrl && !hasError}+ hasError={hasError}+ />+ {workbookBuffer && !imageUrl && !hasError ? (+ <XlsxThumbnailGenerator+ file={file}+ workbookBuffer={workbookBuffer}+ onError={() => setHasError(true)}+ onImageUrl={setImageUrl}+ />+ ) : null}+ </>)}-export function getFileKindLabel(file: DemoFile) {- if (isPdfFile(file)) return "PDF"- if (isImageFile(file)) return "Image"- if (isDocxFile(file)) return "DOCX"- if (isXlsxFile(file)) return "XLSX"+function XlsxThumbnailGenerator({+ file,+ onError,+ onImageUrl,+ workbookBuffer,+}: {+ file: DemoFile+ onError: () => void+ onImageUrl: (url: string) => void+ workbookBuffer: ArrayBuffer+}) {+ const controller = useXlsxViewerController(+ React.useMemo(+ () => ({+ file: workbookBuffer,+ fileName: file.name,+ readOnly: true,+ useWorker: true,+ }),+ [file.name, workbookBuffer]+ )+ )- return "File"+ return (+ <XlsxViewerProvider controller={controller}>+ <XlsxThumbnailCapture onError={onError} onImageUrl={onImageUrl} />+ </XlsxViewerProvider>+ )}-function getThumbnailFile(file: DemoFile): ThumbnailFile {- return {- name: file.name,- type: file.type,- url: file.url,- }+function XlsxThumbnailCapture({+ onError,+ onImageUrl,+}: {+ onError: () => void+ onImageUrl: (url: string) => void+}) {+ const { thumbnails } = useXlsxViewerThumbnails(+ React.useMemo(+ () => ({+ includeHeaders: true,+ resolution: {+ maxHeight: XLSX_THUMBNAIL_WIDTH,+ maxWidth: XLSX_THUMBNAIL_WIDTH,+ },+ }),+ []+ )+ )+ const firstThumbnail = thumbnails[0]++ React.useEffect(() => {+ if (!firstThumbnail) return++ const canvas = document.createElement("canvas")++ canvas.width = firstThumbnail.width+ canvas.height = firstThumbnail.height++ if (!firstThumbnail.paint(canvas)) {+ onError()+ return+ }++ onImageUrl(canvas.toDataURL("image/png"))+ }, [firstThumbnail, onError, onImageUrl])++ return null+}++function FileThumbnailExample({+ className,+ file,+ previewAspectRatio,+}: {+ className?: string+ file: DemoFile+ previewAspectRatio?: number+}) {+ return (+ <div className={className}>+ {file.kind === "image" ? (+ <ImageThumbnailPreview+ file={file}+ previewAspectRatio={previewAspectRatio}+ />+ ) : null}+ {file.kind === "pdf" ? (+ <PdfThumbnailPreview+ file={file}+ previewAspectRatio={previewAspectRatio}+ />+ ) : null}+ {file.kind === "docx" ? (+ <DocxThumbnailPreview+ file={file}+ previewAspectRatio={previewAspectRatio}+ />+ ) : null}+ {file.kind === "xlsx" ? (+ <XlsxThumbnailPreview+ file={file}+ previewAspectRatio={previewAspectRatio}+ />+ ) : null}+ </div>+ )}export function DocumentAwareFileThumbnail({file,className,- generationDelayMs = 0,- thumbnailWidth,}: {file: DemoFileclassName?: string- generationDelayMs?: number- thumbnailWidth?: number}) {return (- <FileThumbnail- file={getThumbnailFile(file)}- source={file.url}- generationDelayMs={generationDelayMs}- thumbnailWidth={thumbnailWidth ?? (isXlsxFile(file) ? 680 : 520)}+ <FileThumbnailExample+ file={file}className={className}+ previewAspectRatio={1}/>)}@@ -115,12 +529,9 @@ export function FileThumbnailDemo() {><div className="grid gap-6 bg-background p-6 sm:grid-cols-2 lg:grid-cols-4">{SAMPLE_FILES.map((file) => (- <div key={file.url} className="space-y-2">- <div className="text-sm font-medium">{getFileKindLabel(file)}</div>- <DocumentAwareFileThumbnail- file={file}- generationDelayMs={250 + SAMPLE_FILES.indexOf(file) * 300}- />+ <div key={file.name} className="space-y-2">+ <div className="text-sm font-medium">{file.description}</div>+ <FileThumbnailExample file={file} previewAspectRatio={1} /></div>))}</div>@@ -171,68 +582,289 @@ export function FileThumbnailDemo() {const fileThumbnailDemoCode = `"use client"import * as React from "react"-import {- FileThumbnail,- type ThumbnailFile,-} from "@/components/ui/file-thumbnail"+ DocxEditorViewer,+ useDocxEditor,+ useDocxViewerThumbnails,+} from "@extend-ai/react-docx"+import {+ useXlsxViewerController,+ useXlsxViewerThumbnails,+ XlsxViewerProvider,+} from "@extend-ai/react-xlsx"-type DemoFile = ThumbnailFile & {- url: string+import { FileThumbnail } from "@/components/ui/file-thumbnail"++export function PdfAttachmentThumbnail({ reactPdf, fileUrl }) {+ return (+ <FileThumbnail+ file={{ name: "contract.pdf", type: "application/pdf" }}+ previewAspectRatio={0.77}+ previewClassName="bg-white"+ previewContent={+ <reactPdf.Document file={fileUrl} loading={null} error={null}>+ <reactPdf.Thumbnail pageNumber={1} width={240} />+ </reactPdf.Document>+ }+ />+ )}-const SAMPLE_FILES: DemoFile[] = [- {- name: "attention.pdf",- type: "application/pdf",- url: "/samples/attention.pdf",- },- {- name: "demo.docx",- type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",- url: "/samples/demo.docx",- },- {- name: "crazy-chart-zoo.xlsx",- type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",- url: "/samples/crazy-chart-zoo.xlsx",- },- {- name: "opengraph-image.png",- type: "image/png",- url: "/opengraph-image.png",- },-]+export function DocxAttachmentThumbnail({ file }) {+ const editor = useDocxEditor({ initialFileName: file.name })+ const { thumbnails } = useDocxViewerThumbnails(editor, {+ pixelRatio: 2,+ resolution: { maxHeight: 324, maxWidth: 240 },+ })+ const firstThumbnail = thumbnails[0]-function toThumbnailFile(file: DemoFile): ThumbnailFile {- return {- name: file.name,- type: file.type,- }+ React.useEffect(() => {+ void editor.importDocxFile(file)+ }, [editor, file])++ return (+ <>+ <FileThumbnail+ file={file}+ previewAspectRatio={firstThumbnail?.aspectRatio ?? 0.77}+ previewClassName="bg-white"+ previewContent={+ firstThumbnail ? (+ <canvas+ ref={firstThumbnail.canvasRef}+ width={firstThumbnail.pixelWidthPx}+ height={firstThumbnail.pixelHeightPx}+ className="!size-full bg-white object-cover object-top"+ />+ ) : null+ }+ isLoading={!firstThumbnail}+ />+ <div className="pointer-events-none fixed -z-10 opacity-0">+ <DocxEditorViewer editor={editor} mode="read-only" />+ </div>+ </>+ )+}++export function XlsxAttachmentThumbnail({ workbookBuffer }) {+ const [imageUrl, setImageUrl] = React.useState(null)+ const controller = useXlsxViewerController({+ file: workbookBuffer,+ fileName: "workbook.xlsx",+ readOnly: true,+ useWorker: true,+ })++ return (+ <XlsxViewerProvider controller={controller}>+ <XlsxThumbnailCapture onImageUrl={setImageUrl} />+ <FileThumbnail+ file={{ name: "workbook.xlsx", type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }}+ previewAspectRatio={11 / 7}+ previewClassName="bg-white [&>img]:object-left-top"+ previewImageUrl={imageUrl}+ isLoading={!imageUrl}+ />+ </XlsxViewerProvider>+ )}-function getThumbnailWidth(file: DemoFile) {- return file.name.toLowerCase().endsWith(".xlsx") ? 680 : 520+function XlsxThumbnailCapture({ onImageUrl }) {+ const { thumbnails } = useXlsxViewerThumbnails({+ includeHeaders: true,+ resolution: { maxHeight: 520, maxWidth: 520 },+ })++ React.useEffect(() => {+ const thumbnail = thumbnails[0]+ if (!thumbnail) return++ const canvas = document.createElement("canvas")+ canvas.width = thumbnail.width+ canvas.height = thumbnail.height+ if (thumbnail.paint(canvas)) {+ onImageUrl(canvas.toDataURL("image/png"))+ }+ }, [onImageUrl, thumbnails])++ return null+}`++const fileThumbnailSourceCode = `"use client"++import * as React from "react"++export type ThumbnailFile = {+ name: string+ type: string}-export function FileThumbnailGrid() {+export type FileThumbnailProps = {+ file: ThumbnailFile | File+ className?: string+ previewAspectRatio?: number+ previewClassName?: string+ previewContent?: React.ReactNode+ previewImageUrl?: string | null+ isLoading?: boolean+ hasError?: boolean+}++function cx(...classes: Array<string | false | null | undefined>) {+ return classes.filter(Boolean).join(" ")+}++export function FileThumbnailLoadingOverlay() {return (- <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">- {SAMPLE_FILES.map((file, index) => (- <FileThumbnail- key={file.url}- file={toThumbnailFile(file)}- source={file.url}- generationDelayMs={250 + index * 300}- thumbnailWidth={getThumbnailWidth(file)}- />- ))}+ <div+ aria-hidden="true"+ className="absolute inset-0 z-10 overflow-hidden bg-muted"+ >+ <div className="absolute inset-0 bg-muted" />+ <div className="absolute inset-0 animate-pulse bg-background/55 motion-reduce:animate-none" /></div>)-}`+}-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 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}\n\ntype NormalizedThumbnailFile = {\n name: string\n type: string\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 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 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\nfunction canvasHasVisiblePixels(canvas: HTMLCanvasElement) {\n const context = canvas.getContext("2d")\n if (!context || canvas.width <= 0 || canvas.height <= 0) return false\n\n try {\n const { data } = context.getImageData(0, 0, canvas.width, canvas.height)\n\n for (let index = 3; index < data.length; index += 4) {\n if (data[index] > 0) return true\n }\n\n return false\n } catch {\n return true\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 hiddenPreviewRenderer,\n isLoading = false,\n hasError = false,\n}: {\n file: NormalizedThumbnailFile\n className?: string\n previewAspectRatio?: number\n previewClassName?: string\n previewContent?: React.ReactNode\n previewImageUrl?: string | null\n hiddenPreviewRenderer?: React.ReactNode\n isLoading?: boolean\n hasError?: boolean\n}) {\n const imageRef = React.useRef<HTMLImageElement | null>(null)\n const revealFrameRef = React.useRef<number | null>(null)\n const [loadedPreviewImageUrl, setLoadedPreviewImageUrl] = React.useState<\n string | null\n >(null)\n const [failedPreviewImageUrl, setFailedPreviewImageUrl] = React.useState<\n string | null\n >(null)\n const imageFailed = Boolean(\n previewImageUrl && failedPreviewImageUrl === previewImageUrl\n )\n const isImageLoading = Boolean(\n previewImageUrl && loadedPreviewImageUrl !== previewImageUrl && !imageFailed\n )\n const showLoading = isLoading || isImageLoading\n const hasPreviewContent = Boolean(previewContent)\n const showFallback =\n !showLoading &&\n (hasError || imageFailed || (!previewImageUrl && !hasPreviewContent))\n const cancelImageReveal = React.useCallback(() => {\n if (revealFrameRef.current === null) return\n\n window.cancelAnimationFrame(revealFrameRef.current)\n revealFrameRef.current = null\n }, [])\n const markImageLoaded = React.useCallback(\n (image: HTMLImageElement, imageUrl: string | null | undefined) => {\n if (!imageUrl) return\n\n const didLoad = image.naturalWidth > 0 && image.naturalHeight > 0\n\n setFailedPreviewImageUrl(didLoad ? null : imageUrl)\n if (didLoad) {\n cancelImageReveal()\n revealFrameRef.current = window.requestAnimationFrame(() => {\n revealFrameRef.current = window.requestAnimationFrame(() => {\n setLoadedPreviewImageUrl(imageUrl)\n revealFrameRef.current = null\n })\n })\n }\n },\n [cancelImageReveal]\n )\n\n React.useEffect(() => {\n cancelImageReveal()\n\n if (previewImageUrl) return\n\n setLoadedPreviewImageUrl(null)\n setFailedPreviewImageUrl(null)\n }, [cancelImageReveal, previewImageUrl])\n\n React.useEffect(() => cancelImageReveal, [cancelImageReveal])\n\n React.useEffect(() => {\n const image = imageRef.current\n\n if (!image || !previewImageUrl) return\n\n if (image.complete) {\n markImageLoaded(image, previewImageUrl)\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 [contain:layout_paint]",\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 "absolute inset-0 block size-full object-cover transition-[opacity,filter] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",\n showLoading ? "opacity-0 blur-sm" : "blur-0 opacity-100"\n )}\n onLoad={(event) => {\n markImageLoaded(event.currentTarget, previewImageUrl)\n }}\n onError={() => {\n if (previewImageUrl) {\n cancelImageReveal()\n setFailedPreviewImageUrl(previewImageUrl)\n setLoadedPreviewImageUrl((currentUrl) =>\n currentUrl === previewImageUrl ? null : currentUrl\n )\n }\n }}\n />\n ) : null}\n {previewContent ? (\n <div\n className={cn(\n "absolute inset-0 size-full transition-[opacity,filter] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",\n showLoading ? "opacity-0 blur-sm" : "blur-0 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 {hiddenPreviewRenderer}\n </div>\n )\n}\n\nfunction ImageFileThumbnail({\n className,\n file,\n hasError,\n isLoading,\n previewClassName,\n previewAspectRatio,\n source,\n}: {\n className?: string\n file: NormalizedThumbnailFile\n hasError?: boolean\n isLoading?: boolean\n previewAspectRatio?: number\n previewClassName?: string\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 />\n )\n}\n\nfunction PdfFileThumbnail({\n file,\n className,\n hasError: externalHasError,\n isActive,\n isLoading: externalIsLoading,\n previewClassName,\n previewAspectRatio,\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 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 <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 hiddenPreviewRenderer={\n shouldRenderPdf ? (\n <div\n ref={rootRef}\n aria-hidden="true"\n className="pointer-events-none fixed top-0 left-0 -z-10 w-[560px] overflow-hidden bg-white opacity-0 [contain:layout_paint]"\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}\n\nfunction DocxFileThumbnail({\n file,\n className,\n hasError: externalHasError,\n isActive,\n isLoading: externalIsLoading,\n previewClassName,\n previewAspectRatio,\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 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 if (canvas) firstThumbnail?.canvasRef(canvas)\n },\n [firstThumbnail]\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 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 checkThumbnail = () => {\n if (!isCurrent) return\n\n if (canvasHasVisiblePixels(thumbnailCanvas)) {\n setIsReady(true)\n return\n }\n\n if (!getRenderedPageSurface()) {\n attempts += 1\n\n if (attempts > 50) {\n setIsReady(true)\n return\n }\n\n timeoutId = window.setTimeout(checkThumbnail, 100)\n return\n }\n\n attempts += 1\n\n if (attempts > 50) {\n setIsReady(true)\n return\n }\n\n timeoutId = window.setTimeout(checkThumbnail, 100)\n }\n\n checkThumbnail()\n\n return () => {\n isCurrent = false\n if (timeoutId !== undefined) window.clearTimeout(timeoutId)\n }\n }, [\n firstThumbnail,\n firstThumbnail?.isMounted,\n hasError,\n isActive,\n isReady,\n thumbnailCanvas,\n ])\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 <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 hiddenPreviewRenderer={\n isActive && !hasError ? (\n <div\n ref={hiddenDocxViewerRef}\n aria-hidden="true"\n className="pointer-events-none fixed top-0 left-0 -z-10 h-[1056px] w-[816px] overflow-hidden bg-white opacity-0 [contain:layout_paint]"\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}\n\nfunction XlsxFileThumbnail({\n file,\n className,\n hasError: externalHasError,\n isActive,\n isLoading: externalIsLoading,\n previewClassName,\n previewAspectRatio,\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 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(externalIsLoading || (!imageUrl && !hasError))}\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 />\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 thumbnailOptions = React.useMemo(\n () => ({\n includeHeaders: true,\n resolution: {\n maxHeight: thumbnailWidth,\n maxWidth: thumbnailWidth,\n },\n }),\n [thumbnailWidth]\n )\n const { thumbnails } = useXlsxViewerThumbnails(thumbnailOptions)\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}: 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 />\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 />\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 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 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 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 />\n )\n}\n'+export function FileThumbnail({+ file: _file,+ className,+ previewAspectRatio,+ previewClassName,+ previewContent,+ previewImageUrl,+ isLoading = false,+ hasError = false,+}: FileThumbnailProps) {+ const imageRef = React.useRef<HTMLImageElement | null>(null)+ const revealFrameRef = React.useRef<number | null>(null)+ const [loadedPreviewImageUrl, setLoadedPreviewImageUrl] = React.useState<+ string | null+ >(null)+ const [failedPreviewImageUrl, setFailedPreviewImageUrl] = React.useState<+ string | null+ >(null)+ const imageFailed = Boolean(+ previewImageUrl && failedPreviewImageUrl === previewImageUrl+ )+ const isImageLoading = Boolean(+ previewImageUrl && loadedPreviewImageUrl !== previewImageUrl && !imageFailed+ )+ const showLoading = isLoading || isImageLoading+ const hasPreviewContent = Boolean(previewContent)+ const showFallback =+ !showLoading &&+ (hasError || imageFailed || (!previewImageUrl && !hasPreviewContent))+ const cancelImageReveal = React.useCallback(() => {+ if (revealFrameRef.current === null) return++ window.cancelAnimationFrame(revealFrameRef.current)+ revealFrameRef.current = null+ }, [])+ const markImageLoaded = React.useCallback(+ (image: HTMLImageElement, imageUrl: string | null | undefined) => {+ if (!imageUrl) return++ const didLoad = image.naturalWidth > 0 && image.naturalHeight > 0++ setFailedPreviewImageUrl(didLoad ? null : imageUrl)+ if (didLoad) {+ cancelImageReveal()+ revealFrameRef.current = window.requestAnimationFrame(() => {+ revealFrameRef.current = window.requestAnimationFrame(() => {+ setLoadedPreviewImageUrl(imageUrl)+ revealFrameRef.current = null+ })+ })+ }+ },+ [cancelImageReveal]+ )++ React.useEffect(() => {+ cancelImageReveal()++ if (previewImageUrl) return++ setLoadedPreviewImageUrl(null)+ setFailedPreviewImageUrl(null)+ }, [cancelImageReveal, previewImageUrl])++ React.useEffect(() => cancelImageReveal, [cancelImageReveal])++ React.useEffect(() => {+ const image = imageRef.current++ if (!image || !previewImageUrl) return++ if (image.complete) {+ markImageLoaded(image, previewImageUrl)+ }+ }, [markImageLoaded, previewImageUrl])++ return (+ <div+ className={cx(+ "group overflow-hidden rounded-lg border bg-background text-foreground",+ className+ )}+ >+ <div+ className={cx(+ "relative aspect-square overflow-hidden bg-muted [contain:layout_paint]",+ previewClassName+ )}+ style={+ previewAspectRatio+ ? { aspectRatio: String(previewAspectRatio) }+ : undefined+ }+ >+ {previewImageUrl ? (+ <img+ ref={imageRef}+ src={previewImageUrl}+ alt=""+ draggable={false}+ loading="lazy"+ decoding="async"+ className={cx(+ "absolute inset-0 block size-full object-cover transition-[opacity,filter] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",+ showLoading ? "opacity-0 blur-sm" : "blur-0 opacity-100"+ )}+ onLoad={(event) => {+ markImageLoaded(event.currentTarget, previewImageUrl)+ }}+ onError={() => {+ if (previewImageUrl) {+ cancelImageReveal()+ setFailedPreviewImageUrl(previewImageUrl)+ setLoadedPreviewImageUrl((currentUrl) =>+ currentUrl === previewImageUrl ? null : currentUrl+ )+ }+ }}+ />+ ) : null}+ {previewContent ? (+ <div+ className={cx(+ "absolute inset-0 size-full transition-[opacity,filter] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",+ showLoading ? "opacity-0 blur-sm" : "blur-0 opacity-100"+ )}+ >+ {previewContent}+ </div>+ ) : null}+ {showLoading ? <FileThumbnailLoadingOverlay /> : null}+ {showFallback ? (+ <div className="absolute inset-0 bg-muted" aria-hidden="true" />+ ) : null}+ </div>+ </div>+ )+}`export function FileThumbnailSource() {return <HighlightedCodeBlock code={fileThumbnailSourceCode} />diff --git a/apps/v4/components/ocr-blocks-docs.tsx b/apps/v4/components/ocr-blocks-docs.tsxindex 4547464..e946342 100644--- a/apps/v4/components/ocr-blocks-docs.tsx+++ b/apps/v4/components/ocr-blocks-docs.tsx@@ -92,6 +92,7 @@ type HighlightArea = {const PDF_URL = "/samples/attention-rotated.pdf"const DEFAULT_ZOOM = 0.75+const ROOT_OCR_PREVIEW_PAGE = 1const OCR_BLOCK_ROW_ESTIMATE = 132const OCR_BLOCK_LIST_PADDING = 12const OCR_MARKDOWN_SCHEMA = {@@ -8367,7 +8368,13 @@ function OcrBlockButton({}export function OcrBlocks() {- return <OcrBlocksPanel blocks={getOcrBlocks(ATTENTION_OCR_OUTPUT)} />+ return (+ <OcrBlocksPanel+ blocks={getOcrBlocks(ATTENTION_OCR_OUTPUT).filter(+ (block) => block.page === ROOT_OCR_PREVIEW_PAGE+ )}+ />+ )}export function OcrBlocksBlock({diff --git a/apps/v4/components/pdf-viewer-docs.tsx b/apps/v4/components/pdf-viewer-docs.tsxindex 90ae999..82ff3a1 100644--- a/apps/v4/components/pdf-viewer-docs.tsx+++ b/apps/v4/components/pdf-viewer-docs.tsx@@ -182,7 +182,7 @@ export function PdfViewerExample() {}`const pdfViewerSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n Download01Icon,\n MinusSignCircleIcon,\n PlusSignCircleIcon,\n RotateClockwiseIcon,\n Search01Icon,\n SidebarLeftIcon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport type { PDFDocumentProxy } from "pdfjs-dist"\nimport type * as ReactPdf from "react-pdf"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DocumentViewerSidebarSkeleton,\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/ui/document-viewer-sidebar"\nimport { 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 { Input } from "@/registry/new-york-v4/ui/input"\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from "@/registry/new-york-v4/ui/popover"\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\ntype ReactPdfModule = typeof ReactPdf\ntype PageRotationDeltas = Map<number, number>\n\ntype PDFPageMetrics = {\n width: number\n height: number\n rotation: number\n}\n\nexport type PDFViewerPageOverlayProps = {\n pageNumber: number\n pageWidth: number\n pageHeight: number\n scale: number\n rotation: number\n}\n\nexport type PDFViewerHandle = {\n scrollToPage: (pageNumber: number, options?: ScrollIntoViewOptions) => void\n scrollToPageArea: (\n pageNumber: number,\n area: { top: number; left?: number; width?: number; height?: number },\n options?: ScrollToOptions\n ) => void\n getViewportElement: () => HTMLDivElement | null\n}\n\nexport type PDFViewerProps = {\n file?: string\n className?: string\n defaultThumbnailSidebarOpen?: boolean\n defaultZoom?: number\n pageWidth?: number\n pageHeight?: number\n pageNumbers?: number[]\n pageRenderBuffer?: number\n downloadFileName?: string\n showDownload?: boolean\n showRotateControls?: boolean\n showUpload?: boolean\n toolbarActions?: React.ReactNode\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onActivePageChange?: (pageNumber: number) => void\n onDocumentLoadSuccess?: (numPages: number) => void\n onPdfUpload?: (file: File) => void\n onPagePointerDown?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerMove?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerUp?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerCancel?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n}\n\nconst DEFAULT_PAGE_WIDTH = 612\nconst DEFAULT_PAGE_HEIGHT = 792\nconst DEFAULT_ZOOM = 0.75\nconst ZOOM_OPTIONS = [0.5, 0.75, 1, 1.25, 1.5, 2]\nconst MAX_DEVICE_PIXEL_RATIO = 2\nconst DEFAULT_PAGE_RENDER_BUFFER = 4\nconst THUMBNAIL_WIDTH = 92\ntype SearchHighlight = {\n id: string\n left: number\n top: number\n width: number\n height: number\n}\n\nfunction getPdfWorkerUrl(pdfjsVersion: string) {\n return `//unpkg.com/pdfjs-dist@${pdfjsVersion}/legacy/build/pdf.worker.min.mjs`\n}\n\nfunction normalizeRotation(rotation: number) {\n return (((Math.round(rotation / 90) * 90) % 360) + 360) % 360\n}\n\nfunction isQuarterTurn(rotation: number) {\n return Math.abs(normalizeRotation(rotation) / 90) % 2 === 1\n}\n\nfunction getPageDimensions(metrics: PDFPageMetrics, rotation: number) {\n return isQuarterTurn(rotation)\n ? { width: metrics.height, height: metrics.width }\n : { width: metrics.width, height: metrics.height }\n}\n\nfunction ensurePdfExtension(fileName: string) {\n return fileName.toLowerCase().endsWith(".pdf") ? fileName : `${fileName}.pdf`\n}\n\nfunction getPdfDownloadFileName(fileName: string | undefined, file: string) {\n if (fileName?.trim()) return ensurePdfExtension(fileName.trim())\n\n const pathname = file.split(/[?#]/)[0] ?? ""\n const rawName = pathname.split("/").pop() || "document.pdf"\n\n try {\n return ensurePdfExtension(decodeURIComponent(rawName))\n } catch {\n return ensurePdfExtension(rawName)\n }\n}\n\nfunction getRotatedPdfDownloadFileName(fileName: string) {\n return fileName.replace(/\\.pdf$/i, "-rotated.pdf")\n}\n\nfunction downloadBlob(blob: Blob, fileName: string) {\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n\n anchor.href = url\n anchor.download = fileName\n anchor.rel = "noopener"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nasync function getDocumentPageMetrics(pdf: PDFDocumentProxy) {\n const pageEntries = await Promise.all(\n Array.from({ length: pdf.numPages }, async (_, index) => {\n const pageNumber = index + 1\n const page = await pdf.getPage(pageNumber)\n const viewport = page.getViewport({ scale: 1, rotation: 0 })\n\n return [\n pageNumber,\n {\n width: viewport.width,\n height: viewport.height,\n rotation: normalizeRotation(page.rotate),\n },\n ] as const\n })\n )\n\n return new Map<number, PDFPageMetrics>(pageEntries)\n}\n\nasync function downloadPdfWithPageRotations({\n file,\n fileName,\n pageRotationDeltas,\n}: {\n file: string\n fileName: string\n pageRotationDeltas: PageRotationDeltas\n}) {\n const response = await fetch(file)\n\n if (!response.ok) {\n throw new Error(`Failed to download PDF (${response.status})`)\n }\n\n const [{ PDFDocument, degrees }, pdfBytes] = await Promise.all([\n import("pdf-lib"),\n response.arrayBuffer(),\n ])\n const pdfDocument = await PDFDocument.load(pdfBytes)\n\n pdfDocument.getPages().forEach((page, index) => {\n const pageNumber = index + 1\n const rotationDelta = pageRotationDeltas.get(pageNumber) ?? 0\n\n if (!rotationDelta) return\n\n page.setRotation(\n degrees(normalizeRotation(page.getRotation().angle + rotationDelta))\n )\n })\n\n const nextPdfBytes = await pdfDocument.save()\n const nextPdfBuffer = new ArrayBuffer(nextPdfBytes.byteLength)\n new Uint8Array(nextPdfBuffer).set(nextPdfBytes)\n const hasPageRotationChanges = pageRotationDeltas.size > 0\n\n downloadBlob(\n new Blob([nextPdfBuffer], { type: "application/pdf" }),\n hasPageRotationChanges ? getRotatedPdfDownloadFileName(fileName) : fileName\n )\n}\n\nfunction PDFViewerLoadingSkeleton({\n sidebarOpen,\n sidebarInline,\n}: {\n sidebarOpen: boolean\n sidebarInline: boolean\n}) {\n return (\n <div className="absolute inset-0 z-20 flex bg-muted/30">\n {sidebarOpen ? (\n <DocumentViewerSidebarSkeleton inline={sidebarInline} />\n ) : null}\n <div className="grid min-w-0 flex-1 place-items-center">\n <Spinner className="size-4" />\n </div>\n </div>\n )\n}\n\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 SearchInput({\n value,\n onValueChange,\n onApply,\n onClear,\n}: {\n value: string\n onValueChange: (value: string) => void\n onApply: () => void\n onClear: () => void\n}) {\n return (\n <div className="space-y-3">\n <Input\n placeholder="Search text"\n value={value}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) =>\n onValueChange(event.target.value)\n }\n onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key === "Enter") {\n onApply()\n }\n }}\n />\n <div className="flex justify-end gap-2">\n <Button type="button" variant="outline" size="sm" onClick={onClear}>\n Clear\n </Button>\n <Button type="button" size="sm" onClick={onApply}>\n Search\n </Button>\n </div>\n </div>\n )\n}\n\nfunction PDFSidebarThumbnail({\n file,\n pageMetrics,\n pageNumber,\n reactPdf,\n rotation,\n thumbnailAspectRatio,\n}: {\n file: string\n pageMetrics: PDFPageMetrics\n pageNumber: number\n reactPdf: ReactPdfModule\n rotation: number\n thumbnailAspectRatio: number\n}) {\n const effectiveRotation = normalizeRotation(pageMetrics.rotation + rotation)\n\n return (\n <FileThumbnail\n file={{\n name: `Page ${pageNumber}.pdf`,\n type: "application/pdf",\n source: file,\n }}\n previewAspectRatio={thumbnailAspectRatio}\n previewClassName="rounded-md bg-white"\n previewContent={\n <reactPdf.Thumbnail\n pageNumber={pageNumber}\n width={THUMBNAIL_WIDTH}\n rotate={effectiveRotation}\n className="flex size-full items-center justify-center [&_.react-pdf__Thumbnail__page]:!m-0 [&_.react-pdf__Thumbnail__page]:!h-auto [&_.react-pdf__Thumbnail__page]:!w-full [&_.react-pdf__Thumbnail__page]:overflow-hidden [&_canvas]:!h-auto [&_canvas]:!w-full"\n />\n }\n renderDocumentPreview={false}\n className="w-[92px] rounded-md border-0 shadow-xs ring-0"\n />\n )\n}\n\nfunction PDFViewerPage({\n effectiveRotation,\n reactPdf,\n pageNumber,\n pageStyle,\n renderedPageWidth,\n zoom,\n shouldRenderPage,\n searchQuery,\n pageClassName,\n renderPageOverlay,\n onPageSettled,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n}: {\n effectiveRotation: number\n reactPdf: ReactPdfModule\n pageNumber: number\n pageStyle: React.CSSProperties & { width: number; height: number }\n renderedPageWidth: number\n zoom: number\n shouldRenderPage: boolean\n searchQuery: string\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onPageSettled: (pageNumber: number) => void\n onPagePointerDown?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerMove?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerUp?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerCancel?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n}) {\n const pageRef = React.useRef<HTMLDivElement>(null)\n const [searchHighlights, setSearchHighlights] = React.useState<\n SearchHighlight[]\n >([])\n const hasSearchQuery = Boolean(searchQuery.trim())\n\n const updateSearchHighlights = React.useCallback(() => {\n const pageElement = pageRef.current\n const query = searchQuery.trim().toLowerCase()\n\n if (!pageElement || !query) {\n setSearchHighlights([])\n return\n }\n\n const textLayer = pageElement.querySelector<HTMLElement>(\n ".react-pdf__Page__textContent"\n )\n\n if (!textLayer) {\n setSearchHighlights([])\n return\n }\n\n const pageRect = pageElement.getBoundingClientRect()\n const nextHighlights: SearchHighlight[] = []\n\n textLayer.querySelectorAll<HTMLElement>("span").forEach((span, index) => {\n const textNode = Array.from(span.childNodes).find(\n (node): node is Text => node.nodeType === Node.TEXT_NODE\n )\n const text = textNode?.textContent ?? ""\n const normalizedText = text.toLowerCase()\n let matchIndex = normalizedText.indexOf(query)\n\n while (textNode && matchIndex !== -1) {\n const range = document.createRange()\n range.setStart(textNode, matchIndex)\n range.setEnd(textNode, matchIndex + query.length)\n\n Array.from(range.getClientRects()).forEach((rect, rectIndex) => {\n if (rect.width <= 0 || rect.height <= 0) return\n\n nextHighlights.push({\n id: `${pageNumber}-${index}-${matchIndex}-${rectIndex}`,\n left: rect.left - pageRect.left,\n top: rect.top - pageRect.top,\n width: rect.width,\n height: rect.height,\n })\n })\n\n range.detach()\n matchIndex = normalizedText.indexOf(query, matchIndex + query.length)\n }\n })\n\n setSearchHighlights(nextHighlights)\n }, [pageNumber, searchQuery])\n\n React.useEffect(() => {\n if (!shouldRenderPage || !hasSearchQuery) {\n setSearchHighlights([])\n return\n }\n\n const frame = window.requestAnimationFrame(updateSearchHighlights)\n return () => window.cancelAnimationFrame(frame)\n }, [hasSearchQuery, shouldRenderPage, updateSearchHighlights])\n\n return (\n <div\n ref={pageRef}\n data-pdf-viewer-page={pageNumber}\n className={cn("relative", pageClassName?.(pageNumber))}\n style={pageStyle}\n onPointerDown={(event) => onPagePointerDown?.(event, pageNumber)}\n onPointerMove={(event) => onPagePointerMove?.(event, pageNumber)}\n onPointerUp={(event) => onPagePointerUp?.(event, pageNumber)}\n onPointerCancel={(event) => onPagePointerCancel?.(event, pageNumber)}\n >\n {shouldRenderPage ? (\n <>\n <reactPdf.Page\n pageNumber={pageNumber}\n width={renderedPageWidth}\n rotate={effectiveRotation}\n className="overflow-hidden border bg-background shadow-xs"\n renderAnnotationLayer={false}\n renderTextLayer={hasSearchQuery}\n devicePixelRatio={\n typeof window === "undefined"\n ? 1\n : Math.min(MAX_DEVICE_PIXEL_RATIO, window.devicePixelRatio || 1)\n }\n loading={\n <div className="grid place-items-center" style={pageStyle}>\n <Spinner className="size-4" />\n </div>\n }\n onRenderSuccess={() => onPageSettled(pageNumber)}\n onRenderTextLayerSuccess={updateSearchHighlights}\n onRenderError={() => onPageSettled(pageNumber)}\n />\n {searchHighlights.length ? (\n <div className="pointer-events-none absolute inset-0 z-10">\n {searchHighlights.map((highlight) => (\n <div\n key={highlight.id}\n className="absolute rounded-[2px] bg-yellow-300/45 mix-blend-multiply ring-1 ring-yellow-500/20 dark:bg-yellow-300/35"\n style={{\n left: highlight.left,\n top: highlight.top,\n width: highlight.width,\n height: highlight.height,\n }}\n />\n ))}\n </div>\n ) : null}\n </>\n ) : (\n <div className="size-full border bg-muted/30 shadow-xs" />\n )}\n {renderPageOverlay?.({\n pageNumber,\n pageWidth: pageStyle.width,\n pageHeight: pageStyle.height,\n scale: zoom,\n rotation: effectiveRotation,\n })}\n </div>\n )\n}\n\nexport const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(\n function PDFViewer(\n {\n file,\n className,\n defaultThumbnailSidebarOpen = false,\n defaultZoom = DEFAULT_ZOOM,\n pageWidth = DEFAULT_PAGE_WIDTH,\n pageHeight = DEFAULT_PAGE_HEIGHT,\n pageNumbers,\n pageRenderBuffer = DEFAULT_PAGE_RENDER_BUFFER,\n downloadFileName,\n showDownload = true,\n showRotateControls = true,\n showUpload = true,\n toolbarActions,\n pageClassName,\n renderPageOverlay,\n onActivePageChange,\n onDocumentLoadSuccess,\n onPdfUpload,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n },\n ref\n ) {\n const [reactPdf, setReactPdf] = React.useState<ReactPdfModule | null>(null)\n const [pdfFile, setPdfFile] = React.useState(file ?? "")\n const [uploadedPdfUrl, setUploadedPdfUrl] = React.useState<string | null>(\n null\n )\n const [numPages, setNumPages] = React.useState(0)\n const [activePage, setActivePage] = React.useState(1)\n const [zoom, setZoom] = React.useState(defaultZoom)\n const [pageRotationDeltas, setPageRotationDeltas] =\n React.useState<PageRotationDeltas>(() => new Map())\n const [pageMetrics, setPageMetrics] = React.useState<\n Map<number, PDFPageMetrics>\n >(() => new Map())\n const [sidebarOpen, setSidebarOpen] = React.useState(\n defaultThumbnailSidebarOpen\n )\n const [searchDraft, setSearchDraft] = React.useState("")\n const [searchQuery, setSearchQuery] = React.useState("")\n const [isDocumentLoading, setIsDocumentLoading] = React.useState(true)\n const [isFirstPageRendering, setIsFirstPageRendering] = React.useState(true)\n const [settledPageNumbers, setSettledPageNumbers] = React.useState<\n Set<number>\n >(() => new Set())\n const [loadError, setLoadError] = React.useState(false)\n const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)\n const viewportRef = React.useRef<HTMLDivElement>(null)\n const thumbnailViewportRef = React.useRef<HTMLDivElement>(null)\n const wasThumbnailSidebarVisibleRef = React.useRef(false)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const thumbnailClickScrollYRef = React.useRef<number | null>(null)\n\n React.useEffect(() => {\n setPdfFile(file ?? "")\n setLoadError(false)\n setIsDocumentLoading(Boolean(file))\n setIsFirstPageRendering(Boolean(file))\n setSettledPageNumbers(new Set())\n setNumPages(0)\n setActivePage(1)\n setPageMetrics(new Map())\n setPageRotationDeltas(new Map())\n }, [file])\n\n React.useEffect(() => {\n let mounted = true\n\n void import("react-pdf")\n .then((module) => {\n module.pdfjs.GlobalWorkerOptions.workerSrc = getPdfWorkerUrl(\n module.pdfjs.version\n )\n\n if (mounted) {\n setReactPdf(module)\n }\n })\n .catch(() => {\n if (mounted) {\n setLoadError(true)\n setIsDocumentLoading(false)\n setIsFirstPageRendering(false)\n }\n })\n\n return () => {\n mounted = false\n }\n }, [])\n\n React.useEffect(() => {\n return () => {\n if (uploadedPdfUrl) {\n URL.revokeObjectURL(uploadedPdfUrl)\n }\n }\n }, [uploadedPdfUrl])\n\n const renderedPageNumbers = React.useMemo(() => {\n if (pageNumbers?.length) return pageNumbers\n\n return Array.from({ length: numPages || 1 }, (_, index) => index + 1)\n }, [numPages, pageNumbers])\n\n const firstRenderedPage = renderedPageNumbers[0] ?? 1\n const defaultPageMetrics = React.useMemo<PDFPageMetrics>(\n () => ({ width: pageWidth, height: pageHeight, rotation: 0 }),\n [pageHeight, pageWidth]\n )\n const getPageMetrics = React.useCallback(\n (pageNumber: number) => pageMetrics.get(pageNumber) ?? defaultPageMetrics,\n [defaultPageMetrics, pageMetrics]\n )\n const resolvedDownloadFileName = React.useMemo(\n () => getPdfDownloadFileName(downloadFileName, pdfFile),\n [downloadFileName, pdfFile]\n )\n const hasPdfFile = Boolean(pdfFile)\n const controlsDisabled = !hasPdfFile || !reactPdf || !numPages\n const downloadDisabled = controlsDisabled || isPreparingDownload\n const isLoading =\n hasPdfFile && (!reactPdf || isDocumentLoading || isFirstPageRendering)\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const thumbnailSidebarVisible = Boolean(\n sidebarOpen && !isLoading && !loadError\n )\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !renderedPageNumbers.length) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n let closestPage = renderedPageNumbers[0] ?? 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>("[data-pdf-viewer-page]")\n .forEach((page) => {\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 = Number(page.dataset.pdfViewerPage || "1")\n }\n })\n\n setActivePage((currentPage) => {\n if (currentPage === closestPage) return currentPage\n onActivePageChange?.(closestPage)\n return closestPage\n })\n }, [onActivePageChange, renderedPageNumbers])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !numPages) 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 }, [numPages, updateActivePageFromViewport])\n\n React.useImperativeHandle(\n ref,\n () => ({\n scrollToPage: (pageNumber, options) => {\n const page = viewportRef.current?.querySelector<HTMLElement>(\n `[data-pdf-viewer-page="${pageNumber}"]`\n )\n\n page?.scrollIntoView({\n block: "start",\n inline: "nearest",\n ...options,\n })\n },\n scrollToPageArea: (pageNumber, area, options) => {\n const viewport = viewportRef.current\n const page = viewport?.querySelector<HTMLElement>(\n `[data-pdf-viewer-page="${pageNumber}"]`\n )\n\n if (!viewport || !page) return\n\n const pageTop =\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop\n const targetTop =\n pageTop +\n (area.top / 100) * page.getBoundingClientRect().height -\n 96\n\n viewport.scrollTo({\n top: Math.max(0, targetTop),\n behavior: "smooth",\n ...options,\n })\n },\n getViewportElement: () => viewportRef.current,\n }),\n []\n )\n\n const restoreWindowScroll = React.useCallback((scrollY: number) => {\n window.scrollTo({ top: scrollY })\n window.requestAnimationFrame(() => {\n window.scrollTo({ top: scrollY })\n window.requestAnimationFrame(() => {\n window.scrollTo({ top: scrollY })\n })\n })\n ;[0, 50, 150, 300].forEach((delay) => {\n window.setTimeout(() => {\n window.scrollTo({ top: scrollY })\n }, delay)\n })\n }, [])\n\n const scrollToPage = React.useCallback(\n (pageNumber: number) => {\n const windowScrollY = thumbnailClickScrollYRef.current ?? window.scrollY\n setActivePage(pageNumber)\n\n const viewport = viewportRef.current\n const page = viewport?.querySelector<HTMLElement>(\n `[data-pdf-viewer-page="${pageNumber}"]`\n )\n\n if (!viewport || !page) {\n restoreWindowScroll(windowScrollY)\n return\n }\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n restoreWindowScroll(windowScrollY)\n window.setTimeout(() => {\n if (thumbnailClickScrollYRef.current === windowScrollY) {\n thumbnailClickScrollYRef.current = null\n }\n }, 350)\n },\n [restoreWindowScroll]\n )\n\n const preserveThumbnailClickScroll = React.useCallback(\n (event: React.PointerEvent | React.MouseEvent) => {\n event.preventDefault()\n\n if (thumbnailClickScrollYRef.current === null) {\n thumbnailClickScrollYRef.current = window.scrollY\n }\n },\n []\n )\n\n const scrollActiveThumbnailIntoView = React.useCallback(() => {\n const viewport = thumbnailViewportRef.current\n const thumbnail = viewport?.querySelector<HTMLElement>(\n `[data-pdf-viewer-thumbnail="${activePage}"]`\n )\n\n if (!viewport || !thumbnail) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const thumbnailRect = thumbnail.getBoundingClientRect()\n const targetTop =\n thumbnailRect.top -\n viewportRect.top +\n viewport.scrollTop -\n (viewport.clientHeight - thumbnail.offsetHeight) / 2\n\n viewport.scrollTo({\n top: Math.max(0, targetTop),\n behavior: "auto",\n })\n }, [activePage])\n\n React.useEffect(() => {\n const wasThumbnailSidebarVisible = wasThumbnailSidebarVisibleRef.current\n wasThumbnailSidebarVisibleRef.current = thumbnailSidebarVisible\n\n if (!thumbnailSidebarVisible || wasThumbnailSidebarVisible) return\n\n const frameId = window.requestAnimationFrame(\n scrollActiveThumbnailIntoView\n )\n\n return () => window.cancelAnimationFrame(frameId)\n }, [scrollActiveThumbnailIntoView, thumbnailSidebarVisible])\n\n const handleLoadStart = React.useCallback(() => {\n setIsDocumentLoading(true)\n setIsFirstPageRendering(true)\n setLoadError(false)\n setNumPages(0)\n setActivePage(1)\n setPageMetrics(new Map())\n setPageRotationDeltas(new Map())\n setSettledPageNumbers(new Set())\n onActivePageChange?.(1)\n setSearchQuery("")\n setSearchDraft("")\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [onActivePageChange])\n\n const handleLoadSuccess = React.useCallback(\n async (pdf: PDFDocumentProxy) => {\n const nextNumPages = pdf.numPages\n\n setNumPages(nextNumPages)\n setIsFirstPageRendering(true)\n setSettledPageNumbers(new Set())\n setLoadError(false)\n setActivePage(1)\n onActivePageChange?.(1)\n onDocumentLoadSuccess?.(nextNumPages)\n setSearchQuery("")\n setSearchDraft("")\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n\n try {\n setPageMetrics(await getDocumentPageMetrics(pdf))\n setIsDocumentLoading(false)\n } catch {\n setPageMetrics(new Map())\n setIsDocumentLoading(false)\n }\n },\n [onActivePageChange, onDocumentLoadSuccess]\n )\n\n const handleLoadError = React.useCallback(() => {\n setIsDocumentLoading(false)\n setIsFirstPageRendering(false)\n setLoadError(true)\n setNumPages(0)\n setPageMetrics(new Map())\n setPageRotationDeltas(new Map())\n }, [])\n\n const handlePageSettled = React.useCallback(\n (pageNumber: number) => {\n setSettledPageNumbers((currentPageNumbers) => {\n if (currentPageNumbers.has(pageNumber)) return currentPageNumbers\n\n const nextPageNumbers = new Set(currentPageNumbers)\n nextPageNumbers.add(pageNumber)\n return nextPageNumbers\n })\n\n if (pageNumber === firstRenderedPage) {\n setIsFirstPageRendering(false)\n }\n },\n [firstRenderedPage]\n )\n\n React.useEffect(() => {\n setSettledPageNumbers(new Set())\n setIsFirstPageRendering(Boolean(pdfFile))\n }, [pdfFile, pageMetrics])\n\n const rotateActivePage = React.useCallback(\n (rotationDelta: number) => {\n setPageRotationDeltas((currentRotations) => {\n const currentRotation = currentRotations.get(activePage) ?? 0\n const nextRotation = normalizeRotation(\n currentRotation + rotationDelta\n )\n const nextRotations = new Map(currentRotations)\n\n if (nextRotation) {\n nextRotations.set(activePage, nextRotation)\n } else {\n nextRotations.delete(activePage)\n }\n\n return nextRotations\n })\n },\n [activePage]\n )\n\n const handleDownload = React.useCallback(async () => {\n if (!pdfFile || isPreparingDownload) return\n\n setIsPreparingDownload(true)\n\n try {\n await downloadPdfWithPageRotations({\n file: pdfFile,\n fileName: resolvedDownloadFileName,\n pageRotationDeltas,\n })\n } catch (error) {\n console.error(error)\n } finally {\n setIsPreparingDownload(false)\n }\n }, [\n isPreparingDownload,\n pageRotationDeltas,\n pdfFile,\n resolvedDownloadFileName,\n ])\n\n const handleUpload = React.useCallback(\n (file: File) => {\n const nextUrl = URL.createObjectURL(file)\n\n setUploadedPdfUrl((previousUrl) => {\n if (previousUrl) URL.revokeObjectURL(previousUrl)\n return nextUrl\n })\n setPdfFile(nextUrl)\n onPdfUpload?.(file)\n },\n [onPdfUpload]\n )\n\n return (\n <div\n data-slot="pdf-viewer"\n className={cn(\n "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n <div className="flex min-h-12 items-center justify-between gap-3 border-b px-3">\n <div className="flex items-center gap-2">\n <TooltipProvider>\n <ToolbarTooltip label="Toggle thumbnails">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Toggle thumbnails"\n disabled={controlsDisabled}\n onClick={() => setSidebarOpen((open) => !open)}\n >\n <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </TooltipProvider>\n <div className="text-sm whitespace-nowrap text-primary">\n Page {activePage} of {numPages || "-"}\n </div>\n </div>\n <TooltipProvider>\n <div className="flex min-w-0 items-center gap-1">\n {showRotateControls ? (\n <>\n <ToolbarTooltip label="Rotate page counterclockwise">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Rotate page counterclockwise"\n disabled={controlsDisabled}\n onClick={() => rotateActivePage(-90)}\n >\n <HugeiconsIcon\n icon={RotateClockwiseIcon}\n className="size-4 -scale-x-100"\n />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Rotate page clockwise">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Rotate page clockwise"\n disabled={controlsDisabled}\n onClick={() => rotateActivePage(90)}\n >\n <HugeiconsIcon\n icon={RotateClockwiseIcon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom out"\n disabled={controlsDisabled || zoom <= ZOOM_OPTIONS[0]}\n onClick={() => {\n const currentIndex = ZOOM_OPTIONS.indexOf(zoom)\n setZoom(ZOOM_OPTIONS[Math.max(0, currentIndex - 1)] ?? zoom)\n }}\n >\n <HugeiconsIcon\n icon={MinusSignCircleIcon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={String(zoom)}\n onValueChange={(value) => setZoom(Number(value))}\n disabled={controlsDisabled}\n modal={false}\n >\n <SelectTrigger size="sm" className="w-[84px] min-w-[84px]">\n <SelectValue placeholder="Zoom">\n {Math.round(zoom * 100)}%\n </SelectValue>\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((option) => (\n <SelectItem key={option} value={String(option)}>\n {Math.round(option * 100)}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom in"\n disabled={\n controlsDisabled ||\n zoom >= ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n }\n onClick={() => {\n const currentIndex = ZOOM_OPTIONS.indexOf(zoom)\n setZoom(\n ZOOM_OPTIONS[\n Math.min(ZOOM_OPTIONS.length - 1, currentIndex + 1)\n ] ?? zoom\n )\n }}\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {showDownload ? (\n <>\n <ToolbarTooltip label="Download PDF">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Download PDF"\n disabled={downloadDisabled}\n onClick={handleDownload}\n >\n {isPreparingDownload ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon\n icon={Download01Icon}\n className="size-4"\n />\n )}\n </Button>\n </ToolbarTooltip>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <Popover>\n <ToolbarTooltip label="Search text">\n <PopoverTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search text"\n disabled={controlsDisabled}\n >\n <HugeiconsIcon icon={Search01Icon} className="size-4" />\n </Button>\n </PopoverTrigger>\n </ToolbarTooltip>\n <PopoverContent align="end" className="w-64">\n <SearchInput\n value={searchDraft}\n onValueChange={setSearchDraft}\n onApply={() => setSearchQuery(searchDraft)}\n onClear={() => {\n setSearchDraft("")\n setSearchQuery("")\n }}\n />\n </PopoverContent>\n </Popover>\n {toolbarActions ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {toolbarActions}\n </>\n ) : null}\n {showUpload ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <ToolbarTooltip label="Upload PDF">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Upload PDF"\n render={\n <label>\n <input\n type="file"\n accept="application/pdf,.pdf"\n className="sr-only"\n onChange={(event) => {\n const nextFile = event.target.files?.[0]\n\n if (nextFile) {\n handleUpload(nextFile)\n event.currentTarget.value = ""\n }\n }}\n />\n <HugeiconsIcon\n icon={Upload01Icon}\n className="size-4"\n />\n </label>\n }\n />\n </ToolbarTooltip>\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {!hasPdfFile ? (\n <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-center text-sm text-muted-foreground">\n <div className="max-w-sm space-y-3">\n <div className="font-medium text-foreground">\n Upload a PDF to preview\n </div>\n <div>\n Pass a PDF URL with the <code>file</code> prop or use the\n upload control.\n </div>\n </div>\n </div>\n ) : null}\n {isLoading && !loadError ? (\n <PDFViewerLoadingSkeleton\n sidebarInline={sidebarInline}\n sidebarOpen={sidebarOpen}\n />\n ) : null}\n {loadError ? (\n <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-sm text-muted-foreground">\n Unable to load the PDF preview.\n </div>\n ) : null}\n {reactPdf && hasPdfFile ? (\n <reactPdf.Document\n file={pdfFile}\n className={cn(\n "flex h-full min-h-0 w-full flex-1",\n (isLoading || loadError) && "invisible"\n )}\n loading={null}\n error={null}\n onLoadStart={handleLoadStart}\n onLoadSuccess={handleLoadSuccess}\n onLoadError={handleLoadError}\n >\n <div className="flex h-full max-h-full min-h-0 w-full flex-1 overflow-hidden">\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={thumbnailSidebarVisible}\n >\n <ScrollArea\n className="h-full"\n scrollFade\n viewportRef={thumbnailViewportRef}\n >\n <div className="p-4">\n <div className="flex flex-col items-center gap-3">\n {renderedPageNumbers.map((pageNumber) => {\n const metrics = getPageMetrics(pageNumber)\n const rotationDelta =\n pageRotationDeltas.get(pageNumber) ?? 0\n const effectiveRotation = normalizeRotation(\n metrics.rotation + rotationDelta\n )\n const thumbnailDimensions = getPageDimensions(\n metrics,\n effectiveRotation\n )\n const thumbnailAspectRatio =\n thumbnailDimensions.width /\n thumbnailDimensions.height\n\n return (\n <Button\n key={pageNumber}\n data-pdf-viewer-thumbnail={pageNumber}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",\n pageNumber === activePage\n ? "bg-sidebar-accent text-foreground"\n : "text-muted-foreground"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onMouseDown={preserveThumbnailClickScroll}\n onPointerDown={preserveThumbnailClickScroll}\n onClick={() => scrollToPage(pageNumber)}\n >\n <PDFSidebarThumbnail\n file={pdfFile}\n pageMetrics={metrics}\n pageNumber={pageNumber}\n reactPdf={reactPdf}\n rotation={rotationDelta}\n thumbnailAspectRatio={thumbnailAspectRatio}\n />\n {pageNumber}\n </Button>\n )\n })}\n </div>\n </div>\n </ScrollArea>\n </DocumentViewerThumbnailSidebar>\n <ScrollArea\n className="h-full max-h-full min-h-0 min-w-0 flex-1"\n viewportClassName={cn(\n isFirstPageRendering && !loadError && "invisible"\n )}\n viewportRef={viewportRef}\n >\n <div className="flex min-h-full w-max min-w-full flex-col items-center justify-start gap-6 p-6">\n {renderedPageNumbers.map((pageNumber) => {\n const metrics = getPageMetrics(pageNumber)\n const rotationDelta =\n pageRotationDeltas.get(pageNumber) ?? 0\n const effectiveRotation = normalizeRotation(\n metrics.rotation + rotationDelta\n )\n const dimensions = getPageDimensions(\n metrics,\n effectiveRotation\n )\n const shouldRenderPage =\n Math.abs(pageNumber - activePage) <= pageRenderBuffer ||\n settledPageNumbers.has(pageNumber) ||\n renderedPageNumbers.length <= pageRenderBuffer * 2 + 1\n const pageStyle = {\n width: dimensions.width * zoom,\n height: dimensions.height * zoom,\n }\n const pageSearchQuery =\n searchQuery.trim() &&\n Math.abs(pageNumber - activePage) <= 1\n ? searchQuery\n : ""\n\n return (\n <PDFViewerPage\n key={pageNumber}\n effectiveRotation={effectiveRotation}\n reactPdf={reactPdf}\n pageNumber={pageNumber}\n pageStyle={pageStyle}\n renderedPageWidth={pageStyle.width}\n zoom={zoom}\n shouldRenderPage={shouldRenderPage}\n searchQuery={pageSearchQuery}\n pageClassName={pageClassName}\n renderPageOverlay={renderPageOverlay}\n onPageSettled={handlePageSettled}\n onPagePointerDown={onPagePointerDown}\n onPagePointerMove={onPagePointerMove}\n onPagePointerUp={onPagePointerUp}\n onPagePointerCancel={onPagePointerCancel}\n />\n )\n })}\n </div>\n </ScrollArea>\n </div>\n </reactPdf.Document>\n ) : null}\n </div>\n </div>\n )\n }\n)\n'+ '"use client"\n\nimport * as React from "react"\nimport {\n Download01Icon,\n MinusSignCircleIcon,\n PlusSignCircleIcon,\n RotateClockwiseIcon,\n Search01Icon,\n SidebarLeftIcon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport type { PDFDocumentProxy } from "pdfjs-dist"\nimport type * as ReactPdf from "react-pdf"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DocumentViewerSidebarSkeleton,\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/ui/document-viewer-sidebar"\nimport { 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 { Input } from "@/registry/new-york-v4/ui/input"\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from "@/registry/new-york-v4/ui/popover"\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\ntype ReactPdfModule = typeof ReactPdf\ntype PageRotationDeltas = Map<number, number>\n\ntype PDFPageMetrics = {\n width: number\n height: number\n rotation: number\n}\n\nexport type PDFViewerPageOverlayProps = {\n pageNumber: number\n pageWidth: number\n pageHeight: number\n scale: number\n rotation: number\n}\n\nexport type PDFViewerHandle = {\n scrollToPage: (pageNumber: number, options?: ScrollIntoViewOptions) => void\n scrollToPageArea: (\n pageNumber: number,\n area: { top: number; left?: number; width?: number; height?: number },\n options?: ScrollToOptions\n ) => void\n getViewportElement: () => HTMLDivElement | null\n}\n\nexport type PDFViewerProps = {\n file?: string\n className?: string\n defaultThumbnailSidebarOpen?: boolean\n defaultZoom?: number\n pageWidth?: number\n pageHeight?: number\n pageNumbers?: number[]\n pageRenderBuffer?: number\n downloadFileName?: string\n showDownload?: boolean\n showRotateControls?: boolean\n showUpload?: boolean\n toolbarActions?: React.ReactNode\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onActivePageChange?: (pageNumber: number) => void\n onDocumentLoadSuccess?: (numPages: number) => void\n onPdfUpload?: (file: File) => void\n onPagePointerDown?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerMove?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerUp?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerCancel?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n}\n\nconst DEFAULT_PAGE_WIDTH = 612\nconst DEFAULT_PAGE_HEIGHT = 792\nconst DEFAULT_ZOOM = 0.75\nconst ZOOM_OPTIONS = [0.5, 0.75, 1, 1.25, 1.5, 2]\nconst MAX_DEVICE_PIXEL_RATIO = 2\nconst DEFAULT_PAGE_RENDER_BUFFER = 4\nconst THUMBNAIL_WIDTH = 92\ntype SearchHighlight = {\n id: string\n left: number\n top: number\n width: number\n height: number\n}\n\nfunction getPdfWorkerUrl(pdfjsVersion: string) {\n return `//unpkg.com/pdfjs-dist@${pdfjsVersion}/legacy/build/pdf.worker.min.mjs`\n}\n\nfunction normalizeRotation(rotation: number) {\n return (((Math.round(rotation / 90) * 90) % 360) + 360) % 360\n}\n\nfunction isQuarterTurn(rotation: number) {\n return Math.abs(normalizeRotation(rotation) / 90) % 2 === 1\n}\n\nfunction getPageDimensions(metrics: PDFPageMetrics, rotation: number) {\n return isQuarterTurn(rotation)\n ? { width: metrics.height, height: metrics.width }\n : { width: metrics.width, height: metrics.height }\n}\n\nfunction ensurePdfExtension(fileName: string) {\n return fileName.toLowerCase().endsWith(".pdf") ? fileName : `${fileName}.pdf`\n}\n\nfunction getPdfDownloadFileName(fileName: string | undefined, file: string) {\n if (fileName?.trim()) return ensurePdfExtension(fileName.trim())\n\n const pathname = file.split(/[?#]/)[0] ?? ""\n const rawName = pathname.split("/").pop() || "document.pdf"\n\n try {\n return ensurePdfExtension(decodeURIComponent(rawName))\n } catch {\n return ensurePdfExtension(rawName)\n }\n}\n\nfunction getRotatedPdfDownloadFileName(fileName: string) {\n return fileName.replace(/\\.pdf$/i, "-rotated.pdf")\n}\n\nfunction downloadBlob(blob: Blob, fileName: string) {\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n\n anchor.href = url\n anchor.download = fileName\n anchor.rel = "noopener"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nasync function getDocumentPageMetrics(pdf: PDFDocumentProxy) {\n const pageEntries = await Promise.all(\n Array.from({ length: pdf.numPages }, async (_, index) => {\n const pageNumber = index + 1\n const page = await pdf.getPage(pageNumber)\n const viewport = page.getViewport({ scale: 1, rotation: 0 })\n\n return [\n pageNumber,\n {\n width: viewport.width,\n height: viewport.height,\n rotation: normalizeRotation(page.rotate),\n },\n ] as const\n })\n )\n\n return new Map<number, PDFPageMetrics>(pageEntries)\n}\n\nasync function downloadPdfWithPageRotations({\n file,\n fileName,\n pageRotationDeltas,\n}: {\n file: string\n fileName: string\n pageRotationDeltas: PageRotationDeltas\n}) {\n const response = await fetch(file)\n\n if (!response.ok) {\n throw new Error(`Failed to download PDF (${response.status})`)\n }\n\n const [{ PDFDocument, degrees }, pdfBytes] = await Promise.all([\n import("pdf-lib"),\n response.arrayBuffer(),\n ])\n const pdfDocument = await PDFDocument.load(pdfBytes)\n\n pdfDocument.getPages().forEach((page, index) => {\n const pageNumber = index + 1\n const rotationDelta = pageRotationDeltas.get(pageNumber) ?? 0\n\n if (!rotationDelta) return\n\n page.setRotation(\n degrees(normalizeRotation(page.getRotation().angle + rotationDelta))\n )\n })\n\n const nextPdfBytes = await pdfDocument.save()\n const nextPdfBuffer = new ArrayBuffer(nextPdfBytes.byteLength)\n new Uint8Array(nextPdfBuffer).set(nextPdfBytes)\n const hasPageRotationChanges = pageRotationDeltas.size > 0\n\n downloadBlob(\n new Blob([nextPdfBuffer], { type: "application/pdf" }),\n hasPageRotationChanges ? getRotatedPdfDownloadFileName(fileName) : fileName\n )\n}\n\nfunction PDFViewerLoadingSkeleton({\n sidebarOpen,\n sidebarInline,\n}: {\n sidebarOpen: boolean\n sidebarInline: boolean\n}) {\n return (\n <div className="absolute inset-0 z-20 flex bg-muted/30">\n {sidebarOpen ? (\n <DocumentViewerSidebarSkeleton inline={sidebarInline} />\n ) : null}\n <div className="grid min-w-0 flex-1 place-items-center">\n <Spinner className="size-4" />\n </div>\n </div>\n )\n}\n\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 SearchInput({\n value,\n onValueChange,\n onApply,\n onClear,\n}: {\n value: string\n onValueChange: (value: string) => void\n onApply: () => void\n onClear: () => void\n}) {\n return (\n <div className="space-y-3">\n <Input\n placeholder="Search text"\n value={value}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) =>\n onValueChange(event.target.value)\n }\n onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key === "Enter") {\n onApply()\n }\n }}\n />\n <div className="flex justify-end gap-2">\n <Button type="button" variant="outline" size="sm" onClick={onClear}>\n Clear\n </Button>\n <Button type="button" size="sm" onClick={onApply}>\n Search\n </Button>\n </div>\n </div>\n )\n}\n\nfunction PDFSidebarThumbnail({\n file,\n pageMetrics,\n pageNumber,\n reactPdf,\n rotation,\n thumbnailAspectRatio,\n}: {\n file: string\n pageMetrics: PDFPageMetrics\n pageNumber: number\n reactPdf: ReactPdfModule\n rotation: number\n thumbnailAspectRatio: number\n}) {\n const effectiveRotation = normalizeRotation(pageMetrics.rotation + rotation)\n\n return (\n <FileThumbnail\n file={{\n name: `Page ${pageNumber}.pdf`,\n type: "application/pdf",\n source: file,\n }}\n previewAspectRatio={thumbnailAspectRatio}\n previewClassName="rounded-md bg-white"\n previewContent={\n <reactPdf.Thumbnail\n pageNumber={pageNumber}\n width={THUMBNAIL_WIDTH}\n rotate={effectiveRotation}\n className="flex size-full items-center justify-center [&_.react-pdf__Thumbnail__page]:!m-0 [&_.react-pdf__Thumbnail__page]:!h-auto [&_.react-pdf__Thumbnail__page]:!w-full [&_.react-pdf__Thumbnail__page]:overflow-hidden [&_canvas]:!h-auto [&_canvas]:!w-full"\n />\n }\n className="w-[92px] rounded-md border-0 shadow-xs ring-0"\n />\n )\n}\n\nfunction PDFViewerPage({\n effectiveRotation,\n reactPdf,\n pageNumber,\n pageStyle,\n renderedPageWidth,\n zoom,\n shouldRenderPage,\n searchQuery,\n pageClassName,\n renderPageOverlay,\n onPageSettled,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n}: {\n effectiveRotation: number\n reactPdf: ReactPdfModule\n pageNumber: number\n pageStyle: React.CSSProperties & { width: number; height: number }\n renderedPageWidth: number\n zoom: number\n shouldRenderPage: boolean\n searchQuery: string\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onPageSettled: (pageNumber: number) => void\n onPagePointerDown?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerMove?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerUp?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerCancel?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n}) {\n const pageRef = React.useRef<HTMLDivElement>(null)\n const [searchHighlights, setSearchHighlights] = React.useState<\n SearchHighlight[]\n >([])\n const hasSearchQuery = Boolean(searchQuery.trim())\n\n const updateSearchHighlights = React.useCallback(() => {\n const pageElement = pageRef.current\n const query = searchQuery.trim().toLowerCase()\n\n if (!pageElement || !query) {\n setSearchHighlights([])\n return\n }\n\n const textLayer = pageElement.querySelector<HTMLElement>(\n ".react-pdf__Page__textContent"\n )\n\n if (!textLayer) {\n setSearchHighlights([])\n return\n }\n\n const pageRect = pageElement.getBoundingClientRect()\n const nextHighlights: SearchHighlight[] = []\n\n textLayer.querySelectorAll<HTMLElement>("span").forEach((span, index) => {\n const textNode = Array.from(span.childNodes).find(\n (node): node is Text => node.nodeType === Node.TEXT_NODE\n )\n const text = textNode?.textContent ?? ""\n const normalizedText = text.toLowerCase()\n let matchIndex = normalizedText.indexOf(query)\n\n while (textNode && matchIndex !== -1) {\n const range = document.createRange()\n range.setStart(textNode, matchIndex)\n range.setEnd(textNode, matchIndex + query.length)\n\n Array.from(range.getClientRects()).forEach((rect, rectIndex) => {\n if (rect.width <= 0 || rect.height <= 0) return\n\n nextHighlights.push({\n id: `${pageNumber}-${index}-${matchIndex}-${rectIndex}`,\n left: rect.left - pageRect.left,\n top: rect.top - pageRect.top,\n width: rect.width,\n height: rect.height,\n })\n })\n\n range.detach()\n matchIndex = normalizedText.indexOf(query, matchIndex + query.length)\n }\n })\n\n setSearchHighlights(nextHighlights)\n }, [pageNumber, searchQuery])\n\n React.useEffect(() => {\n if (!shouldRenderPage || !hasSearchQuery) {\n setSearchHighlights([])\n return\n }\n\n const frame = window.requestAnimationFrame(updateSearchHighlights)\n return () => window.cancelAnimationFrame(frame)\n }, [hasSearchQuery, shouldRenderPage, updateSearchHighlights])\n\n return (\n <div\n ref={pageRef}\n data-pdf-viewer-page={pageNumber}\n className={cn("relative", pageClassName?.(pageNumber))}\n style={pageStyle}\n onPointerDown={(event) => onPagePointerDown?.(event, pageNumber)}\n onPointerMove={(event) => onPagePointerMove?.(event, pageNumber)}\n onPointerUp={(event) => onPagePointerUp?.(event, pageNumber)}\n onPointerCancel={(event) => onPagePointerCancel?.(event, pageNumber)}\n >\n {shouldRenderPage ? (\n <>\n <reactPdf.Page\n pageNumber={pageNumber}\n width={renderedPageWidth}\n rotate={effectiveRotation}\n className="overflow-hidden border bg-background shadow-xs"\n renderAnnotationLayer={false}\n renderTextLayer={hasSearchQuery}\n devicePixelRatio={\n typeof window === "undefined"\n ? 1\n : Math.min(MAX_DEVICE_PIXEL_RATIO, window.devicePixelRatio || 1)\n }\n loading={\n <div className="grid place-items-center" style={pageStyle}>\n <Spinner className="size-4" />\n </div>\n }\n onRenderSuccess={() => onPageSettled(pageNumber)}\n onRenderTextLayerSuccess={updateSearchHighlights}\n onRenderError={() => onPageSettled(pageNumber)}\n />\n {searchHighlights.length ? (\n <div className="pointer-events-none absolute inset-0 z-10">\n {searchHighlights.map((highlight) => (\n <div\n key={highlight.id}\n className="absolute rounded-[2px] bg-yellow-300/45 mix-blend-multiply ring-1 ring-yellow-500/20 dark:bg-yellow-300/35"\n style={{\n left: highlight.left,\n top: highlight.top,\n width: highlight.width,\n height: highlight.height,\n }}\n />\n ))}\n </div>\n ) : null}\n </>\n ) : (\n <div className="size-full border bg-muted/30 shadow-xs" />\n )}\n {renderPageOverlay?.({\n pageNumber,\n pageWidth: pageStyle.width,\n pageHeight: pageStyle.height,\n scale: zoom,\n rotation: effectiveRotation,\n })}\n </div>\n )\n}\n\nexport const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(\n function PDFViewer(\n {\n file,\n className,\n defaultThumbnailSidebarOpen = false,\n defaultZoom = DEFAULT_ZOOM,\n pageWidth = DEFAULT_PAGE_WIDTH,\n pageHeight = DEFAULT_PAGE_HEIGHT,\n pageNumbers,\n pageRenderBuffer = DEFAULT_PAGE_RENDER_BUFFER,\n downloadFileName,\n showDownload = true,\n showRotateControls = true,\n showUpload = true,\n toolbarActions,\n pageClassName,\n renderPageOverlay,\n onActivePageChange,\n onDocumentLoadSuccess,\n onPdfUpload,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n },\n ref\n ) {\n const [reactPdf, setReactPdf] = React.useState<ReactPdfModule | null>(null)\n const [pdfFile, setPdfFile] = React.useState(file ?? "")\n const [uploadedPdfUrl, setUploadedPdfUrl] = React.useState<string | null>(\n null\n )\n const [numPages, setNumPages] = React.useState(0)\n const [activePage, setActivePage] = React.useState(1)\n const [zoom, setZoom] = React.useState(defaultZoom)\n const [pageRotationDeltas, setPageRotationDeltas] =\n React.useState<PageRotationDeltas>(() => new Map())\n const [pageMetrics, setPageMetrics] = React.useState<\n Map<number, PDFPageMetrics>\n >(() => new Map())\n const [sidebarOpen, setSidebarOpen] = React.useState(\n defaultThumbnailSidebarOpen\n )\n const [searchDraft, setSearchDraft] = React.useState("")\n const [searchQuery, setSearchQuery] = React.useState("")\n const [isDocumentLoading, setIsDocumentLoading] = React.useState(true)\n const [isFirstPageRendering, setIsFirstPageRendering] = React.useState(true)\n const [settledPageNumbers, setSettledPageNumbers] = React.useState<\n Set<number>\n >(() => new Set())\n const [loadError, setLoadError] = React.useState(false)\n const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)\n const viewportRef = React.useRef<HTMLDivElement>(null)\n const thumbnailViewportRef = React.useRef<HTMLDivElement>(null)\n const wasThumbnailSidebarVisibleRef = React.useRef(false)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const thumbnailClickScrollYRef = React.useRef<number | null>(null)\n\n React.useEffect(() => {\n setPdfFile(file ?? "")\n setLoadError(false)\n setIsDocumentLoading(Boolean(file))\n setIsFirstPageRendering(Boolean(file))\n setSettledPageNumbers(new Set())\n setNumPages(0)\n setActivePage(1)\n setPageMetrics(new Map())\n setPageRotationDeltas(new Map())\n }, [file])\n\n React.useEffect(() => {\n let mounted = true\n\n void import("react-pdf")\n .then((module) => {\n module.pdfjs.GlobalWorkerOptions.workerSrc = getPdfWorkerUrl(\n module.pdfjs.version\n )\n\n if (mounted) {\n setReactPdf(module)\n }\n })\n .catch(() => {\n if (mounted) {\n setLoadError(true)\n setIsDocumentLoading(false)\n setIsFirstPageRendering(false)\n }\n })\n\n return () => {\n mounted = false\n }\n }, [])\n\n React.useEffect(() => {\n return () => {\n if (uploadedPdfUrl) {\n URL.revokeObjectURL(uploadedPdfUrl)\n }\n }\n }, [uploadedPdfUrl])\n\n const renderedPageNumbers = React.useMemo(() => {\n if (pageNumbers?.length) return pageNumbers\n\n return Array.from({ length: numPages || 1 }, (_, index) => index + 1)\n }, [numPages, pageNumbers])\n\n const firstRenderedPage = renderedPageNumbers[0] ?? 1\n const defaultPageMetrics = React.useMemo<PDFPageMetrics>(\n () => ({ width: pageWidth, height: pageHeight, rotation: 0 }),\n [pageHeight, pageWidth]\n )\n const getPageMetrics = React.useCallback(\n (pageNumber: number) => pageMetrics.get(pageNumber) ?? defaultPageMetrics,\n [defaultPageMetrics, pageMetrics]\n )\n const resolvedDownloadFileName = React.useMemo(\n () => getPdfDownloadFileName(downloadFileName, pdfFile),\n [downloadFileName, pdfFile]\n )\n const hasPdfFile = Boolean(pdfFile)\n const controlsDisabled = !hasPdfFile || !reactPdf || !numPages\n const downloadDisabled = controlsDisabled || isPreparingDownload\n const isLoading =\n hasPdfFile && (!reactPdf || isDocumentLoading || isFirstPageRendering)\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const thumbnailSidebarVisible = Boolean(\n sidebarOpen && !isLoading && !loadError\n )\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !renderedPageNumbers.length) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n let closestPage = renderedPageNumbers[0] ?? 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>("[data-pdf-viewer-page]")\n .forEach((page) => {\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 = Number(page.dataset.pdfViewerPage || "1")\n }\n })\n\n setActivePage((currentPage) => {\n if (currentPage === closestPage) return currentPage\n onActivePageChange?.(closestPage)\n return closestPage\n })\n }, [onActivePageChange, renderedPageNumbers])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !numPages) 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 }, [numPages, updateActivePageFromViewport])\n\n React.useImperativeHandle(\n ref,\n () => ({\n scrollToPage: (pageNumber, options) => {\n const page = viewportRef.current?.querySelector<HTMLElement>(\n `[data-pdf-viewer-page="${pageNumber}"]`\n )\n\n page?.scrollIntoView({\n block: "start",\n inline: "nearest",\n ...options,\n })\n },\n scrollToPageArea: (pageNumber, area, options) => {\n const viewport = viewportRef.current\n const page = viewport?.querySelector<HTMLElement>(\n `[data-pdf-viewer-page="${pageNumber}"]`\n )\n\n if (!viewport || !page) return\n\n const pageTop =\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop\n const targetTop =\n pageTop +\n (area.top / 100) * page.getBoundingClientRect().height -\n 96\n\n viewport.scrollTo({\n top: Math.max(0, targetTop),\n behavior: "smooth",\n ...options,\n })\n },\n getViewportElement: () => viewportRef.current,\n }),\n []\n )\n\n const restoreWindowScroll = React.useCallback((scrollY: number) => {\n window.scrollTo({ top: scrollY })\n window.requestAnimationFrame(() => {\n window.scrollTo({ top: scrollY })\n window.requestAnimationFrame(() => {\n window.scrollTo({ top: scrollY })\n })\n })\n ;[0, 50, 150, 300].forEach((delay) => {\n window.setTimeout(() => {\n window.scrollTo({ top: scrollY })\n }, delay)\n })\n }, [])\n\n const scrollToPage = React.useCallback(\n (pageNumber: number) => {\n const windowScrollY = thumbnailClickScrollYRef.current ?? window.scrollY\n setActivePage(pageNumber)\n\n const viewport = viewportRef.current\n const page = viewport?.querySelector<HTMLElement>(\n `[data-pdf-viewer-page="${pageNumber}"]`\n )\n\n if (!viewport || !page) {\n restoreWindowScroll(windowScrollY)\n return\n }\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n restoreWindowScroll(windowScrollY)\n window.setTimeout(() => {\n if (thumbnailClickScrollYRef.current === windowScrollY) {\n thumbnailClickScrollYRef.current = null\n }\n }, 350)\n },\n [restoreWindowScroll]\n )\n\n const preserveThumbnailClickScroll = React.useCallback(\n (event: React.PointerEvent | React.MouseEvent) => {\n event.preventDefault()\n\n if (thumbnailClickScrollYRef.current === null) {\n thumbnailClickScrollYRef.current = window.scrollY\n }\n },\n []\n )\n\n const scrollActiveThumbnailIntoView = React.useCallback(() => {\n const viewport = thumbnailViewportRef.current\n const thumbnail = viewport?.querySelector<HTMLElement>(\n `[data-pdf-viewer-thumbnail="${activePage}"]`\n )\n\n if (!viewport || !thumbnail) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const thumbnailRect = thumbnail.getBoundingClientRect()\n const targetTop =\n thumbnailRect.top -\n viewportRect.top +\n viewport.scrollTop -\n (viewport.clientHeight - thumbnail.offsetHeight) / 2\n\n viewport.scrollTo({\n top: Math.max(0, targetTop),\n behavior: "auto",\n })\n }, [activePage])\n\n React.useEffect(() => {\n const wasThumbnailSidebarVisible = wasThumbnailSidebarVisibleRef.current\n wasThumbnailSidebarVisibleRef.current = thumbnailSidebarVisible\n\n if (!thumbnailSidebarVisible || wasThumbnailSidebarVisible) return\n\n const frameId = window.requestAnimationFrame(\n scrollActiveThumbnailIntoView\n )\n\n return () => window.cancelAnimationFrame(frameId)\n }, [scrollActiveThumbnailIntoView, thumbnailSidebarVisible])\n\n const handleLoadStart = React.useCallback(() => {\n setIsDocumentLoading(true)\n setIsFirstPageRendering(true)\n setLoadError(false)\n setNumPages(0)\n setActivePage(1)\n setPageMetrics(new Map())\n setPageRotationDeltas(new Map())\n setSettledPageNumbers(new Set())\n onActivePageChange?.(1)\n setSearchQuery("")\n setSearchDraft("")\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [onActivePageChange])\n\n const handleLoadSuccess = React.useCallback(\n async (pdf: PDFDocumentProxy) => {\n const nextNumPages = pdf.numPages\n\n setNumPages(nextNumPages)\n setIsFirstPageRendering(true)\n setSettledPageNumbers(new Set())\n setLoadError(false)\n setActivePage(1)\n onActivePageChange?.(1)\n onDocumentLoadSuccess?.(nextNumPages)\n setSearchQuery("")\n setSearchDraft("")\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n\n try {\n setPageMetrics(await getDocumentPageMetrics(pdf))\n setIsDocumentLoading(false)\n } catch {\n setPageMetrics(new Map())\n setIsDocumentLoading(false)\n }\n },\n [onActivePageChange, onDocumentLoadSuccess]\n )\n\n const handleLoadError = React.useCallback(() => {\n setIsDocumentLoading(false)\n setIsFirstPageRendering(false)\n setLoadError(true)\n setNumPages(0)\n setPageMetrics(new Map())\n setPageRotationDeltas(new Map())\n }, [])\n\n const handlePageSettled = React.useCallback(\n (pageNumber: number) => {\n setSettledPageNumbers((currentPageNumbers) => {\n if (currentPageNumbers.has(pageNumber)) return currentPageNumbers\n\n const nextPageNumbers = new Set(currentPageNumbers)\n nextPageNumbers.add(pageNumber)\n return nextPageNumbers\n })\n\n if (pageNumber === firstRenderedPage) {\n setIsFirstPageRendering(false)\n }\n },\n [firstRenderedPage]\n )\n\n React.useEffect(() => {\n setSettledPageNumbers(new Set())\n setIsFirstPageRendering(Boolean(pdfFile))\n }, [pdfFile, pageMetrics])\n\n const rotateActivePage = React.useCallback(\n (rotationDelta: number) => {\n setPageRotationDeltas((currentRotations) => {\n const currentRotation = currentRotations.get(activePage) ?? 0\n const nextRotation = normalizeRotation(\n currentRotation + rotationDelta\n )\n const nextRotations = new Map(currentRotations)\n\n if (nextRotation) {\n nextRotations.set(activePage, nextRotation)\n } else {\n nextRotations.delete(activePage)\n }\n\n return nextRotations\n })\n },\n [activePage]\n )\n\n const handleDownload = React.useCallback(async () => {\n if (!pdfFile || isPreparingDownload) return\n\n setIsPreparingDownload(true)\n\n try {\n await downloadPdfWithPageRotations({\n file: pdfFile,\n fileName: resolvedDownloadFileName,\n pageRotationDeltas,\n })\n } catch (error) {\n console.error(error)\n } finally {\n setIsPreparingDownload(false)\n }\n }, [\n isPreparingDownload,\n pageRotationDeltas,\n pdfFile,\n resolvedDownloadFileName,\n ])\n\n const handleUpload = React.useCallback(\n (file: File) => {\n const nextUrl = URL.createObjectURL(file)\n\n setUploadedPdfUrl((previousUrl) => {\n if (previousUrl) URL.revokeObjectURL(previousUrl)\n return nextUrl\n })\n setPdfFile(nextUrl)\n onPdfUpload?.(file)\n },\n [onPdfUpload]\n )\n\n return (\n <div\n data-slot="pdf-viewer"\n className={cn(\n "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n <div className="flex min-h-12 items-center justify-between gap-3 border-b px-3">\n <div className="flex items-center gap-2">\n <TooltipProvider>\n <ToolbarTooltip label="Toggle thumbnails">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Toggle thumbnails"\n disabled={controlsDisabled}\n onClick={() => setSidebarOpen((open) => !open)}\n >\n <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </TooltipProvider>\n <div className="text-sm whitespace-nowrap text-primary">\n Page {activePage} of {numPages || "-"}\n </div>\n </div>\n <TooltipProvider>\n <div className="flex min-w-0 items-center gap-1">\n {showRotateControls ? (\n <>\n <ToolbarTooltip label="Rotate page counterclockwise">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Rotate page counterclockwise"\n disabled={controlsDisabled}\n onClick={() => rotateActivePage(-90)}\n >\n <HugeiconsIcon\n icon={RotateClockwiseIcon}\n className="size-4 -scale-x-100"\n />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Rotate page clockwise">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Rotate page clockwise"\n disabled={controlsDisabled}\n onClick={() => rotateActivePage(90)}\n >\n <HugeiconsIcon\n icon={RotateClockwiseIcon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom out"\n disabled={controlsDisabled || zoom <= ZOOM_OPTIONS[0]}\n onClick={() => {\n const currentIndex = ZOOM_OPTIONS.indexOf(zoom)\n setZoom(ZOOM_OPTIONS[Math.max(0, currentIndex - 1)] ?? zoom)\n }}\n >\n <HugeiconsIcon\n icon={MinusSignCircleIcon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={String(zoom)}\n onValueChange={(value) => setZoom(Number(value))}\n disabled={controlsDisabled}\n modal={false}\n >\n <SelectTrigger size="sm" className="w-[84px] min-w-[84px]">\n <SelectValue placeholder="Zoom">\n {Math.round(zoom * 100)}%\n </SelectValue>\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((option) => (\n <SelectItem key={option} value={String(option)}>\n {Math.round(option * 100)}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom in"\n disabled={\n controlsDisabled ||\n zoom >= ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n }\n onClick={() => {\n const currentIndex = ZOOM_OPTIONS.indexOf(zoom)\n setZoom(\n ZOOM_OPTIONS[\n Math.min(ZOOM_OPTIONS.length - 1, currentIndex + 1)\n ] ?? zoom\n )\n }}\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {showDownload ? (\n <>\n <ToolbarTooltip label="Download PDF">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Download PDF"\n disabled={downloadDisabled}\n onClick={handleDownload}\n >\n {isPreparingDownload ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon\n icon={Download01Icon}\n className="size-4"\n />\n )}\n </Button>\n </ToolbarTooltip>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <Popover>\n <ToolbarTooltip label="Search text">\n <PopoverTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search text"\n disabled={controlsDisabled}\n >\n <HugeiconsIcon icon={Search01Icon} className="size-4" />\n </Button>\n </PopoverTrigger>\n </ToolbarTooltip>\n <PopoverContent align="end" className="w-64">\n <SearchInput\n value={searchDraft}\n onValueChange={setSearchDraft}\n onApply={() => setSearchQuery(searchDraft)}\n onClear={() => {\n setSearchDraft("")\n setSearchQuery("")\n }}\n />\n </PopoverContent>\n </Popover>\n {toolbarActions ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {toolbarActions}\n </>\n ) : null}\n {showUpload ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <ToolbarTooltip label="Upload PDF">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Upload PDF"\n render={\n <label>\n <input\n type="file"\n accept="application/pdf,.pdf"\n className="sr-only"\n onChange={(event) => {\n const nextFile = event.target.files?.[0]\n\n if (nextFile) {\n handleUpload(nextFile)\n event.currentTarget.value = ""\n }\n }}\n />\n <HugeiconsIcon\n icon={Upload01Icon}\n className="size-4"\n />\n </label>\n }\n />\n </ToolbarTooltip>\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {!hasPdfFile ? (\n <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-center text-sm text-muted-foreground">\n <div className="max-w-sm space-y-3">\n <div className="font-medium text-foreground">\n Upload a PDF to preview\n </div>\n <div>\n Pass a PDF URL with the <code>file</code> prop or use the\n upload control.\n </div>\n </div>\n </div>\n ) : null}\n {isLoading && !loadError ? (\n <PDFViewerLoadingSkeleton\n sidebarInline={sidebarInline}\n sidebarOpen={sidebarOpen}\n />\n ) : null}\n {loadError ? (\n <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-sm text-muted-foreground">\n Unable to load the PDF preview.\n </div>\n ) : null}\n {reactPdf && hasPdfFile ? (\n <reactPdf.Document\n file={pdfFile}\n className={cn(\n "flex h-full min-h-0 w-full flex-1",\n (isLoading || loadError) && "invisible"\n )}\n loading={null}\n error={null}\n onLoadStart={handleLoadStart}\n onLoadSuccess={handleLoadSuccess}\n onLoadError={handleLoadError}\n >\n <div className="flex h-full max-h-full min-h-0 w-full flex-1 overflow-hidden">\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={thumbnailSidebarVisible}\n >\n <ScrollArea\n className="h-full"\n scrollFade\n viewportRef={thumbnailViewportRef}\n >\n <div className="p-4">\n <div className="flex flex-col items-center gap-3">\n {renderedPageNumbers.map((pageNumber) => {\n const metrics = getPageMetrics(pageNumber)\n const rotationDelta =\n pageRotationDeltas.get(pageNumber) ?? 0\n const effectiveRotation = normalizeRotation(\n metrics.rotation + rotationDelta\n )\n const thumbnailDimensions = getPageDimensions(\n metrics,\n effectiveRotation\n )\n const thumbnailAspectRatio =\n thumbnailDimensions.width /\n thumbnailDimensions.height\n\n return (\n <Button\n key={pageNumber}\n data-pdf-viewer-thumbnail={pageNumber}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",\n pageNumber === activePage\n ? "bg-sidebar-accent text-foreground"\n : "text-muted-foreground"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onMouseDown={preserveThumbnailClickScroll}\n onPointerDown={preserveThumbnailClickScroll}\n onClick={() => scrollToPage(pageNumber)}\n >\n <PDFSidebarThumbnail\n file={pdfFile}\n pageMetrics={metrics}\n pageNumber={pageNumber}\n reactPdf={reactPdf}\n rotation={rotationDelta}\n thumbnailAspectRatio={thumbnailAspectRatio}\n />\n {pageNumber}\n </Button>\n )\n })}\n </div>\n </div>\n </ScrollArea>\n </DocumentViewerThumbnailSidebar>\n <ScrollArea\n className="h-full max-h-full min-h-0 min-w-0 flex-1"\n viewportClassName={cn(\n isFirstPageRendering && !loadError && "invisible"\n )}\n viewportRef={viewportRef}\n >\n <div className="flex min-h-full w-max min-w-full flex-col items-center justify-start gap-6 p-6">\n {renderedPageNumbers.map((pageNumber) => {\n const metrics = getPageMetrics(pageNumber)\n const rotationDelta =\n pageRotationDeltas.get(pageNumber) ?? 0\n const effectiveRotation = normalizeRotation(\n metrics.rotation + rotationDelta\n )\n const dimensions = getPageDimensions(\n metrics,\n effectiveRotation\n )\n const shouldRenderPage =\n Math.abs(pageNumber - activePage) <= pageRenderBuffer ||\n settledPageNumbers.has(pageNumber) ||\n renderedPageNumbers.length <= pageRenderBuffer * 2 + 1\n const pageStyle = {\n width: dimensions.width * zoom,\n height: dimensions.height * zoom,\n }\n const pageSearchQuery =\n searchQuery.trim() &&\n Math.abs(pageNumber - activePage) <= 1\n ? searchQuery\n : ""\n\n return (\n <PDFViewerPage\n key={pageNumber}\n effectiveRotation={effectiveRotation}\n reactPdf={reactPdf}\n pageNumber={pageNumber}\n pageStyle={pageStyle}\n renderedPageWidth={pageStyle.width}\n zoom={zoom}\n shouldRenderPage={shouldRenderPage}\n searchQuery={pageSearchQuery}\n pageClassName={pageClassName}\n renderPageOverlay={renderPageOverlay}\n onPageSettled={handlePageSettled}\n onPagePointerDown={onPagePointerDown}\n onPagePointerMove={onPagePointerMove}\n onPagePointerUp={onPagePointerUp}\n onPagePointerCancel={onPagePointerCancel}\n />\n )\n })}\n </div>\n </ScrollArea>\n </div>\n </reactPdf.Document>\n ) : null}\n </div>\n </div>\n )\n }\n)\n'export function PdfViewerDemo() {const [isCodeVisible, setIsCodeVisible] = React.useState(false)diff --git a/apps/v4/components/root-components-collage.tsx b/apps/v4/components/root-components-collage.tsxindex 5762964..65e24ab 100644--- a/apps/v4/components/root-components-collage.tsx+++ b/apps/v4/components/root-components-collage.tsx@@ -143,18 +143,13 @@ function OcrBlocksTile() {function RootFileThumbnailGrid() {return (<div className="flex flex-wrap content-start items-start justify-center gap-3 bg-background px-3 py-4">- {SAMPLE_FILES.map((file, index) => (+ {SAMPLE_FILES.map((file) => (<div- key={file.url}+ key={file.name}className="min-w-0 basis-[calc(50%-0.375rem)] space-y-1.5 sm:max-w-[7.5rem]"><div className="text-xs font-medium">{getFileKindLabel(file)}</div>- <DocumentAwareFileThumbnail- file={file}- generationDelayMs={250 + index * 220}- className="w-full"- thumbnailWidth={260}- />+ <DocumentAwareFileThumbnail file={file} className="w-full" /></div>))}</div>diff --git a/apps/v4/components/ui/docx-editor.tsx b/apps/v4/components/ui/docx-editor.tsxindex eb2d6cf..e85cd05 100644--- a/apps/v4/components/ui/docx-editor.tsx+++ b/apps/v4/components/ui/docx-editor.tsx@@ -699,7 +699,6 @@ function DocxSidebarThumbnail({className="!size-full bg-white object-cover object-top"/>}- renderDocumentPreview={false}isLoading={isLoading}hasError={hasError}className={cn(diff --git a/apps/v4/components/ui/docx-viewer.tsx b/apps/v4/components/ui/docx-viewer.tsxindex b25a2d3..feff37e 100644--- a/apps/v4/components/ui/docx-viewer.tsx+++ b/apps/v4/components/ui/docx-viewer.tsx@@ -433,7 +433,6 @@ function DocxSidebarThumbnail({className="!size-full bg-white object-cover object-top"/>}- renderDocumentPreview={false}isLoading={isLoading}hasError={hasError}className={cn(diff --git a/apps/v4/components/ui/file-thumbnail.tsx b/apps/v4/components/ui/file-thumbnail.tsxindex 2edb20e..a119afb 100644--- a/apps/v4/components/ui/file-thumbnail.tsx+++ b/apps/v4/components/ui/file-thumbnail.tsx@@ -1,30 +1,10 @@"use client"import * as React from "react"-import {- DocxEditorViewer,- useDocxEditor,- useDocxViewerThumbnails,-} from "@extend-ai/react-docx"-import {- useXlsxViewer,- useXlsxViewerController,- useXlsxViewerThumbnails,- XlsxViewerProvider,-} from "@extend-ai/react-xlsx"-import { File01Icon, FileImageIcon } from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"-import type * as ReactPdf from "react-pdf"--import { cn } from "@/lib/utils"--export type ThumbnailSource = string | File | Blobexport type ThumbnailFile = {name: stringtype: string- source?: ThumbnailSource- url?: string}export type FileThumbnailProps = {@@ -34,215 +14,12 @@ export type FileThumbnailProps = {previewClassName?: stringpreviewContent?: React.ReactNodepreviewImageUrl?: string | null- source?: ThumbnailSource- thumbnailWidth?: number- generationDelayMs?: number- renderDocumentPreview?: booleanisLoading?: booleanhasError?: boolean}-type NormalizedThumbnailFile = {- name: string- type: string- source?: ThumbnailSource- url?: string-}--type ReactPdfModule = typeof ReactPdf--function isBlobLike(value: unknown): value is Blob {- return typeof Blob !== "undefined" && value instanceof Blob-}--function isFileLike(value: unknown): value is File {- return typeof File !== "undefined" && value instanceof File-}--function normalizeFile(file: ThumbnailFile | File): NormalizedThumbnailFile {- return {- name: file.name,- source: isFileLike(file) ? file : (file as ThumbnailFile).source,- type: file.type,- url: (file as ThumbnailFile).url,- }-}--function getThumbnailSource(- file: NormalizedThumbnailFile,- source?: ThumbnailSource-): ThumbnailSource | undefined {- return source ?? file.source ?? file.url-}--function isImageFile(file: NormalizedThumbnailFile) {- return file.type.startsWith("image/")-}--function isPdfFile(file: NormalizedThumbnailFile) {- return (- file.type === "application/pdf" || file.name.toLowerCase().endsWith(".pdf")- )-}--function isDocxFile(file: NormalizedThumbnailFile) {- return (- file.type ===- "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||- file.name.toLowerCase().endsWith(".docx")- )-}--function isXlsxFile(file: NormalizedThumbnailFile) {- const fileName = file.name.toLowerCase()-- return (- file.type ===- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||- file.type === "application/vnd.ms-excel" ||- fileName.endsWith(".xlsx") ||- fileName.endsWith(".xls")- )-}--function FileKindIcon({ file }: { file: NormalizedThumbnailFile }) {- const icon = isImageFile(file) ? FileImageIcon : File01Icon-- return <HugeiconsIcon icon={icon} className="size-4" />-}--function useThumbnailActivation(delayMs: number) {- const [isActive, setIsActive] = React.useState(delayMs <= 0)-- React.useEffect(() => {- if (delayMs <= 0) {- setIsActive(true)- return- }-- setIsActive(false)- const timeout = window.setTimeout(() => {- setIsActive(true)- }, delayMs)-- return () => window.clearTimeout(timeout)- }, [delayMs])-- return isActive-}--function useObjectUrl() {- const [objectUrl, setObjectUrl] = React.useState<string | null>(null)-- const updateObjectUrl = React.useCallback((blob: Blob) => {- const nextUrl = URL.createObjectURL(blob)- setObjectUrl((currentUrl) => {- if (currentUrl) URL.revokeObjectURL(currentUrl)- return nextUrl- })- }, [])-- React.useEffect(() => {- return () => {- if (objectUrl) URL.revokeObjectURL(objectUrl)- }- }, [objectUrl])-- return { objectUrl, updateObjectUrl }-}--function useSourceObjectUrl(source: ThumbnailSource | undefined) {- const [objectUrl, setObjectUrl] = React.useState<string | null>(null)-- React.useEffect(() => {- if (!source || typeof source === "string") {- setObjectUrl(null)- return- }-- const nextUrl = URL.createObjectURL(source)- setObjectUrl(nextUrl)-- return () => URL.revokeObjectURL(nextUrl)- }, [source])-- if (!source) return undefined- return typeof source === "string" ? source : (objectUrl ?? undefined)-}--async function sourceToFile(- source: ThumbnailSource,- file: NormalizedThumbnailFile-) {- if (isFileLike(source)) return source-- if (isBlobLike(source)) {- return new File([source], file.name, {- type: source.type || file.type,- })- }-- const response = await fetch(source)- if (!response.ok) {- throw new Error(`Failed to fetch ${file.name} (${response.status})`)- }-- const blob = await response.blob()-- return new File([blob], file.name, {- type: blob.type || file.type,- })-}--function canvasToBlob(canvas: HTMLCanvasElement | null) {- if (!canvas) return Promise.resolve<Blob | null>(null)-- return new Promise<Blob | null>((resolve) => {- const blobFromDataUrl = async () => {- try {- const dataUrl = canvas.toDataURL("image/png")- const response = await fetch(dataUrl)- return await response.blob()- } catch {- return null- }- }-- try {- if (typeof canvas.toBlob === "function") {- canvas.toBlob((blob) => {- if (blob) {- resolve(blob)- return- }-- void blobFromDataUrl().then(resolve)- }, "image/png")- return- }-- void blobFromDataUrl().then(resolve)- } catch {- resolve(null)- }- })-}--function canvasHasVisiblePixels(canvas: HTMLCanvasElement) {- const context = canvas.getContext("2d")- if (!context || canvas.width <= 0 || canvas.height <= 0) return false-- try {- const { data } = context.getImageData(0, 0, canvas.width, canvas.height)-- for (let index = 3; index < data.length; index += 4) {- if (data[index] > 0) return true- }-- return false- } catch {- return true- }+function cx(...classes: Array<string | false | null | undefined>) {+ return classes.filter(Boolean).join(" ")}export function FileThumbnailLoadingOverlay() {@@ -257,27 +34,16 @@ export function FileThumbnailLoadingOverlay() {)}-function FileThumbnailShell({- file,+export function FileThumbnail({+ file: _file,className,previewAspectRatio,previewClassName,previewContent,previewImageUrl,- hiddenPreviewRenderer,isLoading = false,hasError = false,-}: {- file: NormalizedThumbnailFile- className?: string- previewAspectRatio?: number- previewClassName?: string- previewContent?: React.ReactNode- previewImageUrl?: string | null- hiddenPreviewRenderer?: React.ReactNode- isLoading?: boolean- hasError?: boolean-}) {+}: FileThumbnailProps) {const imageRef = React.useRef<HTMLImageElement | null>(null)const revealFrameRef = React.useRef<number | null>(null)const [loadedPreviewImageUrl, setLoadedPreviewImageUrl] = React.useState<@@ -346,13 +112,13 @@ function FileThumbnailShell({return (<div- className={cn(+ className={cx("group overflow-hidden rounded-lg border bg-background text-foreground",className)}><div- className={cn(+ className={cx("relative aspect-square overflow-hidden bg-muted [contain:layout_paint]",previewClassName)}@@ -370,7 +136,7 @@ function FileThumbnailShell({draggable={false}loading="lazy"decoding="async"- className={cn(+ className={cx("absolute inset-0 block size-full object-cover transition-[opacity,filter] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",showLoading ? "opacity-0 blur-sm" : "blur-0 opacity-100")}@@ -390,7 +156,7 @@ function FileThumbnailShell({) : null}{previewContent ? (<div- className={cn(+ className={cx("absolute inset-0 size-full transition-[opacity,filter] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",showLoading ? "opacity-0 blur-sm" : "blur-0 opacity-100")}@@ -400,650 +166,9 @@ function FileThumbnailShell({) : null}{showLoading ? <FileThumbnailLoadingOverlay /> : null}{showFallback ? (- <div className="absolute inset-0 grid place-items-center bg-muted text-muted-foreground">- <FileKindIcon file={file} />- </div>+ <div className="absolute inset-0 bg-muted" aria-hidden="true" />) : null}</div>- {hiddenPreviewRenderer}</div>)}--function ImageFileThumbnail({- className,- file,- hasError,- isLoading,- previewClassName,- previewAspectRatio,- source,-}: {- className?: string- file: NormalizedThumbnailFile- hasError?: boolean- isLoading?: boolean- previewAspectRatio?: number- previewClassName?: string- source: ThumbnailSource-}) {- const imageUrl = useSourceObjectUrl(source)-- return (- <FileThumbnailShell- file={file}- previewImageUrl={imageUrl}- isLoading={isLoading || !imageUrl}- hasError={hasError}- className={className}- previewAspectRatio={previewAspectRatio}- previewClassName={previewClassName}- />- )-}--function PdfFileThumbnail({- file,- className,- hasError: externalHasError,- isActive,- isLoading: externalIsLoading,- previewClassName,- previewAspectRatio,- source,- thumbnailWidth,-}: {- file: NormalizedThumbnailFile- className?: string- hasError?: boolean- isActive: boolean- isLoading?: boolean- previewAspectRatio?: number- previewClassName?: string- source: ThumbnailSource- thumbnailWidth: number-}) {- const sourceUrl = useSourceObjectUrl(source)- const [reactPdf, setReactPdf] = React.useState<ReactPdfModule | null>(null)- const [isLoading, setIsLoading] = React.useState(true)- const [hasError, setHasError] = React.useState(false)- const rootRef = React.useRef<HTMLDivElement | null>(null)- const { objectUrl, updateObjectUrl } = useObjectUrl()- const shouldRenderPdf =- isActive && sourceUrl && reactPdf && !objectUrl && !hasError- const capturePdfCanvas = React.useCallback(() => {- const canvas = rootRef.current?.querySelector("canvas") ?? null-- void canvasToBlob(canvas).then((blob) => {- if (!blob) {- setHasError(true)- setIsLoading(false)- return- }-- updateObjectUrl(blob)- setHasError(false)- setIsLoading(false)- })- }, [updateObjectUrl])-- React.useEffect(() => {- setIsLoading(true)- setHasError(false)- }, [sourceUrl])-- React.useEffect(() => {- if (!isActive || reactPdf || objectUrl) return-- let isMounted = true- setIsLoading(true)- setHasError(false)-- void import("react-pdf")- .then((module) => {- module.pdfjs.GlobalWorkerOptions.workerSrc = `https://unpkg.com/pdfjs-dist@${module.pdfjs.version}/legacy/build/pdf.worker.min.mjs`- if (isMounted) setReactPdf(module)- })- .catch(() => {- if (isMounted) {- setHasError(true)- setIsLoading(false)- }- })-- return () => {- isMounted = false- }- }, [isActive, objectUrl, reactPdf])-- return (- <FileThumbnailShell- file={file}- previewImageUrl={objectUrl}- isLoading={Boolean(externalIsLoading || (isLoading && !objectUrl))}- hasError={Boolean(externalHasError || hasError)}- className={className}- previewAspectRatio={previewAspectRatio}- previewClassName={previewClassName}- hiddenPreviewRenderer={- shouldRenderPdf ? (- <div- ref={rootRef}- aria-hidden="true"- className="pointer-events-none fixed top-0 left-0 -z-10 w-[560px] overflow-hidden bg-white opacity-0 [contain:layout_paint]"- >- <reactPdf.Document- file={sourceUrl}- loading={null}- error={null}- noData={null}- onLoadError={() => {- setHasError(true)- setIsLoading(false)- }}- >- <reactPdf.Thumbnail- pageNumber={1}- width={thumbnailWidth}- loading={null}- error={null}- onRenderSuccess={() => {- window.requestAnimationFrame(() => {- capturePdfCanvas()- })- }}- onRenderError={() => {- setHasError(true)- setIsLoading(false)- }}- />- </reactPdf.Document>- </div>- ) : null- }- />- )-}--function DocxFileThumbnail({- file,- className,- hasError: externalHasError,- isActive,- isLoading: externalIsLoading,- previewClassName,- previewAspectRatio,- source,- thumbnailWidth,-}: {- file: NormalizedThumbnailFile- className?: string- hasError?: boolean- isActive: boolean- isLoading?: boolean- previewAspectRatio?: number- previewClassName?: string- source: ThumbnailSource- thumbnailWidth: number-}) {- const editor = useDocxEditor({- initialDocumentTheme: "light",- initialFileName: file.name,- })- const thumbnailOptions = React.useMemo(- () => ({- pixelRatio: 2,- resolution: {- maxHeight: thumbnailWidth,- maxWidth: thumbnailWidth,- },- }),- [thumbnailWidth]- )- const { thumbnails } = useDocxViewerThumbnails(editor, thumbnailOptions)- const firstThumbnail = thumbnails[0]- const [hasError, setHasError] = React.useState(false)- const [isReady, setIsReady] = React.useState(false)- const [thumbnailSize, setThumbnailSize] = React.useState<{- height: number- width: number- } | null>(null)- const [thumbnailCanvas, setThumbnailCanvas] =- React.useState<HTMLCanvasElement | null>(null)- const editorRef = React.useRef(editor)- const importedDocxKeyRef = React.useRef<string | null>(null)- const hiddenDocxViewerRef = React.useRef<HTMLDivElement | null>(null)-- React.useEffect(() => {- editorRef.current = editor- }, [editor])-- React.useEffect(() => {- if (!isActive) return-- const docxKey =- typeof source === "string"- ? `${file.name}:${source}`- : `${file.name}:${source.size}:${source.type}`-- if (importedDocxKeyRef.current === docxKey) return-- let isCurrent = true- importedDocxKeyRef.current = docxKey- setHasError(false)- setIsReady(false)-- async function loadDocx() {- try {- const docxFile = await sourceToFile(source, file)- await editorRef.current.importDocxFile(docxFile)- } catch {- if (isCurrent && importedDocxKeyRef.current === docxKey) {- setHasError(true)- }- }- }-- void loadDocx()-- return () => {- isCurrent = false- }- }, [file, isActive, source])-- React.useEffect(() => {- if (!firstThumbnail) {- setThumbnailSize(null)- return- }-- setThumbnailSize((currentSize) => {- if (- currentSize?.height === firstThumbnail.pixelHeightPx &&- currentSize.width === firstThumbnail.pixelWidthPx- ) {- return currentSize- }-- return {- height: firstThumbnail.pixelHeightPx,- width: firstThumbnail.pixelWidthPx,- }- })-- if (firstThumbnail?.status === "error") {- setHasError(true)- }- }, [- firstThumbnail,- firstThumbnail?.pixelHeightPx,- firstThumbnail?.pixelWidthPx,- firstThumbnail?.status,- ])-- const attachThumbnailCanvas = React.useCallback(- (canvas: HTMLCanvasElement | null) => {- setThumbnailCanvas(canvas)- if (canvas) firstThumbnail?.canvasRef(canvas)- },- [firstThumbnail]- )-- React.useEffect(() => {- if (- !isActive ||- !firstThumbnail ||- !thumbnailCanvas ||- isReady ||- hasError- ) {- return- }-- let isCurrent = true- let timeoutId: number | undefined- let attempts = 0-- const getRenderedPageSurface = () => {- const pageSurface = hiddenDocxViewerRef.current?.querySelector(- '[data-docx-page-surface="true"]'- )-- if (!pageSurface) return null-- const hasText = Boolean(pageSurface.textContent?.trim())- const hasEmbeddedContent = Boolean(- pageSurface.querySelector("canvas,img,svg,table")- )-- return hasText || hasEmbeddedContent ? pageSurface : null- }-- const checkThumbnail = () => {- if (!isCurrent) return-- if (canvasHasVisiblePixels(thumbnailCanvas)) {- setIsReady(true)- return- }-- if (!getRenderedPageSurface()) {- attempts += 1-- if (attempts > 50) {- setIsReady(true)- return- }-- timeoutId = window.setTimeout(checkThumbnail, 100)- return- }-- attempts += 1-- if (attempts > 50) {- setIsReady(true)- return- }-- timeoutId = window.setTimeout(checkThumbnail, 100)- }-- checkThumbnail()-- return () => {- isCurrent = false- if (timeoutId !== undefined) window.clearTimeout(timeoutId)- }- }, [- firstThumbnail,- firstThumbnail?.isMounted,- hasError,- isActive,- isReady,- thumbnailCanvas,- ])-- const previewContent = thumbnailSize ? (- <canvas- ref={attachThumbnailCanvas}- width={thumbnailSize.width}- height={thumbnailSize.height}- className="!size-full bg-white object-cover object-top"- />- ) : null-- return (- <FileThumbnailShell- file={file}- previewContent={previewContent}- isLoading={Boolean(externalIsLoading || (!isReady && !hasError))}- hasError={Boolean(externalHasError || hasError)}- className={className}- previewAspectRatio={previewAspectRatio}- previewClassName={cn("bg-white", previewClassName)}- hiddenPreviewRenderer={- isActive && !hasError ? (- <div- ref={hiddenDocxViewerRef}- aria-hidden="true"- className="pointer-events-none fixed top-0 left-0 -z-10 h-[1056px] w-[816px] overflow-hidden bg-white opacity-0 [contain:layout_paint]"- >- <div className="w-[816px]">- <DocxEditorViewer- editor={editor}- mode="read-only"- pageBackgroundColor="#ffffff"- pageGapBackgroundColor="transparent"- visiblePageRange={{ endPageIndex: 0, startPageIndex: 0 }}- pageVirtualization={{ enabled: false }}- deferInitialPaginationPaint={false}- />- </div>- </div>- ) : null- }- />- )-}--function XlsxFileThumbnail({- file,- className,- hasError: externalHasError,- isActive,- isLoading: externalIsLoading,- previewClassName,- previewAspectRatio,- source,- thumbnailWidth,-}: {- file: NormalizedThumbnailFile- className?: string- hasError?: boolean- isActive: boolean- isLoading?: boolean- previewAspectRatio?: number- previewClassName?: string- source: ThumbnailSource- thumbnailWidth: number-}) {- const sourceUrl = useSourceObjectUrl(source)- const [imageUrl, setImageUrl] = React.useState<string | null>(null)- const [hasError, setHasError] = React.useState(false)-- React.useEffect(() => {- setImageUrl(null)- setHasError(false)- }, [sourceUrl])-- return (- <>- <FileThumbnailShell- file={file}- previewImageUrl={imageUrl}- isLoading={Boolean(externalIsLoading || (!imageUrl && !hasError))}- hasError={Boolean(externalHasError || hasError)}- className={className}- previewAspectRatio={previewAspectRatio}- previewClassName={cn(- "bg-white [&>img]:object-left-top",- previewClassName- )}- />- {isActive && sourceUrl && !imageUrl && !hasError ? (- <XlsxThumbnailGenerator- file={file}- sourceUrl={sourceUrl}- thumbnailWidth={thumbnailWidth}- onError={() => setHasError(true)}- onImageUrl={setImageUrl}- />- ) : null}- </>- )-}--function XlsxThumbnailGenerator({- file,- onError,- onImageUrl,- sourceUrl,- thumbnailWidth,-}: {- file: NormalizedThumbnailFile- onError: () => void- onImageUrl: (url: string) => void- sourceUrl: string- thumbnailWidth: number-}) {- const controller = useXlsxViewerController(- React.useMemo(- () => ({- fileName: file.name,- readOnly: true,- src: sourceUrl,- useWorker: true,- }),- [file.name, sourceUrl]- )- )-- return (- <XlsxViewerProvider controller={controller}>- <XlsxThumbnailGeneratorContent- thumbnailWidth={thumbnailWidth}- onError={onError}- onImageUrl={onImageUrl}- />- </XlsxViewerProvider>- )-}--function XlsxThumbnailGeneratorContent({- onError,- onImageUrl,- thumbnailWidth,-}: {- onError: () => void- onImageUrl: (url: string) => void- thumbnailWidth: number-}) {- const controller = useXlsxViewer()- const thumbnailOptions = React.useMemo(- () => ({- includeHeaders: true,- resolution: {- maxHeight: thumbnailWidth,- maxWidth: thumbnailWidth,- },- }),- [thumbnailWidth]- )- const { thumbnails } = useXlsxViewerThumbnails(thumbnailOptions)- const firstThumbnail = thumbnails[0]-- React.useEffect(() => {- if (controller.error) {- onError()- return- }-- if (!firstThumbnail) return-- const canvas = document.createElement("canvas")-- if (!firstThumbnail.paint(canvas)) return-- onImageUrl(canvas.toDataURL("image/png"))- }, [controller.error, firstThumbnail, onError, onImageUrl])-- return null-}--export function FileThumbnail({- file: rawFile,- className,- previewAspectRatio,- previewClassName,- previewContent,- previewImageUrl,- source: explicitSource,- thumbnailWidth,- generationDelayMs = 0,- renderDocumentPreview = true,- isLoading = false,- hasError = false,-}: FileThumbnailProps) {- const file = React.useMemo(() => normalizeFile(rawFile), [rawFile])- const source = getThumbnailSource(file, explicitSource)- const isActive = useThumbnailActivation(generationDelayMs)-- if (previewImageUrl || previewContent || !renderDocumentPreview || !source) {- return (- <FileThumbnailShell- file={file}- previewImageUrl={previewImageUrl}- previewContent={previewContent}- isLoading={isLoading}- hasError={hasError}- className={className}- previewAspectRatio={previewAspectRatio}- previewClassName={previewClassName}- />- )- }-- if (isImageFile(file)) {- return (- <ImageFileThumbnail- file={file}- source={source}- isLoading={isLoading}- hasError={hasError}- className={className}- previewAspectRatio={previewAspectRatio}- previewClassName={previewClassName}- />- )- }-- if (isPdfFile(file)) {- return (- <PdfFileThumbnail- file={file}- source={source}- isActive={isActive}- isLoading={isLoading}- hasError={hasError}- className={className}- previewAspectRatio={previewAspectRatio}- previewClassName={previewClassName}- thumbnailWidth={thumbnailWidth ?? 520}- />- )- }-- if (isDocxFile(file)) {- return (- <DocxFileThumbnail- file={file}- source={source}- isActive={isActive}- isLoading={isLoading}- hasError={hasError}- className={className}- previewAspectRatio={previewAspectRatio}- previewClassName={previewClassName}- thumbnailWidth={thumbnailWidth ?? 520}- />- )- }-- if (isXlsxFile(file)) {- return (- <XlsxFileThumbnail- file={file}- source={source}- isActive={isActive}- isLoading={isLoading}- hasError={hasError}- className={className}- previewAspectRatio={previewAspectRatio}- previewClassName={previewClassName}- thumbnailWidth={thumbnailWidth ?? 680}- />- )- }-- return (- <FileThumbnailShell- file={file}- isLoading={isLoading}- hasError={hasError}- className={className}- previewAspectRatio={previewAspectRatio}- previewClassName={previewClassName}- />- )-}diff --git a/apps/v4/components/ui/pdf-viewer.tsx b/apps/v4/components/ui/pdf-viewer.tsxindex 669daf8..9877277 100644--- a/apps/v4/components/ui/pdf-viewer.tsx+++ b/apps/v4/components/ui/pdf-viewer.tsx@@ -315,14 +315,12 @@ function SearchInput({}function PDFSidebarThumbnail({- file,pageMetrics,pageNumber,reactPdf,rotation,thumbnailAspectRatio,}: {- file: stringpageMetrics: PDFPageMetricspageNumber: numberreactPdf: ReactPdfModule@@ -336,7 +334,6 @@ function PDFSidebarThumbnail({file={{name: `Page ${pageNumber}.pdf`,type: "application/pdf",- source: file,}}previewAspectRatio={thumbnailAspectRatio}previewClassName="rounded-md bg-white"@@ -348,7 +345,6 @@ function PDFSidebarThumbnail({className="flex size-full items-center justify-center [&_.react-pdf__Thumbnail__page]:!m-0 [&_.react-pdf__Thumbnail__page]:!h-auto [&_.react-pdf__Thumbnail__page]:!w-full [&_.react-pdf__Thumbnail__page]:overflow-hidden [&_canvas]:!h-auto [&_canvas]:!w-full"/>}- renderDocumentPreview={false}className="w-[92px] rounded-md border-0 shadow-xs ring-0"/>)@@ -1302,7 +1298,6 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(onClick={() => scrollToPage(pageNumber)}><PDFSidebarThumbnail- file={pdfFile}pageMetrics={metrics}pageNumber={pageNumber}reactPdf={reactPdf}diff --git a/apps/v4/content/docs/components/file-thumbnail.mdx b/apps/v4/content/docs/components/file-thumbnail.mdxindex bad1458..6f76846 100644--- a/apps/v4/content/docs/components/file-thumbnail.mdx+++ b/apps/v4/content/docs/components/file-thumbnail.mdx@@ -4,7 +4,7 @@ description: Render compact file preview images with a skeleton, fade transitioncomponent: true----File Thumbnail gives document lists, upload queues, and attachment trays a consistent preview shell. It can render plain image previews and generate first-page thumbnails for PDF, DOCX, and XLSX files when you pass a `source`, `file.source`, or `file.url`.+File Thumbnail gives document lists, upload queues, and attachment trays a consistent preview shell. Pass an image URL or renderer output from your PDF, DOCX, XLSX, or image pipeline; the component handles the thumbnail frame, loading shimmer, fade-in, and fallback state.<FileThumbnailDemo />@@ -28,12 +28,6 @@ npx shadcn@latest add https://ui.extend.ai/r/file-thumbnail.json<Steps className="mb-0 pt-2">-<Step>Install the package dependencies used by the thumbnail renderers.</Step>--```bash-npm install @extend-ai/react-docx @extend-ai/react-xlsx pdfjs-dist react-pdf-```-<Step>Copy `components/ui/file-thumbnail.tsx` from the registry item into yourproject.@@ -51,19 +45,12 @@ npm install @extend-ai/react-docx @extend-ai/react-xlsx pdfjs-dist react-pdf## Document Previews-The registry install includes the renderer dependencies used by the component:--- `react-pdf` and `pdfjs-dist` for first-page PDF thumbnails.-- `@extend-ai/react-docx` for first-page DOCX thumbnails.-- `@extend-ai/react-xlsx` for first-sheet XLSX thumbnails.--Pass a `File`, `Blob`, or URL string through `source`, `file.source`, or `file.url`. You can still override the generated preview with `previewImageUrl` or `previewContent`.+File Thumbnail does not parse documents or install renderer packages. The registry item has no npm dependencies; generate thumbnails with whichever viewer stack you already use, then pass the result through `previewImageUrl` or `previewContent`.## Useful Behaviors-- Installs the PDF, DOCX, and XLSX renderer packages through the registry item.-- Generates first-page thumbnails for image, PDF, DOCX, and XLSX sources.-- Shows a shimmering file-preview state while an external preview is being generated or loaded.+- Accepts externally generated thumbnails as an image URL or custom React content.+- Shows a shimmering file-preview state while your thumbnail generator is loading.- Fades the preview in after it loads.- Falls back to a compact file icon when no preview image is available or image loading fails.@@ -71,28 +58,22 @@ Pass a `File`, `Blob`, or URL string through `source`, `file.source`, or `file.u### FileThumbnail-The FileThumbnail component renders the reusable thumbnail shell. It accepts externally generated previews and can generate image, PDF, DOCX, and XLSX thumbnails from a source.--| Prop | Type | Default | Required |-| ----------------------- | ------------------------ | ------- | -------- |-| `file` | `ThumbnailFile \| File` | `-` | Yes |-| `className` | `string` | `-` | No |-| `previewAspectRatio` | `number` | `-` | No |-| `previewClassName` | `string` | `-` | No |-| `previewContent` | `React.ReactNode` | `-` | No |-| `previewImageUrl` | `string \| null` | `-` | No |-| `source` | `string \| File \| Blob` | `-` | No |-| `thumbnailWidth` | `number` | `-` | No |-| `generationDelayMs` | `number` | `0` | No |-| `renderDocumentPreview` | `boolean` | `true` | No |-| `isLoading` | `boolean` | `false` | No |-| `hasError` | `boolean` | `false` | No |+The FileThumbnail component renders the reusable thumbnail shell. It accepts externally generated previews from your own rendering pipeline.++| Prop | Type | Default | Required |+| -------------------- | ----------------------- | ------- | -------- |+| `file` | `ThumbnailFile \| File` | `-` | Yes |+| `className` | `string` | `-` | No |+| `previewAspectRatio` | `number` | `-` | No |+| `previewClassName` | `string` | `-` | No |+| `previewContent` | `React.ReactNode` | `-` | No |+| `previewImageUrl` | `string \| null` | `-` | No |+| `isLoading` | `boolean` | `false` | No |+| `hasError` | `boolean` | `false` | No |### ThumbnailFile-| Prop | Type | Default | Required |-| -------- | ------------------------ | ------- | -------- |-| `name` | `string` | `-` | Yes |-| `type` | `string` | `-` | Yes |-| `source` | `string \| File \| Blob` | `-` | No |-| `url` | `string` | `-` | No |+| Prop | Type | Default | Required |+| ------ | -------- | ------- | -------- |+| `name` | `string` | `-` | Yes |+| `type` | `string` | `-` | Yes |diff --git a/apps/v4/package.json b/apps/v4/package.jsonindex 99e5a1e..d70f02b 100644--- a/apps/v4/package.json+++ b/apps/v4/package.json@@ -32,6 +32,7 @@"@pierre/trees": "1.0.0-beta.4","@tabler/icons-react": "^3.31.0","@tanstack/react-virtual": "3.13.26",+ "@vercel/analytics": "^2.0.1","border-beam": "^1.0.1","class-variance-authority": "^0.7.1","clsx": "^2.1.1",diff --git a/apps/v4/public/android-chrome-192x192.png b/apps/v4/public/android-chrome-192x192.pngindex 12cf161..a165811 100644Binary files a/apps/v4/public/android-chrome-192x192.png and b/apps/v4/public/android-chrome-192x192.png differdiff --git a/apps/v4/public/android-chrome-512x512.png b/apps/v4/public/android-chrome-512x512.pngindex 5bafcab..154c653 100644Binary files a/apps/v4/public/android-chrome-512x512.png and b/apps/v4/public/android-chrome-512x512.png differdiff --git a/apps/v4/public/apple-touch-icon.png b/apps/v4/public/apple-touch-icon.pngindex 1027935..6eb6307 100644Binary files a/apps/v4/public/apple-touch-icon.png and b/apps/v4/public/apple-touch-icon.png differdiff --git a/apps/v4/public/favicon-16x16.png b/apps/v4/public/favicon-16x16.pngindex 547154b..ae2d3bc 100644Binary files a/apps/v4/public/favicon-16x16.png and b/apps/v4/public/favicon-16x16.png differdiff --git a/apps/v4/public/favicon-32x32.png b/apps/v4/public/favicon-32x32.pngindex ccf57ec..66fbdff 100644Binary files a/apps/v4/public/favicon-32x32.png and b/apps/v4/public/favicon-32x32.png differdiff --git a/apps/v4/public/favicon.ico b/apps/v4/public/favicon.icoindex 7819851..13dafb1 100644Binary files a/apps/v4/public/favicon.ico and b/apps/v4/public/favicon.ico differdiff --git a/apps/v4/public/site.webmanifest b/apps/v4/public/site.webmanifestindex c8106ee..27a37c5 100644--- a/apps/v4/public/site.webmanifest+++ b/apps/v4/public/site.webmanifest@@ -1,7 +1,17 @@{- "name": "",- "short_name": "",+ "name": "Extend UI",+ "short_name": "Extend UI","icons": [+ {+ "src": "/android-chrome-192x192.png",+ "sizes": "192x192",+ "type": "image/png"+ },+ {+ "src": "/android-chrome-512x512.png",+ "sizes": "512x512",+ "type": "image/png"+ },{"src": "/extend.svg","sizes": "any",diff --git a/apps/v4/registry.json b/apps/v4/registry.jsonindex b430385..9fe4363 100644--- a/apps/v4/registry.json+++ b/apps/v4/registry.json@@ -545,16 +545,7 @@"name": "file-thumbnail","type": "registry:ui","title": "File Thumbnail",- "description": "A compact file preview thumbnail with built-in image, PDF, DOCX, and XLSX first-page thumbnail generation.",- "dependencies": [- "@extend-ai/react-docx@^0.6.6",- "@extend-ai/react-xlsx@^0.9.2",- "@hugeicons/core-free-icons@^4.1.1",- "@hugeicons/react@^1.1.6",- "[email protected]",- "react-pdf@^10.4.1"- ],- "registryDependencies": ["utils"],+ "description": "A compact file preview thumbnail shell for externally generated images, loading states, and fallback states.","categories": ["documents"],"files": [{diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2026351..0c04705 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -60,6 +60,9 @@ importers:'@tanstack/react-virtual':specifier: 3.13.26+ '@vercel/analytics':+ specifier: ^2.0.1+ version: 2.0.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])border-beam:specifier: ^1.0.1@@ -2072,6 +2075,35 @@ packages:cpu: [x64]os: [win32]+ '@vercel/[email protected]':+ resolution: {integrity: sha512-MTQG6V9qQrt1tsDeF+2Uoo5aPjqbVPys1xvnIftXSJYG2SrwXRHnqEvVoYID7BTruDz4lCd2Z7rM1BdkUehk2g==}+ peerDependencies:+ '@remix-run/react': ^2+ '@sveltejs/kit': ^1 || ^2+ next: '>= 13'+ nuxt: '>= 3'+ react: ^18 || ^19 || ^19.0.0-rc+ svelte: '>= 4'+ vue: ^3+ vue-router: ^4+ peerDependenciesMeta:+ '@remix-run/react':+ optional: true+ '@sveltejs/kit':+ optional: true+ next:+ optional: true+ nuxt:+ optional: true+ react:+ optional: true+ svelte:+ optional: true+ vue:+ optional: true+ vue-router:+ optional: true+'@wyw-in-js/[email protected]':resolution: {integrity: sha512-5YAZMUmF+S2HaqheKfew6ybbYBMnF10PjIgI7ieyuFxCohyqJNF4xdo6oHftv2z5Z4vCQ0OZHtDOQyDImBYwmg==}engines: {node: '>=16.0.0'}@@ -6879,6 +6911,11 @@ snapshots:'@unrs/[email protected]':optional: true+ '@vercel/[email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])':+ optionalDependencies:+ next: 16.2.6(@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ react: 19.2.3+'@wyw-in-js/[email protected]':dependencies:'@babel/generator': 7.29.1