TypeScript
Fix block preview scrolling and height overflow
Andrew Luo64694803f497
diff --git a/apps/v4/components/callout.tsx b/apps/v4/components/callout.tsxindex 9629767..52c3160 100644--- a/apps/v4/components/callout.tsx+++ b/apps/v4/components/callout.tsx@@ -20,7 +20,7 @@ export function Callout({<Alertdata-variant={variant}className={cn(- "mt-6 w-auto rounded-xl border-surface bg-surface text-surface-foreground md:-mx-1 **:[code]:border",+ "mt-6 w-auto rounded-xl border-surface bg-surface text-surface-foreground md:-mx-1",className)}{...props}diff --git a/apps/v4/components/document-splitter-docs.tsx b/apps/v4/components/document-splitter-docs.tsxindex 62ba5b9..0ef4c03 100644--- a/apps/v4/components/document-splitter-docs.tsx+++ b/apps/v4/components/document-splitter-docs.tsx@@ -87,6 +87,8 @@ const DEFAULT_THUMBNAIL_SIZE = {} satisfies ThumbnailSizeconst SHEET_THUMBNAIL_WIDTH = 112const SHEET_THUMBNAIL_HEIGHT = 76+const SHEET_THUMBNAIL_PREVIEW_CLASS_NAME =+ "size-full !aspect-auto bg-white [&>img]:!h-auto [&>img]:!w-full [&>img]:object-left-top"const DEFAULT_ZOOM = 0.75const DEFAULT_PREVIEW_PAGE_COUNT = 15const DEFAULT_PREVIEW_SHEET_COUNT = 8@@ -299,7 +301,11 @@ const PageThumbnailPreview = React.memo(function PageThumbnailPreview({<FileThumbnailfile={itemFile}previewImageUrl={imageUrl}- previewClassName="h-full aspect-auto"+ previewClassName={+ labelPlacement === "bottom"+ ? SHEET_THUMBNAIL_PREVIEW_CLASS_NAME+ : "h-full aspect-auto"+ }className="size-full rounded-[inherit] border-0"isLoading={!imageUrl}/>@@ -556,7 +562,11 @@ function PageDragOverlay({<FileThumbnailfile={getItemFile(pageId)}previewImageUrl={imageUrl}- previewClassName="h-full aspect-auto"+ previewClassName={+ labelPlacement === "bottom"+ ? SHEET_THUMBNAIL_PREVIEW_CLASS_NAME+ : "h-full aspect-auto"+ }className="size-full rounded-[inherit] border-0"isLoading={!imageUrl}/>diff --git a/apps/v4/components/document-viewer-sidebar-docs.tsx b/apps/v4/components/document-viewer-sidebar-docs.tsxindex d7bf1e9..3a9c8be 100644--- a/apps/v4/components/document-viewer-sidebar-docs.tsx+++ b/apps/v4/components/document-viewer-sidebar-docs.tsx@@ -307,13 +307,33 @@ export function DocumentViewerThumbnailSidebar({inline: booleanopen: boolean}) {+ const [transitionsReady, setTransitionsReady] = React.useState(false)+ const shouldAnimateSidebar = transitionsReady && open++ React.useEffect(() => {+ let secondFrameId = 0+ const firstFrameId = window.requestAnimationFrame(() => {+ secondFrameId = window.requestAnimationFrame(() => {+ setTransitionsReady(true)+ })+ })++ return () => {+ window.cancelAnimationFrame(firstFrameId)+ window.cancelAnimationFrame(secondFrameId)+ }+ }, [])+return (<asidedata-document-thumbnail-sidebar=""data-sidebar-mode={inline ? "inline" : "overlay"}data-sidebar-open={open ? "true" : "false"}className={cn(- "absolute inset-y-0 left-0 z-30 w-40 shrink-0 overflow-hidden border-r bg-sidebar shadow-lg transition-[translate,margin-left,border-color] duration-200 ease-out",+ "absolute inset-y-0 left-0 z-30 w-40 shrink-0 overflow-hidden border-r bg-sidebar shadow-lg",+ shouldAnimateSidebar+ ? "transition-[translate,margin-left,border-color] duration-200 ease-out"+ : "transition-none",inline && "relative z-auto translate-x-0 shadow-none",open? "ml-0 translate-x-0"diff --git a/apps/v4/components/docx-editor-docs.tsx b/apps/v4/components/docx-editor-docs.tsxindex 1387bd5..401b801 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 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 thumbnailSidebarOpen = Boolean(\n sidebarOpen && (pageCount || isLoadingDocument)\n )\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(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={thumbnailSidebarOpen}\n >\n <div\n className={cn(\n "h-full overscroll-contain",\n thumbnailSidebarOpen ? "overflow-auto" : "overflow-hidden"\n )}\n >\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </>\n ) : (\n <div className="flex flex-col items-center gap-3">\n {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (\n <Button\n key={thumbnail.pageIndex}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent text-foreground",\n thumbnail.pageNumber !== activePage &&\n "text-muted-foreground"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => scrollToPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n !thumbnail.isMounted &&\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n ))}\n </div>\n )}\n </div>\n </div>\n </DocumentViewerThumbnailSidebar>\n <div\n ref={viewportRef}\n className={cn(\n "min-h-0 flex-1 overflow-auto overscroll-contain 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/pdf-block-resizable-shell.tsx b/apps/v4/components/pdf-block-resizable-shell.tsxindex 3cb3c7f..e4193fd 100644--- a/apps/v4/components/pdf-block-resizable-shell.tsx+++ b/apps/v4/components/pdf-block-resizable-shell.tsx@@ -1,6 +1,7 @@"use client"import * as React from "react"+import { useDefaultLayout } from "react-resizable-panels"import { cn } from "@/lib/utils"import { useMediaQuery } from "@/hooks/use-media-query"@@ -23,6 +24,10 @@ type PdfBlockResizableShellProps = {rightMinSize?: number}+function toPercentSize(size: number) {+ return `${size}%`+}+export function PdfBlockResizableShell({autoSaveId,className,@@ -36,35 +41,49 @@ export function PdfBlockResizableShell({rightMinSize = 24,}: PdfBlockResizableShellProps) {const isDesktop = useMediaQuery("lg")- const direction = isDesktop ? "horizontal" : "vertical"+ const orientation = isDesktop ? "horizontal" : "vertical"const resolvedLeftDefaultSize =leftDefaultSize ?? (isDesktop ? 100 - rightDefaultSize : 62)+ const layoutId = `${autoSaveId}-${orientation}`+ const leftPanelId = `${layoutId}-left`+ const rightPanelId = `${layoutId}-right`+ const panelIds = React.useMemo(+ () => [leftPanelId, rightPanelId],+ [leftPanelId, rightPanelId]+ )+ const { defaultLayout, onLayoutChanged } = useDefaultLayout({+ id: layoutId,+ panelIds,+ })return (<divclassName={cn(heightClassName,- "relative max-h-[calc(100vh-8rem)] min-h-[420px] overflow-hidden bg-background",+ "relative min-h-[420px] overflow-hidden bg-background",className)}><ResizablePanelGroup- direction={direction}- autoSaveId={`${autoSaveId}-${direction}`}+ orientation={orientation}+ defaultLayout={defaultLayout}+ onLayoutChanged={onLayoutChanged}className="h-full min-h-0"><ResizablePanel- defaultSize={resolvedLeftDefaultSize}- minSize={leftMinSize ?? (isDesktop ? 42 : 34)}+ id={leftPanelId}+ defaultSize={toPercentSize(resolvedLeftDefaultSize)}+ minSize={toPercentSize(leftMinSize ?? (isDesktop ? 42 : 34))}className="min-h-0 min-w-0 overflow-hidden">{left}</ResizablePanel><ResizableHandle className="group z-[1000]" withHandle /><ResizablePanel- defaultSize={isDesktop ? rightDefaultSize : 38}- minSize={isDesktop ? rightMinSize : 24}- maxSize={isDesktop ? rightMaxSize : 66}+ id={rightPanelId}+ defaultSize={toPercentSize(isDesktop ? rightDefaultSize : 38)}+ minSize={toPercentSize(isDesktop ? rightMinSize : 24)}+ maxSize={toPercentSize(isDesktop ? rightMaxSize : 66)}className="min-h-0 min-w-0 overflow-hidden">{right}diff --git a/apps/v4/components/pdf-dropzone-block.tsx b/apps/v4/components/pdf-dropzone-block.tsxindex 0940280..9e29d04 100644--- a/apps/v4/components/pdf-dropzone-block.tsx+++ b/apps/v4/components/pdf-dropzone-block.tsx@@ -50,7 +50,7 @@ export function PdfDropzoneBlock() {if (!pdfFile) {return (- <div className="grid h-[720px] place-items-center bg-background p-4">+ <div className="grid h-full min-h-[680px] place-items-center bg-background p-4"><FileUploadaccept={PDF_ACCEPT}acceptedFileTypes={[{ label: "PDF", icon: FileUploadIcon }]}@@ -68,7 +68,7 @@ export function PdfDropzoneBlock() {}return (- <div className="h-[720px] bg-background">+ <div className="h-full min-h-[680px] bg-background"><PDFViewerkey={pdfFile.url}file={pdfFile.url}diff --git a/apps/v4/components/pdf-viewer-blocks.tsx b/apps/v4/components/pdf-viewer-blocks.tsxindex fb0ed0f..1dbbb07 100644--- a/apps/v4/components/pdf-viewer-blocks.tsx+++ b/apps/v4/components/pdf-viewer-blocks.tsx@@ -17,7 +17,7 @@ import { HugeiconsIcon } from "@hugeicons/react"import { prepareFileTreeInput } from "@pierre/trees"import { FileTree as PierreFileTree, useFileTree } from "@pierre/trees/react"import { useVirtualizer } from "@tanstack/react-virtual"-import type { ImperativePanelHandle } from "react-resizable-panels"+import type { PanelImperativeHandle } from "react-resizable-panels"import { siteConfig } from "@/lib/config"import { cn } from "@/lib/utils"@@ -51,6 +51,17 @@ type LoadedBlockCodeSample = BlockCodeSample & {lineCount: number}+type PdfViewerBlock = {+ id: string+ title: string+ description: string+ command: string+ docsHref: string+ component: React.ComponentType+ hideHeader?: boolean+ previewHeightClassName?: string+}+type BlockViewportSize = "desktop" | "tablet" | "mobile"type BlockView = "preview" | "code"@@ -79,13 +90,13 @@ const OcrBlocksBlock = dynamic(})-const pdfViewerBlocks = [+const pdfViewerBlocks: PdfViewerBlock[] = [{id: "human-review",title: "Human Review",description:"Extraction review cards connected to source evidence in the PDF viewer.",- command: getRegistryAddCommand("human-review"),+ command: getRegistryAddCommand("human-review-block"),docsHref: "/docs/components/human-review",component: HumanReviewBlock,},@@ -104,7 +115,7 @@ const pdfViewerBlocks = [description:"Structured OCR review with typed blocks, confidence, and page overlays.",hideHeader: true,- command: getRegistryAddCommand("ocr-blocks"),+ command: getRegistryAddCommand("ocr-blocks-block"),docsHref: "/docs/components/ocr-blocks",component: OcrBlocksBlock,},@@ -123,7 +134,7 @@ const pdfViewerBlocks = [title: "Document Splits",description:"Lazy page thumbnails, draggable split groups, and PDF navigation.",- command: getRegistryAddCommand("document-splits"),+ command: getRegistryAddCommand("document-splits-block"),docsHref: "/docs/components/document-splits",component: DocumentSplitsBlock,},@@ -144,6 +155,7 @@ const pdfViewerBlocks = [command: getRegistryAddCommand("docx-editor-block"),docsHref: "/docs/components/docx-editor",component: DocxEditorBlock,+ previewHeightClassName: "h-[720px]",},]@@ -182,10 +194,12 @@ function PdfViewerBlockPreview({codeSamples[0]?.targetPath ?? null)const isMounted = useMounted()- const previewPanelRef = React.useRef<ImperativePanelHandle>(null)+ const previewPanelRef = React.useRef<PanelImperativeHandle>(null)const codePanelMountFrameRef = React.useRef<number | null>(null)const Preview = block.componentconst isDesktopViewport = useMediaQuery("(min-width: 768px)")+ const previewHeightClassName =+ block.previewHeightClassName ?? BLOCK_VIEWPORT_HEIGHT_CLASSconst scheduleCodePanelMount = React.useCallback(() => {if (hasOpenedCode || codePanelMountFrameRef.current !== null) return@@ -211,7 +225,7 @@ function PdfViewerBlockPreview({function resizeViewport(viewport: (typeof blockViewportSizes)[number]) {setView("preview")setActiveViewport(viewport.id)- previewPanelRef.current?.resize(viewport.panelSize)+ previewPanelRef.current?.resize(`${viewport.panelSize}%`)}React.useEffect(() => {@@ -336,17 +350,17 @@ function PdfViewerBlockPreview({</div><div className={view === "preview" ? "block" : "hidden"}><div- className={`relative hidden ${BLOCK_VIEWPORT_HEIGHT_CLASS} overflow-hidden rounded-xl border bg-muted/30 md:block`}+ className={`relative hidden ${previewHeightClassName} box-content overflow-hidden rounded-xl border bg-muted/30 md:block`}><div className="absolute inset-0 right-4 bg-[radial-gradient(var(--border)_1px,transparent_1px)] bg-[size:20px_20px]" /><ResizablePanelGroup- direction="horizontal"+ orientation="horizontal"className="relative z-10 h-full"><ResizablePanelref={previewPanelRef}- defaultSize={100}- minSize={30}+ defaultSize="100%"+ minSize="30%"className="min-w-0 overflow-hidden rounded-xl bg-background"><BlockPreviewSurface@@ -357,7 +371,7 @@ function PdfViewerBlockPreview({/></ResizablePanel><ResizableHandle className="relative w-3 bg-transparent p-0 after:absolute after:top-1/2 after:right-0 after:h-8 after:w-1.5 after:-translate-y-1/2 after:rounded-full after:bg-border after:transition-all after:hover:h-10" />- <ResizablePanel defaultSize={0} minSize={0} />+ <ResizablePanel defaultSize="0%" minSize="0%" /></ResizablePanelGroup></div><div className="overflow-hidden rounded-xl border bg-background md:hidden">diff --git a/apps/v4/components/ui/document-viewer-sidebar.tsx b/apps/v4/components/ui/document-viewer-sidebar.tsxindex e31ad51..a4cbcd8 100644--- a/apps/v4/components/ui/document-viewer-sidebar.tsx+++ b/apps/v4/components/ui/document-viewer-sidebar.tsx@@ -44,13 +44,33 @@ export function DocumentViewerThumbnailSidebar({inline: booleanopen: boolean}) {+ const [transitionsReady, setTransitionsReady] = React.useState(false)+ const shouldAnimateSidebar = transitionsReady && open++ React.useEffect(() => {+ let secondFrameId = 0+ const firstFrameId = window.requestAnimationFrame(() => {+ secondFrameId = window.requestAnimationFrame(() => {+ setTransitionsReady(true)+ })+ })++ return () => {+ window.cancelAnimationFrame(firstFrameId)+ window.cancelAnimationFrame(secondFrameId)+ }+ }, [])+return (<asidedata-document-thumbnail-sidebar=""data-sidebar-mode={inline ? "inline" : "overlay"}data-sidebar-open={open ? "true" : "false"}className={cn(- "absolute inset-y-0 left-0 z-30 w-40 shrink-0 overflow-hidden border-r bg-sidebar shadow-lg transition-[translate,margin-left,border-color] duration-200 ease-out",+ "absolute inset-y-0 left-0 z-30 w-40 shrink-0 overflow-hidden border-r bg-sidebar shadow-lg",+ shouldAnimateSidebar+ ? "transition-[translate,margin-left,border-color] duration-200 ease-out"+ : "transition-none",inline && "relative z-auto translate-x-0 shadow-none",open? "ml-0 translate-x-0"diff --git a/apps/v4/components/ui/docx-editor.tsx b/apps/v4/components/ui/docx-editor.tsxindex e85cd05..8cbb1bb 100644--- a/apps/v4/components/ui/docx-editor.tsx+++ b/apps/v4/components/ui/docx-editor.tsx@@ -1631,6 +1631,9 @@ function DocxEditorContent({: 0const controlsDisabled =!hasDocument || isLoadingDocument || Boolean(loadError)+ const thumbnailSidebarOpen = Boolean(+ sidebarOpen && (pageCount || isLoadingDocument)+ )const handlePageCountChange = React.useCallback((nextPageCount: number) => {setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))}, [])@@ -1891,9 +1894,14 @@ function DocxEditorContent({) : null}<DocumentViewerThumbnailSidebarinline={sidebarInline}- open={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}+ open={thumbnailSidebarOpen}>- <div className="h-full overflow-auto">+ <div+ className={cn(+ "h-full overscroll-contain",+ thumbnailSidebarOpen ? "overflow-auto" : "overflow-hidden"+ )}+ ><div className="p-4">{isLoadingDocument ? (<>@@ -1946,7 +1954,7 @@ function DocxEditorContent({<divref={viewportRef}className={cn(- "min-h-0 flex-1 overflow-auto p-4",+ "min-h-0 flex-1 overflow-auto overscroll-contain p-4",rounded && "rounded-b-lg")}style={{ backgroundColor: viewerBackgroundColor }}diff --git a/apps/v4/components/ui/resizable.tsx b/apps/v4/components/ui/resizable.tsxindex 5cf1cc3..40d4a4c 100644--- a/apps/v4/components/ui/resizable.tsx+++ b/apps/v4/components/ui/resizable.tsx@@ -1,21 +1,22 @@"use client"-import type { ComponentPropsWithRef, ReactNode } from "react"+import * as React from "react"+import type { ReactNode } from "react"import { DragDropVerticalIcon } from "@hugeicons/core-free-icons"import { HugeiconsIcon } from "@hugeicons/react"-import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels"+import * as ResizablePrimitive from "react-resizable-panels"import { cn } from "@/lib/utils"function ResizablePanelGroup({className,...props-}: ComponentPropsWithRef<typeof PanelGroup>) {+}: ResizablePrimitive.GroupProps) {return (- <PanelGroup+ <ResizablePrimitive.Groupdata-slot="resizable-panel-group"className={cn(- "flex h-full w-full data-[panel-group-direction=vertical]:flex-col",+ "flex h-full w-full aria-[orientation=vertical]:flex-col",className)}{...props}@@ -23,27 +24,36 @@ function ResizablePanelGroup({)}-function ResizablePanel({ ...props }: ComponentPropsWithRef<typeof Panel>) {- return <Panel data-slot="resizable-panel" {...props} />-}+const ResizablePanel = React.forwardRef<+ ResizablePrimitive.PanelImperativeHandle,+ ResizablePrimitive.PanelProps+>(function ResizablePanel(props, ref) {+ return (+ <ResizablePrimitive.Panel+ data-slot="resizable-panel"+ panelRef={ref}+ {...props}+ />+ )+})function ResizableHandle({withHandle,className,...props-}: ComponentPropsWithRef<typeof PanelResizeHandle> & {+}: ResizablePrimitive.SeparatorProps & {withHandle?: boolean | ReactNode}) {return (- <PanelResizeHandle+ <ResizablePrimitive.Separatordata-slot="resizable-handle"className={cn("flex items-center justify-center","relative isolate w-px bg-border","after:absolute after:inset-y-0 after:left-1/2 after:z-20 after:w-3 after:-translate-x-1/2","focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:outline-hidden",- "data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full [&[data-panel-group-direction=vertical]>div]:rotate-90",- "data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-3 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2",+ "aria-[orientation=horizontal]:h-px aria-[orientation=horizontal]:w-full [&[aria-orientation=horizontal]>div]:rotate-90",+ "aria-[orientation=horizontal]:after:left-0 aria-[orientation=horizontal]:after:h-3 aria-[orientation=horizontal]:after:w-full aria-[orientation=horizontal]:after:translate-x-0 aria-[orientation=horizontal]:after:-translate-y-1/2",className)}{...props}@@ -56,7 +66,7 @@ function ResizableHandle({) : (withHandle))}- </PanelResizeHandle>+ </ResizablePrimitive.Separator>)}diff --git a/apps/v4/content/docs/components/csv-tsv-viewer.mdx b/apps/v4/content/docs/components/csv-tsv-viewer.mdxindex 7a375a1..d4afdca 100644--- a/apps/v4/content/docs/components/csv-tsv-viewer.mdx+++ b/apps/v4/content/docs/components/csv-tsv-viewer.mdx@@ -17,6 +17,23 @@ the last child of your app's `<body>` before using the component:<div id="portal" className="fixed top-0 left-0 z-[9999]" />```+<Callout variant="info" title="Next.js SSR">+Glide Data Grid uses browser-only APIs. If you see SSR errors, render the CSV+Viewer through `next/dynamic` with `ssr: false`.++```tsx+"use client"++import dynamic from "next/dynamic"++const CsvViewer = dynamic(+ () => import("@/components/ui/csv-viewer").then((mod) => mod.CsvViewer),+ { ssr: false }+)+```++</Callout>+<CodeTabs><TabsList>diff --git a/apps/v4/content/docs/components/docx-viewer.mdx b/apps/v4/content/docs/components/docx-viewer.mdxindex f35737a..cb7287a 100644--- a/apps/v4/content/docs/components/docx-viewer.mdx+++ b/apps/v4/content/docs/components/docx-viewer.mdx@@ -64,7 +64,7 @@ The DocxViewerPreview component renders a DOCX file with upload, theme, and zoom| ----------------------------- | --------------------------- | ------- | -------- || `className` | `string` | `-` | No || `defaultIsDark` | `boolean` | `false` | No |-| `defaultThumbnailSidebarOpen` | `boolean` | `true` | No |+| `defaultThumbnailSidebarOpen` | `boolean` | `false` | No || `fileName` | `string` | `-` | No || `isDark` | `boolean` | `-` | No || `onIsDarkChange` | `(isDark: boolean) => void` | `-` | No |diff --git a/apps/v4/content/docs/components/file-thumbnail.mdx b/apps/v4/content/docs/components/file-thumbnail.mdxindex 6f76846..70d265c 100644--- a/apps/v4/content/docs/components/file-thumbnail.mdx+++ b/apps/v4/content/docs/components/file-thumbnail.mdx@@ -52,7 +52,7 @@ File Thumbnail does not parse documents or install renderer packages. The regist- 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.+- Falls back to a blank muted preview surface when no preview image is available or image loading fails.## API Referencediff --git a/apps/v4/content/docs/components/human-review.mdx b/apps/v4/content/docs/components/human-review.mdxindex f0b5c0d..0761c3c 100644--- a/apps/v4/content/docs/components/human-review.mdx+++ b/apps/v4/content/docs/components/human-review.mdx@@ -19,6 +19,24 @@ the last child of your app's `<body>` before using the component:<div id="portal" className="fixed top-0 left-0 z-[9999]" />```+<Callout variant="info" title="Next.js SSR">+Glide Data Grid uses browser-only APIs. If you see SSR errors, render Human+Review through `next/dynamic` with `ssr: false`.++```tsx+"use client"++import dynamic from "next/dynamic"++const HumanReviewPanel = dynamic(+ () =>+ import("@/components/ui/human-review").then((mod) => mod.HumanReviewPanel),+ { ssr: false }+)+```++</Callout>+<CodeTabs><TabsList>diff --git a/apps/v4/content/docs/components/pdf-viewer.mdx b/apps/v4/content/docs/components/pdf-viewer.mdxindex 3fa29bf..f6dae35 100644--- a/apps/v4/content/docs/components/pdf-viewer.mdx+++ b/apps/v4/content/docs/components/pdf-viewer.mdx@@ -70,7 +70,7 @@ The PDFViewer component renders a scrollable PDF surface with toolbar controls,| ----------------------------- | ------------------------------------------------------------------------- | ------- | -------- || `file` | `string` | `-` | No || `className` | `string` | `-` | No |-| `defaultThumbnailSidebarOpen` | `boolean` | `true` | No |+| `defaultThumbnailSidebarOpen` | `boolean` | `false` | No || `defaultZoom` | `number` | `0.75` | No || `pageWidth` | `number` | `612` | No || `pageHeight` | `number` | `792` | No |diff --git a/apps/v4/package.json b/apps/v4/package.jsonindex d70f02b..17cca04 100644--- a/apps/v4/package.json+++ b/apps/v4/package.json@@ -25,7 +25,7 @@"@extend-ai/react-docx": "^0.6.6","@extend-ai/react-xlsx": "^0.9.2","@glideapps/glide-data-grid": "6.0.4-alpha24",- "@hugeicons/core-free-icons": "^4.1.1",+ "@hugeicons/core-free-icons": "^4.2.0","@hugeicons/react": "^1.1.6","@paper-design/shaders-react": "^0.0.76","@pierre/diffs": "^1.1.22",@@ -53,7 +53,7 @@"react-dom": "19.2.3","react-markdown": "^10.1.0","react-pdf": "^10.4.1",- "react-resizable-panels": "^3.0.5",+ "react-resizable-panels": "^4.11.2","react-responsive-carousel": "^3.2.23","rehype-pretty-code": "^0.14.1","rehype-raw": "^7.0.0",diff --git a/apps/v4/registry.json b/apps/v4/registry.jsonindex 9fe4363..185f598 100644--- a/apps/v4/registry.json+++ b/apps/v4/registry.json@@ -37,7 +37,7 @@"description": "A vertically stacked set of expandable content panels.","dependencies": ["@base-ui/react@^1.4.1",- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6"],"registryDependencies": ["utils"],@@ -84,7 +84,7 @@"description": "An autocomplete input built on Base UI primitives.","dependencies": ["@base-ui/react@^1.4.1",- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6"],"registryDependencies": ["input", "scroll-area", "utils"],@@ -121,7 +121,7 @@"description": "Navigation breadcrumbs for page hierarchy.","dependencies": ["@base-ui/react@^1.4.1",- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6"],"registryDependencies": ["utils"],@@ -187,7 +187,7 @@"title": "Command","description": "A command menu surface powered by cmdk.","dependencies": [- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6","cmdk@^1.1.1"],@@ -207,7 +207,7 @@"description": "An accessible modal dialog built on Base UI.","dependencies": ["@base-ui/react@^1.4.1",- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6"],"registryDependencies": ["button", "scroll-area", "utils"],@@ -226,7 +226,7 @@"description": "A dropdown menu built on Base UI menu primitives.","dependencies": ["@base-ui/react@^1.4.1",- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6"],"registryDependencies": ["utils"],@@ -322,7 +322,7 @@"description": "A select control built on Base UI.","dependencies": ["@base-ui/react@^1.4.1",- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6","class-variance-authority@^0.7.1"],@@ -357,7 +357,7 @@"description": "A side sheet built on Base UI dialog primitives.","dependencies": ["@base-ui/react@^1.4.1",- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6"],"registryDependencies": ["button", "scroll-area", "utils"],@@ -376,7 +376,7 @@"description": "A responsive application sidebar with menu, rail, and provider primitives.","dependencies": ["@base-ui/react@^1.4.1",- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6","class-variance-authority@^0.7.1"],@@ -417,7 +417,7 @@"title": "Sonner","description": "A themed toast provider for Sonner.","dependencies": [- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6","sonner@^2.0.0"@@ -436,7 +436,7 @@"title": "Spinner","description": "A compact loading spinner using Hugeicons.","dependencies": [- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6"],"registryDependencies": ["utils"],@@ -484,9 +484,9 @@"title": "Resizable","description": "Resizable panel primitives using react-resizable-panels.","dependencies": [- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6",- "react-resizable-panels@^3.0.5"+ "react-resizable-panels@^4.11.2"],"registryDependencies": ["utils"],"files": [@@ -523,7 +523,7 @@"title": "File Upload","description": "A drag-and-drop file upload surface with accepted file type icons and a compact file list.","dependencies": [- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6","border-beam@^1.0.1"],@@ -561,7 +561,7 @@"title": "PDF Viewer","description": "A PDF viewer with page virtualization, thumbnails, search, zoom, rotation, upload, and page overlay hooks.","dependencies": [- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6","react-pdf@^10.4.1"@@ -594,7 +594,7 @@"description": "A DOCX viewer with upload, zoom, theme controls, cached source loading, and read-only rendering.","dependencies": ["@extend-ai/react-docx@^0.6.6",- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6"],"registryDependencies": [@@ -624,7 +624,7 @@"description": "An experimental DOCX editor with a Word-style toolbar, page thumbnails, import, export, and live document mutation.","dependencies": ["@extend-ai/react-docx@^0.6.6",- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6"],"registryDependencies": [@@ -656,7 +656,7 @@"description": "An XLSX viewer with workbook loading, thumbnails, sheet tabs, upload, zoom, and theme controls.","dependencies": ["@extend-ai/react-xlsx@^0.9.2",- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6"],"registryDependencies": [@@ -686,7 +686,7 @@"description": "An experimental XLSX editor with formula input, undo and redo, sheet controls, export, and live workbook mutation.","dependencies": ["@extend-ai/react-xlsx@^0.9.2",- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6"],"registryDependencies": [@@ -717,7 +717,7 @@"description": "A CSV and TSV viewer with parsing, upload, zoom, theme-aware grid rendering, and Glide Data Grid.","dependencies": ["@glideapps/[email protected]",- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6","papaparse@^5.5.3"],@@ -744,7 +744,7 @@"type": "registry:block","title": "PDF Dropzone","description": "A PDF-only upload dropzone that opens the dropped file in the shared PDF viewer.",- "dependencies": ["@hugeicons/core-free-icons@^4.1.1"],+ "dependencies": ["@hugeicons/core-free-icons@^4.2.0"],"registryDependencies": ["https://ui.extend.ai/r/file-upload.json","https://ui.extend.ai/r/pdf-viewer.json"@@ -760,26 +760,40 @@},{"name": "ocr-blocks",- "type": "registry:block",+ "type": "registry:ui","title": "OCR Blocks",- "description": "A structured OCR review block with confidence cards and PDF region overlays.",+ "description": "A structured OCR review panel with typed blocks and confidence cards.","dependencies": [- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6","react-markdown@^10.1.0"],+ "registryDependencies": ["scroll-area", "utils"],+ "categories": ["documents"],+ "files": [+ {+ "path": "registry/new-york-v4/ui/ocr-blocks.tsx",+ "type": "registry:ui",+ "target": "@ui/ocr-blocks.tsx"+ }+ ]+ },+ {+ "name": "ocr-blocks-block",+ "type": "registry:block",+ "title": "OCR Blocks",+ "description": "A structured OCR review block with confidence cards and PDF region overlays.","registryDependencies": [+ "https://ui.extend.ai/r/ocr-blocks.json","https://ui.extend.ai/r/pdf-block-resizable-shell.json",- "https://ui.extend.ai/r/pdf-viewer.json",- "scroll-area",- "utils"+ "https://ui.extend.ai/r/pdf-viewer.json"],"categories": ["documents", "blocks"],"files": [{- "path": "registry/new-york-v4/blocks/ocr-blocks.tsx",+ "path": "registry/new-york-v4/blocks/ocr-blocks-block.tsx","type": "registry:component",- "target": "@components/blocks/ocr-blocks.tsx"+ "target": "@components/blocks/ocr-blocks-block.tsx"}]},@@ -789,7 +803,7 @@"title": "E-Signature","description": "A PDF signature review block with field overlays and signing actions.","dependencies": [- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6","pdf-lib@^1.17.1","signature_pad@^5.1.3"@@ -813,60 +827,94 @@},{"name": "human-review",- "type": "registry:block",+ "type": "registry:ui","title": "Human Review",- "description": "A human-in-the-loop extraction review block linked to source PDF evidence.",+ "description": "A human-in-the-loop extraction review panel with editable fields and a JSON diff.","dependencies": ["@glideapps/[email protected]",- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6","@pierre/diffs@^1.1.22"],"registryDependencies": ["button","input",- "https://ui.extend.ai/r/pdf-block-resizable-shell.json",- "https://ui.extend.ai/r/pdf-viewer.json","scroll-area","tabs","tooltip","utils"],+ "categories": ["documents"],+ "files": [+ {+ "path": "registry/new-york-v4/ui/human-review.tsx",+ "type": "registry:ui",+ "target": "@ui/human-review.tsx"+ }+ ]+ },+ {+ "name": "human-review-block",+ "type": "registry:block",+ "title": "Human Review",+ "description": "A human-in-the-loop extraction review block linked to source PDF evidence.",+ "registryDependencies": [+ "https://ui.extend.ai/r/human-review.json",+ "https://ui.extend.ai/r/pdf-block-resizable-shell.json",+ "https://ui.extend.ai/r/pdf-viewer.json"+ ],"categories": ["documents", "blocks"],"files": [{- "path": "registry/new-york-v4/blocks/human-review.tsx",+ "path": "registry/new-york-v4/blocks/human-review-block.tsx","type": "registry:component",- "target": "@components/blocks/human-review.tsx"+ "target": "@components/blocks/human-review-block.tsx"}]},{"name": "document-splits",- "type": "registry:block",+ "type": "registry:ui","title": "Document Splits",- "description": "A split-group review block for organizing pages into output documents.",+ "description": "A split-group review panel for organizing pages into output documents.","dependencies": ["@dnd-kit/core@^6.3.1","@dnd-kit/sortable@^10.0.0","@dnd-kit/utilities@^3.2.2",- "@hugeicons/core-free-icons@^4.1.1",+ "@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6"],"registryDependencies": ["button","https://ui.extend.ai/r/file-thumbnail.json",- "https://ui.extend.ai/r/pdf-block-resizable-shell.json",- "https://ui.extend.ai/r/pdf-viewer.json","scroll-area","utils"],+ "categories": ["documents"],+ "files": [+ {+ "path": "registry/new-york-v4/ui/document-splits.tsx",+ "type": "registry:ui",+ "target": "@ui/document-splits.tsx"+ }+ ]+ },+ {+ "name": "document-splits-block",+ "type": "registry:block",+ "title": "Document Splits",+ "description": "A split-group review block for organizing PDF pages into output documents.",+ "registryDependencies": [+ "https://ui.extend.ai/r/document-splits.json",+ "https://ui.extend.ai/r/pdf-block-resizable-shell.json",+ "https://ui.extend.ai/r/pdf-viewer.json"+ ],"categories": ["documents", "blocks"],"files": [{- "path": "registry/new-york-v4/blocks/document-splits.tsx",+ "path": "registry/new-york-v4/blocks/document-splits-block.tsx","type": "registry:component",- "target": "@components/blocks/document-splits.tsx"+ "target": "@components/blocks/document-splits-block.tsx"}]},diff --git a/apps/v4/registry/new-york-v4/blocks/document-splits-block.tsx b/apps/v4/registry/new-york-v4/blocks/document-splits-block.tsxnew file mode 100644index 0000000..17428f7--- /dev/null+++ b/apps/v4/registry/new-york-v4/blocks/document-splits-block.tsx@@ -0,0 +1,98 @@+"use client"++import * as React from "react"++import { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"+import { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"++import {+ createInitialSplits,+ DocumentSplits,+ INITIAL_SPLITS,+ type DocumentSplit,+ type DocumentSplitPageId,+} from "@/components/ui/document-splits"++export function DocumentSplitsBlock({+ file,+ thumbnailImages,+}: {+ file?: string+ thumbnailImages?: Record<DocumentSplitPageId, string>+}) {+ const [splits, setSplits] = React.useState<DocumentSplit[]>(INITIAL_SPLITS)+ const [pdfFile, setPdfFile] = React.useState(file)+ const viewerRef = React.useRef<PDFViewerHandle>(null)+ const uploadedPdfUrlRef = React.useRef<string | null>(null)++ React.useEffect(() => {+ setPdfFile(file)+ }, [file])++ React.useEffect(() => {+ return () => {+ if (uploadedPdfUrlRef.current) {+ URL.revokeObjectURL(uploadedPdfUrlRef.current)+ }+ }+ }, [])++ const handlePdfUpload = React.useCallback((uploadedFile: File) => {+ const nextUrl = URL.createObjectURL(uploadedFile)++ if (uploadedPdfUrlRef.current) {+ URL.revokeObjectURL(uploadedPdfUrlRef.current)+ }++ uploadedPdfUrlRef.current = nextUrl+ setPdfFile(nextUrl)+ }, [])++ const handleDocumentLoadSuccess = React.useCallback((pageCount: number) => {+ setSplits(createInitialSplits(pageCount))+ }, [])++ const handleSelectPage = React.useCallback((pageNumber: number) => {+ viewerRef.current?.scrollToPage(pageNumber, {+ block: "start",+ behavior: "auto",+ })+ }, [])++ return (+ <PdfBlockResizableShell+ autoSaveId="pdf-block-document-splits"+ heightClassName="h-[720px]"+ rightDefaultSize={50}+ rightMaxSize={66}+ rightMinSize={30}+ left={+ <PDFViewer+ ref={viewerRef}+ file={pdfFile}+ defaultZoom={0.75}+ onDocumentLoadSuccess={handleDocumentLoadSuccess}+ onPdfUpload={handlePdfUpload}+ />+ }+ right={+ <div className="flex min-h-0 flex-col bg-background">+ <div className="border-b px-4 py-3">+ <h3 className="text-sm font-medium">Document splits</h3>+ <p className="text-xs text-muted-foreground">+ Drag pages between split groups and reorder output documents.+ </p>+ </div>+ <DocumentSplits+ className="min-h-0 flex-1"+ splits={splits}+ thumbnailImages={thumbnailImages}+ withFrameDivider={false}+ onSelectPage={handleSelectPage}+ onSplitsChange={setSplits}+ />+ </div>+ }+ />+ )+}diff --git a/apps/v4/registry/new-york-v4/blocks/human-review-block.tsx b/apps/v4/registry/new-york-v4/blocks/human-review-block.tsxnew file mode 100644index 0000000..70adfc3--- /dev/null+++ b/apps/v4/registry/new-york-v4/blocks/human-review-block.tsx@@ -0,0 +1,130 @@+"use client"++import * as React from "react"++import { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"+import { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"++import {+ findReviewField,+ getMetadataLocation,+ getReviewFieldLocation,+ getReviewLocationKey,+ HumanReviewHighlight,+ HumanReviewPanel,+ REVIEW_FIELDS,+ type HumanReviewTheme,+ type JsonValue,+ type ReviewField,+ type ReviewLocation,+ type ReviewMetadataEntry,+} from "@/components/ui/human-review"++const DEFAULT_ZOOM = 0.75++export function HumanReviewBlock({+ file,+ fields = REVIEW_FIELDS,+ className,+ metadata,+ resolveArrayItemMetadataPath,+ resolveLocation,+ theme,+}: {+ file?: string+ fields?: ReviewField[]+ className?: string+ metadata?: Record<string, ReviewMetadataEntry>+ resolveArrayItemMetadataPath?: (+ metadataPath: string,+ rowIndex: number,+ rowValue: JsonValue+ ) => string | undefined+ resolveLocation?: (metadataPath: string) => ReviewLocation | undefined+ theme?: HumanReviewTheme+}) {+ const [activeFieldKey, setActiveFieldKey] = React.useState(fields[0]?.key)+ const [hoverLocation, setHoverLocation] =+ React.useState<ReviewLocation | null>(null)+ const viewerRef = React.useRef<PDFViewerHandle>(null)+ const hoverLocationKeyRef = React.useRef<string | null>(null)+ const resolveFieldLocation = React.useCallback(+ (metadataPath: string) =>+ resolveLocation?.(metadataPath) ??+ getMetadataLocation(metadata, metadataPath),+ [metadata, resolveLocation]+ )+ const activeField = findReviewField(fields, activeFieldKey) ?? fields[0]+ const activeLocation =+ hoverLocation ?? getReviewFieldLocation(activeField, resolveFieldLocation)++ React.useEffect(() => {+ if (activeFieldKey || !fields[0]) return+ setActiveFieldKey(fields[0].key)+ }, [activeFieldKey, fields])++ const focusField = React.useCallback(+ (field: ReviewField) => {+ if (field.key === activeFieldKey) return++ setActiveFieldKey(field.key)++ const location = getReviewFieldLocation(field, resolveFieldLocation)+ if (location) {+ viewerRef.current?.scrollToPageArea(location.page, location.area)+ }+ },+ [activeFieldKey, resolveFieldLocation]+ )+ const handleLocationHover = React.useCallback((location?: ReviewLocation) => {+ setHoverLocation(location ?? null)++ const locationKey = getReviewLocationKey(location)+ if (!location) {+ hoverLocationKeyRef.current = null+ return+ }+ if (locationKey === hoverLocationKeyRef.current) return++ hoverLocationKeyRef.current = locationKey+ viewerRef.current?.scrollToPageArea(location.page, location.area, {+ behavior: "auto",+ })+ }, [])++ return (+ <PdfBlockResizableShell+ autoSaveId="pdf-block-human-review"+ className={className}+ rightDefaultSize={42}+ rightMaxSize={60}+ rightMinSize={30}+ left={+ <PDFViewer+ ref={viewerRef}+ file={file}+ defaultZoom={DEFAULT_ZOOM}+ renderPageOverlay={({ pageNumber }) =>+ activeLocation?.page === pageNumber ? (+ <HumanReviewHighlight location={activeLocation} />+ ) : null+ }+ />+ }+ right={+ <aside className="min-h-0 bg-background">+ <HumanReviewPanel+ fields={fields}+ activeFieldKey={activeField?.key}+ className="h-full min-h-0"+ theme={theme}+ onFieldFocus={focusField}+ onLocationHover={handleLocationHover}+ resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}+ resolveLocation={resolveFieldLocation}+ />+ </aside>+ }+ />+ )+}diff --git a/apps/v4/registry/new-york-v4/blocks/ocr-blocks-block.tsx b/apps/v4/registry/new-york-v4/blocks/ocr-blocks-block.tsxnew file mode 100644index 0000000..0279dda--- /dev/null+++ b/apps/v4/registry/new-york-v4/blocks/ocr-blocks-block.tsx@@ -0,0 +1,82 @@+"use client"++import * as React from "react"++import { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"+import { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"++import {+ ATTENTION_OCR_OUTPUT,+ blockToArea,+ getOcrBlocks,+ OcrBlockOverlay,+ OcrBlocksPanel,+ PDF_URL,+ type OcrBlock,+ type ParsedOcrOutput,+} from "@/components/ui/ocr-blocks"++export function OcrBlocksBlock({+ file = PDF_URL,+ output = ATTENTION_OCR_OUTPUT,+}: {+ file?: string+ output?: ParsedOcrOutput+}) {+ const blocks = React.useMemo(() => getOcrBlocks(output), [output])+ const [activeBlockId, setActiveBlockId] = React.useState(blocks[0]?.id)+ const viewerRef = React.useRef<PDFViewerHandle>(null)+ const activeBlock = blocks.find((block) => block.id === activeBlockId)++ React.useEffect(() => {+ if (!blocks.length || blocks.some((block) => block.id === activeBlockId)) {+ return+ }++ setActiveBlockId(blocks[0].id)+ }, [activeBlockId, blocks])++ const focusBlock = React.useCallback((block: OcrBlock) => {+ const area = blockToArea(block)++ setActiveBlockId(block.id)+ viewerRef.current?.scrollToPageArea(block.page, {+ left: Number.parseFloat(String(area.left)),+ top: Number.parseFloat(String(area.top)),+ width: Number.parseFloat(String(area.width)),+ height: Number.parseFloat(String(area.height)),+ })+ }, [])++ return (+ <PdfBlockResizableShell+ autoSaveId="pdf-block-ocr"+ left={+ <PDFViewer+ ref={viewerRef}+ file={file}+ defaultZoom={0.75}+ renderPageOverlay={({ pageNumber }) =>+ blocks+ .filter((block) => block.page === pageNumber)+ .map((block) => (+ <OcrBlockOverlay+ key={block.id}+ block={block}+ isActive={block.id === activeBlock?.id}+ />+ ))+ }+ />+ }+ right={+ <OcrBlocksPanel+ activeBlockId={activeBlock?.id}+ blocks={blocks}+ className="h-full"+ onBlockFocus={focusBlock}+ />+ }+ />+ )+}diff --git a/apps/v4/registry/new-york-v4/blocks/pdf-dropzone.tsx b/apps/v4/registry/new-york-v4/blocks/pdf-dropzone.tsxindex e078824..ad9c8a9 100644--- a/apps/v4/registry/new-york-v4/blocks/pdf-dropzone.tsx+++ b/apps/v4/registry/new-york-v4/blocks/pdf-dropzone.tsx@@ -42,7 +42,7 @@ export function PdfDropzoneBlock() {if (!pdfFile) {return (- <div className="grid h-[720px] place-items-center bg-background p-4">+ <div className="grid h-full min-h-[680px] place-items-center bg-background p-4"><FileUploadaccept={PDF_ACCEPT}acceptedFileTypes={[{ label: "PDF", icon: FileUploadIcon }]}@@ -60,7 +60,7 @@ export function PdfDropzoneBlock() {}return (- <div className="h-[720px] bg-background">+ <div className="h-full min-h-[680px] bg-background"><PDFViewerkey={pdfFile.url}file={pdfFile.url}diff --git a/apps/v4/registry/new-york-v4/blocks/document-splits.tsx b/apps/v4/registry/new-york-v4/ui/document-splits.tsxsimilarity index 88%rename from apps/v4/registry/new-york-v4/blocks/document-splits.tsxrename to apps/v4/registry/new-york-v4/ui/document-splits.tsxindex 6a3109b..61c1632 100644--- a/apps/v4/registry/new-york-v4/blocks/document-splits.tsx+++ b/apps/v4/registry/new-york-v4/ui/document-splits.tsx@@ -31,8 +31,6 @@ import { HugeiconsIcon } from "@hugeicons/react"import { cn } from "@/lib/utils"import { FileThumbnail } from "@/components/ui/file-thumbnail"-import { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"-import { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"import { Button } from "@/registry/new-york-v4/ui/button"import { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"@@ -77,7 +75,7 @@ const splitterCollisionDetection: CollisionDetection = (args) => {return closestCenter(args)}-const INITIAL_SPLITS: DocumentSplit[] = [+export const INITIAL_SPLITS: DocumentSplit[] = [{id: "split-1",title: "Abstract and intro",@@ -95,7 +93,7 @@ const INITIAL_SPLITS: DocumentSplit[] = [},]-function createInitialSplits(pageCount: number) {+export function createInitialSplits(pageCount: number) {if (pageCount <= 0) return INITIAL_SPLITSconst pages = Array.from(@@ -719,87 +717,3 @@ export function DocumentSplits({</aside>)}--export function DocumentSplitsBlock({- file,- thumbnailImages,-}: {- file?: string- thumbnailImages?: Record<PageId, string>-}) {- const [splits, setSplits] = React.useState<DocumentSplit[]>(INITIAL_SPLITS)- const [pdfFile, setPdfFile] = React.useState(file)- const viewerRef = React.useRef<PDFViewerHandle>(null)- const uploadedPdfUrlRef = React.useRef<string | null>(null)-- React.useEffect(() => {- setPdfFile(file)- }, [file])-- React.useEffect(() => {- return () => {- if (uploadedPdfUrlRef.current) {- URL.revokeObjectURL(uploadedPdfUrlRef.current)- }- }- }, [])-- const handlePdfUpload = React.useCallback((uploadedFile: File) => {- const nextUrl = URL.createObjectURL(uploadedFile)-- if (uploadedPdfUrlRef.current) {- URL.revokeObjectURL(uploadedPdfUrlRef.current)- }-- uploadedPdfUrlRef.current = nextUrl- setPdfFile(nextUrl)- }, [])-- const handleDocumentLoadSuccess = React.useCallback((pageCount: number) => {- setSplits(createInitialSplits(pageCount))- }, [])-- const handleSelectPage = React.useCallback((pageNumber: number) => {- viewerRef.current?.scrollToPage(pageNumber, {- block: "start",- behavior: "auto",- })- }, [])-- return (- <PdfBlockResizableShell- autoSaveId="pdf-block-document-splits"- heightClassName="h-[720px]"- rightDefaultSize={50}- rightMaxSize={66}- rightMinSize={30}- left={- <PDFViewer- ref={viewerRef}- file={pdfFile}- defaultZoom={0.75}- onDocumentLoadSuccess={handleDocumentLoadSuccess}- onPdfUpload={handlePdfUpload}- />- }- right={- <div className="flex min-h-0 flex-col bg-background">- <div className="border-b px-4 py-3">- <h3 className="text-sm font-medium">Document splits</h3>- <p className="text-xs text-muted-foreground">- Drag pages between split groups and reorder output documents.- </p>- </div>- <DocumentSplits- className="min-h-0 flex-1"- splits={splits}- thumbnailImages={thumbnailImages}- withFrameDivider={false}- onSelectPage={handleSelectPage}- onSplitsChange={setSplits}- />- </div>- }- />- )-}diff --git a/apps/v4/registry/new-york-v4/blocks/human-review.tsx b/apps/v4/registry/new-york-v4/ui/human-review.tsxsimilarity index 94%rename from apps/v4/registry/new-york-v4/blocks/human-review.tsxrename to apps/v4/registry/new-york-v4/ui/human-review.tsxindex 1723c88..55ee61b 100644--- a/apps/v4/registry/new-york-v4/blocks/human-review.tsx+++ b/apps/v4/registry/new-york-v4/ui/human-review.tsx@@ -34,8 +34,6 @@ import { MultiFileDiff, Virtualizer } from "@pierre/diffs/react"import { flushSync } from "react-dom"import { cn } from "@/lib/utils"-import { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"-import { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"import { Button } from "@/registry/new-york-v4/ui/button"import { Input } from "@/registry/new-york-v4/ui/input"import { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"@@ -232,7 +230,7 @@ function useHumanReviewGridTheme() {)}-const REVIEW_FIELDS: ReviewField[] = [+export const REVIEW_FIELDS: ReviewField[] = [{key: "statement_period",schema: {@@ -396,7 +394,7 @@ function getCitationLocation(}}-function getMetadataLocation(+export function getMetadataLocation(metadata: Record<string, ReviewMetadataEntry> | undefined,metadataPath: string | undefined) {@@ -409,7 +407,7 @@ function getMetadataLocation(return citation ? getCitationLocation(citation) : undefined}-function getReviewFieldLocation(+export function getReviewFieldLocation(field: ReviewField | undefined,resolveLocation?: (metadataPath: string) => ReviewLocation | undefined) {@@ -422,7 +420,7 @@ function getReviewFieldLocation()}-function getReviewLocationKey(location: ReviewLocation | undefined) {+export function getReviewLocationKey(location: ReviewLocation | undefined) {if (!location) return nullconst { area } = location@@ -508,7 +506,7 @@ function countReviewFields(fields: ReviewField[]): number {}, 0)}-function findReviewField(+export function findReviewField(fields: ReviewField[],fieldKey: string | undefined): ReviewField | undefined {@@ -1913,7 +1911,11 @@ function HumanReviewFieldCardBase({)}-function HumanReviewHighlight({ location }: { location: ReviewLocation }) {+export function HumanReviewHighlight({+ location,+}: {+ location: ReviewLocation+}) {const area = location.areareturn (@@ -2093,110 +2095,3 @@ export function HumanReviewPanel({</TooltipProvider>)}--export function HumanReviewBlock({- file,- fields = REVIEW_FIELDS,- className,- metadata,- resolveArrayItemMetadataPath,- resolveLocation,- theme,-}: {- file?: string- fields?: ReviewField[]- className?: string- metadata?: Record<string, ReviewMetadataEntry>- resolveArrayItemMetadataPath?: (- metadataPath: string,- rowIndex: number,- rowValue: JsonValue- ) => string | undefined- resolveLocation?: (metadataPath: string) => ReviewLocation | undefined- theme?: HumanReviewTheme-}) {- const [activeFieldKey, setActiveFieldKey] = React.useState(fields[0]?.key)- const [hoverLocation, setHoverLocation] =- React.useState<ReviewLocation | null>(null)- const viewerRef = React.useRef<PDFViewerHandle>(null)- const hoverLocationKeyRef = React.useRef<string | null>(null)- const resolveFieldLocation = React.useCallback(- (metadataPath: string) =>- resolveLocation?.(metadataPath) ??- getMetadataLocation(metadata, metadataPath),- [metadata, resolveLocation]- )- const activeField = findReviewField(fields, activeFieldKey) ?? fields[0]- const activeLocation =- hoverLocation ?? getReviewFieldLocation(activeField, resolveFieldLocation)-- React.useEffect(() => {- if (activeFieldKey || !fields[0]) return- setActiveFieldKey(fields[0].key)- }, [activeFieldKey, fields])-- const focusField = React.useCallback(- (field: ReviewField) => {- if (field.key === activeFieldKey) return-- setActiveFieldKey(field.key)-- const location = getReviewFieldLocation(field, resolveFieldLocation)- if (location) {- viewerRef.current?.scrollToPageArea(location.page, location.area)- }- },- [activeFieldKey, resolveFieldLocation]- )- const handleLocationHover = React.useCallback((location?: ReviewLocation) => {- setHoverLocation(location ?? null)-- const locationKey = getReviewLocationKey(location)- if (!location) {- hoverLocationKeyRef.current = null- return- }- if (locationKey === hoverLocationKeyRef.current) return-- hoverLocationKeyRef.current = locationKey- viewerRef.current?.scrollToPageArea(location.page, location.area, {- behavior: "auto",- })- }, [])-- return (- <PdfBlockResizableShell- autoSaveId="pdf-block-human-review"- className={className}- rightDefaultSize={42}- rightMaxSize={60}- rightMinSize={30}- left={- <PDFViewer- ref={viewerRef}- file={file}- defaultZoom={DEFAULT_ZOOM}- renderPageOverlay={({ pageNumber }) =>- activeLocation?.page === pageNumber ? (- <HumanReviewHighlight location={activeLocation} />- ) : null- }- />- }- right={- <aside className="min-h-0 bg-background">- <HumanReviewPanel- fields={fields}- activeFieldKey={activeField?.key}- className="h-full min-h-0"- theme={theme}- onFieldFocus={focusField}- onLocationHover={handleLocationHover}- resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}- resolveLocation={resolveFieldLocation}- />- </aside>- }- />- )-}diff --git a/apps/v4/registry/new-york-v4/blocks/ocr-blocks.tsx b/apps/v4/registry/new-york-v4/ui/ocr-blocks.tsxsimilarity index 98%rename from apps/v4/registry/new-york-v4/blocks/ocr-blocks.tsxrename to apps/v4/registry/new-york-v4/ui/ocr-blocks.tsxindex 6ac8d48..7517295 100644--- a/apps/v4/registry/new-york-v4/blocks/ocr-blocks.tsx+++ b/apps/v4/registry/new-york-v4/ui/ocr-blocks.tsx@@ -19,23 +19,21 @@ import rehypeSanitize, { defaultSchema } from "rehype-sanitize"import remarkGfm from "remark-gfm"import { cn } from "@/lib/utils"-import { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"-import { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"import { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"-type Point = {+export type Point = {x: numbery: number}-type BoundingBox = {+export type BoundingBox = {left: numbertop: numberright: numberbottom: number}-type OcrBlockType =+export type OcrBlockType =| "heading"| "paragraph"| "list"@@ -45,7 +43,7 @@ type OcrBlockType =| "footer"| "page_number"-type ParsedOcrBlock = {+export type ParsedOcrBlock = {id: stringtype: stringcontent: string@@ -63,13 +61,13 @@ type ParsedOcrBlock = {boundingBox?: BoundingBox}-type ParsedOcrOutput = {+export type ParsedOcrOutput = {chunks: {blocks: ParsedOcrBlock[]}[]}-type OcrBlock = {+export type OcrBlock = {id: stringtype: OcrBlockTypetext: string@@ -81,7 +79,7 @@ type OcrBlock = {boundingBox?: BoundingBox}-const PDF_URL = "/samples/attention-rotated.pdf"+export const PDF_URL = "/samples/attention-rotated.pdf"const OCR_BLOCK_ROW_ESTIMATE = 132const OCR_BLOCK_LIST_PADDING = 12const OCR_MARKDOWN_SCHEMA = {@@ -105,7 +103,7 @@ const OCR_MARKDOWN_REMARK_PLUGINS: NonNullable<> = [remarkGfm]const OCR_MARKDOWN_FIGURE_CAPTION_PATTERN = /<\/?caption>/gi-const ATTENTION_OCR_OUTPUT = {+export const ATTENTION_OCR_OUTPUT = {chunks: [{blocks: [@@ -8021,7 +8019,7 @@ function getBlockType(block: ParsedOcrBlock): OcrBlockType | undefined {}}-function getOcrBlocks(output: ParsedOcrOutput): OcrBlock[] {+export function getOcrBlocks(output: ParsedOcrOutput): OcrBlock[] {return output.chunks.flatMap((chunk) =>chunk.blocks.flatMap((block) => {const type = getBlockType(block)@@ -8065,7 +8063,7 @@ function getBoundingBox(block: OcrBlock): BoundingBox {return { left, top, right, bottom }}-function blockToArea(block: OcrBlock): React.CSSProperties {+export function blockToArea(block: OcrBlock): React.CSSProperties {const { left, top, right, bottom } = getBoundingBox(block)return {@@ -8179,18 +8177,46 @@ function OcrBlockButton({)}-export function OcrBlocksBlock({- file = PDF_URL,- output = ATTENTION_OCR_OUTPUT,+export function OcrBlockOverlay({+ block,+ isActive,+}: {+ block: OcrBlock+ isActive?: boolean+}) {+ const style = BLOCK_STYLES[block.type]++ return (+ <div+ className={cn(+ "pointer-events-none absolute z-10 border",+ isActive ? style.overlay : style.mutedOverlay+ )}+ style={blockToArea(block)}+ />+ )+}++export function OcrBlocksPanel({+ activeBlockId,+ blocks,+ className,+ onBlockFocus,}: {- file?: string- output?: ParsedOcrOutput+ activeBlockId?: string+ blocks: OcrBlock[]+ className?: string+ onBlockFocus?: (block: OcrBlock) => void}) {- const blocks = React.useMemo(() => getOcrBlocks(output), [output])const scrollViewportRef = React.useRef<HTMLDivElement | null>(null)- const [activeBlockId, setActiveBlockId] = React.useState(blocks[0]?.id)- const viewerRef = React.useRef<PDFViewerHandle>(null)- const activeBlock = blocks.find((block) => block.id === activeBlockId)+ const [localActiveBlockId, setLocalActiveBlockId] = React.useState(+ activeBlockId ?? blocks[0]?.id+ )+ const firstBlock = blocks[0]+ const activeBlock =+ blocks.find(+ (block) => block.id === (activeBlockId ?? localActiveBlockId)+ ) ?? firstBlockconst virtualizer = useVirtualizer({count: blocks.length,estimateSize: () => OCR_BLOCK_ROW_ESTIMATE,@@ -8199,106 +8225,81 @@ export function OcrBlocksBlock({overscan: 8,})+ const focusBlock = React.useCallback(+ (block: OcrBlock) => {+ setLocalActiveBlockId(block.id)+ onBlockFocus?.(block)+ },+ [onBlockFocus]+ )+React.useEffect(() => {- if (!blocks.length || blocks.some((block) => block.id === activeBlockId)) {+ if (!firstBlock) return+ if (+ activeBlockId ||+ blocks.some((block) => block.id === localActiveBlockId)+ ) {return}- setActiveBlockId(blocks[0].id)- }, [activeBlockId, blocks])-- const focusBlock = React.useCallback((block: OcrBlock) => {- const area = blockToArea(block)-- setActiveBlockId(block.id)- viewerRef.current?.scrollToPageArea(block.page, {- left: Number.parseFloat(String(area.left)),- top: Number.parseFloat(String(area.top)),- width: Number.parseFloat(String(area.width)),- height: Number.parseFloat(String(area.height)),- })- }, [])+ setLocalActiveBlockId(firstBlock.id)+ }, [activeBlockId, blocks, firstBlock, localActiveBlockId])return (- <PdfBlockResizableShell- autoSaveId="pdf-block-ocr"- left={- <PDFViewer- ref={viewerRef}- file={file}- defaultZoom={0.75}- renderPageOverlay={({ pageNumber }) =>- blocks- .filter((block) => block.page === pageNumber)- .map((block) => {- const style = BLOCK_STYLES[block.type]-- return (- <div- key={block.id}- className={cn(- "pointer-events-none absolute z-10 border",- block.id === activeBlock?.id- ? style.overlay- : style.mutedOverlay- )}- style={blockToArea(block)}- />- )- })- }- />- }- right={- <aside className="min-h-0 bg-background">- <ScrollArea- className="h-full"- scrollFade- viewportRef={scrollViewportRef}+ <aside+ className={cn("flex h-[420px] min-h-0 flex-col bg-background", className)}+ >+ <ScrollArea+ className="min-h-0 flex-1"+ scrollFade+ viewportRef={scrollViewportRef}+ >+ {blocks.length ? (+ <div+ className="relative"+ style={{+ height: virtualizer.getTotalSize() + OCR_BLOCK_LIST_PADDING * 2,+ }}>- {blocks.length ? (- <div- className="relative"- style={{- height:- virtualizer.getTotalSize() + OCR_BLOCK_LIST_PADDING * 2,- }}- >- {virtualizer.getVirtualItems().map((virtualRow) => {- const block = blocks[virtualRow.index]- if (!block) return null+ {virtualizer.getVirtualItems().map((virtualRow) => {+ const block = blocks[virtualRow.index]+ if (!block) return null- return (- <div- key={virtualRow.key}- ref={virtualizer.measureElement}- data-index={virtualRow.index}- className="absolute top-0 right-3 left-3"- style={{- transform: `translateY(${- virtualRow.start + OCR_BLOCK_LIST_PADDING- }px)`,- }}- >- <OcrBlockButton- block={block}- isActive={block.id === activeBlock?.id}- onFocusBlock={focusBlock}- />- </div>- )- })}- </div>- ) : (- <div className="p-3">- <div className="rounded-lg border bg-muted/30 p-3 text-sm text-muted-foreground">- No OCR blocks found.+ return (+ <div+ key={virtualRow.key}+ ref={virtualizer.measureElement}+ data-index={virtualRow.index}+ className="absolute top-0 right-3 left-3"+ style={{+ transform: `translateY(${+ virtualRow.start + OCR_BLOCK_LIST_PADDING+ }px)`,+ }}+ >+ <OcrBlockButton+ block={block}+ isActive={block.id === activeBlock?.id}+ onFocusBlock={focusBlock}+ /></div>- </div>- )}- </ScrollArea>- </aside>- }- />+ )+ })}+ </div>+ ) : (+ <div className="p-3">+ <div className="rounded-lg border bg-muted/30 p-3 text-sm text-muted-foreground">+ No OCR blocks found.+ </div>+ </div>+ )}+ </ScrollArea>+ </aside>+ )+}++export function OcrBlocks() {+ return (+ <OcrBlocksPanel blocks={getOcrBlocks(ATTENTION_OCR_OUTPUT).slice(0, 12)} />)}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 0c04705..bb6c59f 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -40,8 +40,8 @@ importers:specifier: 6.0.4-alpha24version: 6.0.4-alpha24([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])'@hugeicons/core-free-icons':- specifier: ^4.1.1- version: 4.1.1+ specifier: ^4.2.0+ version: 4.2.0'@hugeicons/react':specifier: ^1.1.6version: 1.1.6([email protected])@@ -124,8 +124,8 @@ importers:specifier: ^10.4.1react-resizable-panels:- specifier: ^3.0.5+ specifier: ^4.11.2react-responsive-carousel:specifier: ^3.2.23version: 3.2.23@@ -893,8 +893,8 @@ packages:peerDependencies:hono: ^4- '@hugeicons/[email protected]':- resolution: {integrity: sha512-teqIBvPHl90ygIwKyJwTxOH8aNp1X1PjDTcMvLkEwdPxPD+8mssrZ5kXKIAJJFYPsz69a8LYQY0UPid4PAdavg==}+ '@hugeicons/[email protected]':+ resolution: {integrity: sha512-V1G/Ph9TbmEow+pKnupZRWQjdORR/TGGr3JVRZOWkomdJ/5N6GgLuKPgBDs7G0kZ0//9LL34AGOUzWe3K+umNA==}'@hugeicons/[email protected]':resolution: {integrity: sha512-c2LhXJMAW5wN1pC/smBXG0YPqUON6ceR/ZdXHCjEI9KvB+hjtqYjmzIxok5hAQOeXGz0WtORgCQMzqewFKAZwg==}@@ -4385,11 +4385,11 @@ packages:'@types/react':optional: true- resolution: {integrity: sha512-b3qKHQ3MLqOgSS+FRYKapNkJZf5EQzuf6+RLiq1/IlTHw99YrZ2NJZLk4hQIzTnnIkRg2LUqyVinu6YWWpUYew==}+ resolution: {integrity: sha512-+kfFbDZ8mygc7g0vxOcDzCVGuwiIUOnILqPoUHo6/uP+Mmyx6HzZU+kj1aOPDlktXuobYbr6BtQekvJwHRX4Eg==}peerDependencies:- react: ^16.14.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc- react-dom: ^16.14.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc+ react: ^18.0.0 || ^19.0.0+ react-dom: ^18.0.0 || ^19.0.0resolution: {integrity: sha512-pqJLsBaKHWJhw/ItODgbVoziR2z4lpcJg+YwmRlSk4rKH32VE633mAtZZ9kDXjy4wFO+pgUZmDKPsPe1fPmHCg==}@@ -5848,7 +5848,7 @@ snapshots:dependencies:hono: 4.11.7- '@hugeicons/[email protected]': {}+ '@hugeicons/[email protected]': {}'@hugeicons/[email protected]([email protected])':dependencies:@@ -9655,7 +9655,7 @@ snapshots:optionalDependencies:'@types/react': 19.2.2dependencies:react: 19.2.3react-dom: 19.2.3([email protected])