TypeScript
Add paragraph style preview tooltip to docx editor
Andrew Luo96c88cfcf9f8
diff --git a/apps/v4/components/docx-editor-docs.tsx b/apps/v4/components/docx-editor-docs.tsxindex 5691e04..68ca5e4 100644--- a/apps/v4/components/docx-editor-docs.tsx+++ b/apps/v4/components/docx-editor-docs.tsx@@ -90,7 +90,7 @@ export function DocxEditorExample() {}`const docxEditorSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n DocxEditorViewer,\n paragraphLetterheadFloatSideAtNodeIndex,\n useDocxBorders,\n useDocxDocumentTheme,\n useDocxEditor,\n useDocxLineSpacing,\n useDocxPageLayout,\n useDocxParagraphStyles,\n useDocxTrackChanges,\n useDocxViewerThumbnails,\n type DocxBorderContext,\n type DocxBorderPreset,\n type DocxDocumentTheme,\n type DocxEditorController,\n} from "@extend-ai/react-docx"\nimport {\n ArrowExpandDiagonal01Icon,\n ArrowExpandDiagonal02Icon,\n BorderAll01Icon,\n BorderBottom01Icon,\n BorderHorizontalIcon,\n BorderInnerIcon,\n BorderLeft01Icon,\n BorderNone01Icon,\n BorderRight01Icon,\n BorderTop01Icon,\n BorderVerticalIcon,\n ColumnsThreeCogIcon,\n Download01Icon,\n EditOffIcon,\n FileDiffIcon,\n HighlighterIcon,\n ImageAdd01Icon,\n LeftToRightListBulletIcon,\n LeftToRightListNumberIcon,\n LineIcon,\n Link02Icon,\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n Redo02Icon,\n SidebarLeftIcon,\n Sun03Icon,\n TableIcon,\n TextAlignCenterIcon,\n TextAlignJustifyLeftIcon,\n TextAlignLeft01Icon,\n TextAlignRight01Icon,\n TextBoldIcon,\n TextColorIcon,\n TextItalicIcon,\n TextStrikethroughIcon,\n TextSubscriptIcon,\n TextSuperscriptIcon,\n TextUnderlineIcon,\n Undo02Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { useTheme } from "next-themes"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/ui/document-viewer-sidebar"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { Input } from "@/components/ui/input"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/registry/new-york-v4/ui/dropdown-menu"\nimport { Separator } from "@/registry/new-york-v4/ui/separator"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_SOURCE_CACHE_LIMIT = 3\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst DOCX_EDITOR_DEFAULT_ZOOM_SCALE = 75\nconst ZOOM_OPTIONS = [50, 75, 90, 100, 110, 125, 150, 175, 200] as const\nconst FONT_FAMILIES = [\n "Calibri",\n "Arial",\n "Times New Roman",\n "Georgia",\n "Helvetica",\n "Courier New",\n] as const\nconst FONT_SIZE_OPTIONS = [\n 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48,\n] as const\nconst LINE_SPACING_OPTIONS = [1, 1.15, 1.2, 1.5, 2, 2.5, 3] as const\nconst FALLBACK_PARAGRAPH_STYLE_OPTIONS = [\n { id: "Normal", name: "Body" },\n { id: "Heading1", name: "Heading 1" },\n { id: "Heading2", name: "Heading 2" },\n { id: "Heading3", name: "Heading 3" },\n] as const\nconst HIGHLIGHT_COLORS = [\n { label: "Yellow", value: "yellow", color: "#fff59d" },\n { label: "Green", value: "green", color: "#bbf7d0" },\n { label: "Cyan", value: "cyan", color: "#a5f3fc" },\n { label: "Magenta", value: "magenta", color: "#f5d0fe" },\n { label: "Red", value: "red", color: "#fecaca" },\n { label: "Blue", value: "blue", color: "#bfdbfe" },\n] as const\nconst DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\n\nconst docxFileCache = new Map<string, File>()\nconst docxFilePromiseCache = new Map<string, Promise<File>>()\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n}\n\ntype BorderControlOption = {\n id: DocxBorderPreset\n label: string\n contexts?: DocxBorderContext[]\n separatorBefore?: boolean\n}\n\nconst BORDER_CONTROL_OPTIONS: BorderControlOption[] = [\n { id: "bottom", label: "Bottom Border" },\n { id: "top", label: "Top Border" },\n { id: "left", label: "Left Border" },\n { id: "right", label: "Right Border" },\n { id: "none", label: "No Border", separatorBefore: true },\n { id: "all", label: "All Borders" },\n { id: "outside", label: "Outside Borders" },\n { id: "inside", label: "Inside Borders", contexts: ["table"] },\n {\n id: "inside-horizontal",\n label: "Inside Horizontal Border",\n contexts: ["table"],\n },\n {\n id: "inside-vertical",\n label: "Inside Vertical Border",\n contexts: ["table"],\n },\n {\n id: "diagonal-down",\n label: "Diagonal Down Border",\n contexts: ["table"],\n separatorBefore: true,\n },\n { id: "diagonal-up", label: "Diagonal Up Border", contexts: ["table"] },\n { id: "horizontal-line", label: "Horizontal Line", separatorBefore: true },\n]\n\nfunction borderControlOptionIcon(optionId: DocxBorderPreset) {\n switch (optionId) {\n case "bottom":\n return BorderBottom01Icon\n case "top":\n return BorderTop01Icon\n case "left":\n return BorderLeft01Icon\n case "right":\n return BorderRight01Icon\n case "none":\n return BorderNone01Icon\n case "inside":\n return BorderInnerIcon\n case "inside-horizontal":\n return BorderHorizontalIcon\n case "inside-vertical":\n return BorderVerticalIcon\n case "diagonal-down":\n return ArrowExpandDiagonal01Icon\n case "diagonal-up":\n return ArrowExpandDiagonal02Icon\n case "horizontal-line":\n return LineIcon\n default:\n return BorderAll01Icon\n }\n}\n\nfunction getDocumentCacheKey(url: string, fileName?: string) {\n return `${url.split("?")[0] ?? url}::${fileName ?? ""}`\n}\n\nfunction rememberDocxFile(cacheKey: string, file: File) {\n if (docxFileCache.has(cacheKey)) {\n docxFileCache.delete(cacheKey)\n }\n\n docxFileCache.set(cacheKey, file)\n\n while (docxFileCache.size > DOCX_SOURCE_CACHE_LIMIT) {\n const oldestKey = docxFileCache.keys().next().value\n if (!oldestKey) break\n docxFileCache.delete(oldestKey)\n }\n}\n\nasync function loadCachedDocxFile(\n url: string,\n displayFileName: string,\n cacheKey: string\n): Promise<File> {\n const cachedFile = docxFileCache.get(cacheKey)\n if (cachedFile) return cachedFile\n\n const pendingRequest = docxFilePromiseCache.get(cacheKey)\n if (pendingRequest) return pendingRequest\n\n const nextRequest = fetch(url)\n .then(async (response) => {\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n const docxFile = new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n\n rememberDocxFile(cacheKey, docxFile)\n return docxFile\n })\n .finally(() => {\n docxFilePromiseCache.delete(cacheKey)\n })\n\n docxFilePromiseCache.set(cacheKey, nextRequest)\n return nextRequest\n}\n\nfunction formatDocumentName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "document.docx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction getNextZoomScale(currentZoomScale: number, direction: 1 | -1) {\n const currentIndex = ZOOM_OPTIONS.indexOf(\n currentZoomScale as (typeof ZOOM_OPTIONS)[number]\n )\n let fallbackIndex = -1\n\n if (direction > 0) {\n fallbackIndex = ZOOM_OPTIONS.findIndex((value) => value > currentZoomScale)\n } else {\n for (let index = ZOOM_OPTIONS.length - 1; index >= 0; index -= 1) {\n if (ZOOM_OPTIONS[index] < currentZoomScale) {\n fallbackIndex = index\n break\n }\n }\n }\n\n const resolvedIndex = currentIndex >= 0 ? currentIndex : fallbackIndex\n if (resolvedIndex < 0) return currentZoomScale\n\n const nextIndex = Math.min(\n Math.max(resolvedIndex + direction, 0),\n ZOOM_OPTIONS.length - 1\n )\n\n return ZOOM_OPTIONS[nextIndex] ?? currentZoomScale\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\n}\n\nfunction useDocumentNightRenderPreference() {\n const [nightRenderEnabled, setNightRenderEnabled] = React.useState(false)\n const [nightRenderPrefLoaded, setNightRenderPrefLoaded] =\n React.useState(false)\n\n React.useEffect(() => {\n const storedValue = window.localStorage.getItem("docx-editor-night-render")\n setNightRenderEnabled(storedValue === "true")\n setNightRenderPrefLoaded(true)\n }, [])\n\n const updateNightRenderEnabled = React.useCallback((checked: boolean) => {\n setNightRenderEnabled(checked)\n window.localStorage.setItem("docx-editor-night-render", String(checked))\n }, [])\n\n return {\n nightRenderEnabled,\n nightRenderPrefLoaded,\n setNightRenderEnabled: updateNightRenderEnabled,\n }\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === "string" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes("padding"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\n}\n\nfunction normalizeHexColor(value?: string, fallback = "#111827") {\n if (!value) return fallback\n\n const trimmed = value.trim()\n const threeDigit = /^#([0-9a-f]{3})$/i.exec(trimmed)\n if (threeDigit?.[1]) {\n const [red, green, blue] = threeDigit[1].split("")\n return `#${red}${red}${green}${green}${blue}${blue}`.toLowerCase()\n }\n\n const sixDigit = /^#([0-9a-f]{6})$/i.exec(trimmed)\n if (sixDigit?.[1]) {\n return `#${sixDigit[1].toLowerCase()}`\n }\n\n return fallback\n}\n\nfunction parseToolbarSectionColumns(\n sectionPropertiesXml?: string\n): { count: number; gapPx: number } | undefined {\n if (!sectionPropertiesXml) return undefined\n\n const columnsTag = sectionPropertiesXml.match(/<w:cols\\b[^>]*\\/?>/i)?.[0]\n if (!columnsTag) return undefined\n\n const countRaw = columnsTag.match(/\\bw:num="(\\d+)"/i)?.[1]\n const count = countRaw ? Number(countRaw) : 1\n if (!Number.isFinite(count) || count <= 1) return undefined\n\n const gapRaw = columnsTag.match(/\\bw:space="(\\d+)"/i)?.[1]\n const gapTwips = gapRaw ? Number(gapRaw) : 720\n const gapPx = Math.max(0, Math.round((gapTwips * 96) / 1440))\n\n return {\n count: Math.max(2, Math.round(count)),\n gapPx,\n }\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction EditorLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction ToolbarIconButton({\n active,\n children,\n label,\n ...props\n}: React.ComponentProps<typeof Button> & {\n active?: boolean\n label: string\n}) {\n return (\n <ToolbarTooltip label={label}>\n <Button\n type="button"\n variant={active ? "secondary" : "ghost"}\n size="icon-sm"\n aria-label={label}\n data-pressed={active ? "" : undefined}\n {...props}\n >\n {children}\n </Button>\n </ToolbarTooltip>\n )\n}\n\nfunction ToolbarColorInput({\n color,\n disabled,\n icon,\n label,\n onChange,\n}: {\n color: string\n disabled?: boolean\n icon: typeof TextColorIcon\n label: string\n onChange: (color: string) => void\n}) {\n return (\n <ToolbarTooltip label={label}>\n <label\n className={cn(\n "relative inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-lg border border-transparent text-foreground transition-colors hover:bg-accent",\n disabled && "pointer-events-none opacity-64"\n )}\n aria-label={label}\n >\n <HugeiconsIcon icon={icon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: color }}\n />\n <input\n type="color"\n aria-label={label}\n disabled={disabled}\n value={color}\n className="sr-only"\n onChange={(event) => onChange(event.target.value)}\n />\n </label>\n </ToolbarTooltip>\n )\n}\n\nfunction DocxSidebarThumbnail({\n canvasRef,\n displayFileName,\n hasError,\n isActive,\n isLoading,\n pageNumber,\n pixelHeightPx,\n pixelWidthPx,\n previewAspectRatio,\n}: {\n canvasRef: React.RefCallback<HTMLCanvasElement>\n displayFileName: string\n hasError: boolean\n isActive: boolean\n isLoading: boolean\n pageNumber: number\n pixelHeightPx: number\n pixelWidthPx: number\n previewAspectRatio: number\n}) {\n return (\n <FileThumbnail\n file={{\n name: `${displayFileName} page ${pageNumber}`,\n type: DOCX_MIME_TYPE,\n }}\n previewAspectRatio={previewAspectRatio}\n previewClassName="bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n renderDocumentPreview={false}\n isLoading={isLoading}\n hasError={hasError}\n showMetadata={false}\n className={cn(\n "w-full rounded-sm border shadow-xs transition-[border-color,box-shadow] duration-150",\n isActive && "border-primary shadow-sm"\n )}\n />\n )\n}\n\nfunction DocxEditorToolbar({\n activePage,\n controlsDisabled,\n editor,\n isReadOnly,\n onImageUploadClick,\n onIsReadOnlyChange,\n onOpenLinkEditor,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showNightRenderToggle,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n editor: DocxEditorController\n isReadOnly: boolean\n onImageUploadClick: () => void\n onIsReadOnlyChange: (checked: boolean) => void\n onOpenLinkEditor: () => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showNightRenderToggle: boolean\n zoomScale: number\n}) {\n const { documentTheme, setDocumentTheme } = useDocxDocumentTheme(editor)\n const { layout: pageLayout } = useDocxPageLayout(editor)\n const { paragraphStyles, selectedParagraphStyleId, setParagraphStyle } =\n useDocxParagraphStyles(editor)\n const { lineSpacing, setLineSpacing } = useDocxLineSpacing(editor)\n const { borderContext, activeBorderPresets, applyBorderPreset } =\n useDocxBorders(editor)\n const { showTrackedChanges, setShowTrackedChanges } =\n useDocxTrackChanges(editor)\n const selectedRunStyle = editor.selectedRunStyle\n const selectedParagraph = editor.selectedParagraph\n const paragraphStyleOptions =\n paragraphStyles.length > 0\n ? paragraphStyles\n : [...FALLBACK_PARAGRAPH_STYLE_OPTIONS]\n const selectedParagraphStyleValue =\n selectedParagraphStyleId ??\n paragraphStyleOptions.find((option) => "isDefault" in option)?.id ??\n paragraphStyleOptions[0]?.id ??\n "Normal"\n const selectedLineSpacingValue = React.useMemo(() => {\n const current = Number.isFinite(lineSpacing.multiple)\n ? lineSpacing.multiple\n : 1\n const nearest = LINE_SPACING_OPTIONS.reduce((closest, candidate) => {\n return Math.abs(candidate - current) < Math.abs(closest - current)\n ? candidate\n : closest\n }, LINE_SPACING_OPTIONS[0])\n return String(nearest)\n }, [lineSpacing.multiple])\n const textColorValue = normalizeHexColor(selectedRunStyle?.color)\n const highlightColor =\n HIGHLIGHT_COLORS.find(\n (option) => option.value === selectedRunStyle?.highlight\n )?.color ?? "#fff59d"\n const activeNodeIndex =\n editor.selection.kind === "paragraph"\n ? editor.selection.nodeIndex\n : editor.selection.tableIndex\n const letterheadColumns =\n editor.selection.kind === "paragraph" &&\n paragraphLetterheadFloatSideAtNodeIndex(\n editor.model.nodes,\n editor.selection.nodeIndex\n )\n ? { count: 2, gapPx: 28 }\n : undefined\n const sections = editor.model.metadata.sections ?? []\n const activeSection = sections\n .filter((section) => section.startNodeIndex <= activeNodeIndex)\n .at(-1)\n const activeColumns =\n letterheadColumns ??\n parseToolbarSectionColumns(activeSection?.sectionPropertiesXml) ??\n parseToolbarSectionColumns(editor.model.metadata.sectionPropertiesXml) ??\n pageLayout.columns\n const activeBorderControlOptions = BORDER_CONTROL_OPTIONS.filter(\n (option) => activeBorderPresets[option.id]\n )\n const borderTriggerLabel =\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].label\n : "Borders"\n const borderTriggerIcon = borderControlOptionIcon(\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].id\n : "all"\n )\n const canEdit = !controlsDisabled && !isReadOnly\n const canZoomIn = zoomScale < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n const canZoomOut = zoomScale > ZOOM_OPTIONS[0]\n\n const preserveTextSelection = React.useCallback(\n (event: React.MouseEvent<HTMLElement> | React.PointerEvent<HTMLElement>) =>\n event.preventDefault(),\n []\n )\n\n return (\n <div className="border-b bg-background">\n <TooltipProvider>\n <div className="flex min-h-11 items-center gap-2 overflow-x-auto overflow-y-hidden border-b px-3">\n <ToolbarIconButton\n label="Toggle pages"\n disabled={controlsDisabled}\n onClick={onToggleSidebar}\n >\n <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />\n </ToolbarIconButton>\n <div className="min-w-28 text-sm whitespace-nowrap text-primary">\n Page {pageCount ? activePage : 1} of {pageCount || "-"}\n </div>\n <div className="min-w-0 flex-1" />\n {showNightRenderToggle ? (\n <>\n <ToolbarIconButton\n label={\n documentTheme === "dark"\n ? "Use light document"\n : "Use dark document"\n }\n disabled={controlsDisabled}\n onClick={() =>\n setDocumentTheme(documentTheme === "dark" ? "light" : "dark")\n }\n >\n <HugeiconsIcon\n icon={documentTheme === "dark" ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </ToolbarIconButton>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <ToolbarIconButton\n label="Show tracked changes"\n active={showTrackedChanges}\n disabled={controlsDisabled}\n onClick={() => setShowTrackedChanges(!showTrackedChanges)}\n >\n <HugeiconsIcon icon={FileDiffIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label={isReadOnly ? "Switch to edit mode" : "Switch to read-only"}\n active={isReadOnly}\n disabled={controlsDisabled}\n onClick={() => onIsReadOnlyChange(!isReadOnly)}\n >\n <HugeiconsIcon icon={EditOffIcon} className="size-4" />\n </ToolbarIconButton>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <ToolbarIconButton\n label="Import DOCX"\n disabled={editor.isImporting}\n onClick={onUploadClick}\n >\n {editor.isImporting ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n )}\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Download DOCX"\n disabled={controlsDisabled || editor.isImporting}\n onClick={editor.exportDocx}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex min-h-12 flex-wrap items-center gap-2 border-b px-3 py-2">\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Undo"\n disabled={!editor.canUndo || isReadOnly}\n onClick={editor.undo}\n >\n <HugeiconsIcon icon={Undo02Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Redo"\n disabled={!editor.canRedo || isReadOnly}\n onClick={editor.redo}\n >\n <HugeiconsIcon icon={Redo02Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <Select\n value={selectedParagraphStyleValue}\n onValueChange={(value) => {\n if (value) {\n setParagraphStyle(value)\n }\n }}\n disabled={!canEdit}\n >\n <SelectTrigger\n size="sm"\n className="w-[136px] min-w-[136px]"\n aria-label="Paragraph style"\n >\n <SelectValue placeholder="Style" />\n </SelectTrigger>\n <SelectContent align="start" className="z-[100010]">\n {paragraphStyleOptions.map((option) => (\n <SelectItem key={option.id} value={option.id}>\n {option.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={selectedRunStyle?.fontFamily ?? "Calibri"}\n onValueChange={(value) => {\n if (value) {\n editor.setFontFamily(value)\n }\n }}\n disabled={!canEdit}\n >\n <SelectTrigger\n size="sm"\n className="w-[156px] min-w-[156px]"\n aria-label="Font family"\n >\n <SelectValue placeholder="Font" />\n </SelectTrigger>\n <SelectContent align="start" className="z-[100010]">\n {FONT_FAMILIES.map((fontFamily) => (\n <SelectItem key={fontFamily} value={fontFamily}>\n <span style={{ fontFamily }}>{fontFamily}</span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={String(Math.round(selectedRunStyle?.fontSizePt ?? 12))}\n onValueChange={(value) => {\n const nextSize = Number(value)\n if (Number.isFinite(nextSize)) {\n editor.setFontSize(nextSize)\n }\n }}\n disabled={!canEdit}\n >\n <SelectTrigger\n size="sm"\n className="w-[86px] min-w-[86px]"\n aria-label="Font size"\n >\n <SelectValue placeholder="Size" />\n </SelectTrigger>\n <SelectContent align="start" className="z-[100010]">\n {FONT_SIZE_OPTIONS.map((size) => (\n <SelectItem key={size} value={String(size)}>\n {size} pt\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={selectedLineSpacingValue}\n onValueChange={(value) => {\n const nextSpacing = Number(value)\n if (Number.isFinite(nextSpacing)) {\n setLineSpacing(nextSpacing)\n }\n }}\n disabled={!canEdit}\n >\n <SelectTrigger\n size="sm"\n className="w-[94px] min-w-[94px]"\n aria-label="Line spacing"\n >\n <SelectValue placeholder="Spacing" />\n </SelectTrigger>\n <SelectContent align="start" className="z-[100010]">\n {LINE_SPACING_OPTIONS.map((spacing) => (\n <SelectItem key={spacing} value={String(spacing)}>\n {spacing}x\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Bold"\n active={Boolean(selectedRunStyle?.bold)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleBold}\n >\n <HugeiconsIcon icon={TextBoldIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Italic"\n active={Boolean(selectedRunStyle?.italic)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleItalic}\n >\n <HugeiconsIcon icon={TextItalicIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Underline"\n active={Boolean(selectedRunStyle?.underline)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleUnderline}\n >\n <HugeiconsIcon icon={TextUnderlineIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Strikethrough"\n active={Boolean(selectedRunStyle?.strike)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleStrike}\n >\n <HugeiconsIcon icon={TextStrikethroughIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Superscript"\n active={selectedRunStyle?.verticalAlign === "superscript"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleSuperscript}\n >\n <HugeiconsIcon icon={TextSuperscriptIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Subscript"\n active={selectedRunStyle?.verticalAlign === "subscript"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleSubscript}\n >\n <HugeiconsIcon icon={TextSubscriptIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarColorInput\n label="Text color"\n icon={TextColorIcon}\n color={textColorValue}\n disabled={!canEdit}\n onChange={(color) =>\n editor.setTextColor(normalizeHexColor(color))\n }\n />\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={!canEdit}\n aria-label="Highlight color"\n className="relative"\n >\n <HugeiconsIcon icon={HighlighterIcon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: highlightColor }}\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="z-[100010] w-44">\n {HIGHLIGHT_COLORS.map((option) => (\n <DropdownMenuCheckboxItem\n key={option.value}\n checked={selectedRunStyle?.highlight === option.value}\n onCheckedChange={() => editor.setHighlight(option.value)}\n >\n <span\n className="size-3 rounded-full border"\n style={{ backgroundColor: option.color }}\n />\n {option.label}\n </DropdownMenuCheckboxItem>\n ))}\n <DropdownMenuSeparator />\n <DropdownMenuCheckboxItem\n checked={!selectedRunStyle?.highlight}\n onCheckedChange={() => editor.setHighlight(undefined)}\n >\n No highlight\n </DropdownMenuCheckboxItem>\n </DropdownMenuContent>\n </DropdownMenu>\n <ToolbarIconButton\n label="Link"\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={onOpenLinkEditor}\n >\n <HugeiconsIcon icon={Link02Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Align left"\n active={\n selectedParagraph?.style?.align === "left" ||\n !selectedParagraph?.style?.align\n }\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("left")}\n >\n <HugeiconsIcon icon={TextAlignLeft01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Align center"\n active={selectedParagraph?.style?.align === "center"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("center")}\n >\n <HugeiconsIcon icon={TextAlignCenterIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Align right"\n active={selectedParagraph?.style?.align === "right"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("right")}\n >\n <HugeiconsIcon icon={TextAlignRight01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Justify"\n active={selectedParagraph?.style?.align === "justify"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("justify")}\n >\n <HugeiconsIcon\n icon={TextAlignJustifyLeftIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Bulleted list"\n active={editor.hasUnorderedList}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.toggleList("unordered")}\n >\n <HugeiconsIcon\n icon={LeftToRightListBulletIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Numbered list"\n active={editor.hasOrderedList}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.toggleList("ordered")}\n >\n <HugeiconsIcon\n icon={LeftToRightListNumberIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="sm"\n disabled={!canEdit}\n className="h-7 gap-1 px-2 shadow-none"\n >\n <HugeiconsIcon icon={borderTriggerIcon} className="size-4" />\n {borderTriggerLabel}\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="z-[100010] w-56">\n {BORDER_CONTROL_OPTIONS.map((option) => {\n const enabledForContext =\n !option.contexts || option.contexts.includes(borderContext)\n const BorderOptionIcon = borderControlOptionIcon(option.id)\n\n return (\n <React.Fragment key={option.id}>\n {option.separatorBefore ? <DropdownMenuSeparator /> : null}\n <DropdownMenuCheckboxItem\n checked={activeBorderPresets[option.id]}\n disabled={!enabledForContext}\n onCheckedChange={() => {\n if (enabledForContext) {\n applyBorderPreset(option.id)\n }\n }}\n >\n <HugeiconsIcon\n icon={BorderOptionIcon}\n className="size-4 text-muted-foreground"\n />\n {option.label}\n </DropdownMenuCheckboxItem>\n </React.Fragment>\n )\n })}\n </DropdownMenuContent>\n </DropdownMenu>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Insert image"\n disabled={!canEdit}\n onClick={onImageUploadClick}\n >\n <HugeiconsIcon icon={ImageAdd01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Insert table"\n disabled={!canEdit}\n onClick={editor.insertTable}\n >\n <HugeiconsIcon icon={TableIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarTooltip label="Section columns">\n <div className="flex h-7 shrink-0 items-center gap-1 rounded-lg px-2 text-xs text-muted-foreground">\n <HugeiconsIcon icon={ColumnsThreeCogIcon} className="size-4" />\n {activeColumns ? `${activeColumns.count} cols` : "1 col"}\n </div>\n </ToolbarTooltip>\n </div>\n\n <div className="ml-auto flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Zoom out"\n disabled={controlsDisabled || !canZoomOut}\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, -1)\n )\n }\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />\n </ToolbarIconButton>\n <Select\n value={zoomScale.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={controlsDisabled}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(zoomScale)}%</SelectValue>\n </SelectTrigger>\n <SelectContent align="end" className="z-[100010]">\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarIconButton\n label="Zoom in"\n disabled={controlsDisabled || !canZoomIn}\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, 1)\n )\n }\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nexport function DocxEditorPreview({\n className,\n fileName,\n rounded = false,\n src,\n}: {\n className?: string\n fileName?: string\n rounded?: boolean\n src?: string\n}) {\n const { resolvedTheme } = useTheme()\n const { nightRenderEnabled, nightRenderPrefLoaded, setNightRenderEnabled } =\n useDocumentNightRenderPreference()\n const isViewerHydrated = resolvedTheme !== undefined && nightRenderPrefLoaded\n const shouldShowHydrationSpinner = useDelayedLoadingIndicator(\n !isViewerHydrated,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n\n if (!isViewerHydrated) {\n return (\n <div\n className={cn(\n "flex h-[720px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <div\n className={cn(\n "min-h-0 flex-1 overflow-hidden bg-muted/30 p-4",\n rounded && "rounded-b-lg"\n )}\n >\n <EditorLoadingSurface showSpinner={shouldShowHydrationSpinner} />\n </div>\n </div>\n )\n }\n\n const shouldRenderNightMode = resolvedTheme === "dark"\n const effectiveIsDark = shouldRenderNightMode && nightRenderEnabled\n\n return (\n <DocxEditorContent\n className={className}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={setNightRenderEnabled}\n shouldRenderNightMode={shouldRenderNightMode}\n url={src}\n />\n )\n}\n\nfunction DocxEditorContent({\n className,\n effectiveIsDark,\n fileName,\n rounded,\n setNightRenderEnabled: _setNightRenderEnabled,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n effectiveIsDark: boolean\n fileName?: string\n rounded: boolean\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const imageInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [activePage, setActivePage] = React.useState(1)\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const [zoomScale, setZoomScale] = React.useState<number>(\n DOCX_EDITOR_DEFAULT_ZOOM_SCALE\n )\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\n const [isReadOnly, setIsReadOnly] = React.useState(false)\n const [linkEditorOpen, setLinkEditorOpen] = React.useState(false)\n const [linkDraft, setLinkDraft] = React.useState("")\n const viewerBackgroundColor =\n "color-mix(in oklab, var(--muted) 40%, transparent)"\n const displayFileName = React.useMemo(\n () =>\n uploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),\n [fileName, uploadedDocxFile?.file.name, url]\n )\n const cacheKey = React.useMemo(\n () =>\n uploadedDocxFile?.identity ??\n (url ? getDocumentCacheKey(url, displayFileName) : "docx-empty"),\n [displayFileName, uploadedDocxFile?.identity, url]\n )\n const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>\n effectiveIsDark ? "dark" : "light"\n )\n const editorOptions = React.useMemo(\n () => ({\n initialDocumentTheme,\n initialFileName: displayFileName,\n }),\n [displayFileName, initialDocumentTheme]\n )\n const editor = useDocxEditor(editorOptions)\n const { importDocxFile, setDocumentTheme, status } = editor\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n []\n )\n const { thumbnails } = useDocxViewerThumbnails(editor, thumbnailOptions)\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <EditorLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const hasDocument = Boolean(url || uploadedDocxFile)\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(DOCX_EDITOR_DEFAULT_ZOOM_SCALE)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [url])\n\n React.useEffect(() => {\n setDocumentTheme(effectiveIsDark ? "dark" : "light")\n }, [effectiveIsDark, setDocumentTheme])\n\n React.useEffect(() => {\n if (\n status.startsWith("Failed to load file") ||\n status === "Only .docx files are supported"\n ) {\n setLoadError(status)\n setIsLoadingDocument(false)\n }\n }, [status])\n\n React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n if (!uploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url\n ? await loadCachedDocxFile(url, displayFileName, cacheKey)\n : null)\n if (!docxFile) return\n await importDocxFile(docxFile)\n\n if (isCurrent) {\n setIsLoadingDocument(false)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }\n } catch (error) {\n if (isCurrent) {\n setLoadError(\n error instanceof Error ? error.message : "Unknown DOCX load error"\n )\n setIsLoadingDocument(false)\n }\n }\n }\n\n void load()\n\n return () => {\n isCurrent = false\n }\n }, [cacheKey, displayFileName, importDocxFile, uploadedDocxFile, url])\n\n React.useEffect(() => {\n if (url) {\n setUploadedDocxFile(null)\n }\n }, [url])\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n let closestPage = 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>(\n \'[data-docx-page-wrapper="true"][data-index]\'\n )\n .forEach((page) => {\n const pageIndex = Number(page.dataset.index)\n if (!Number.isFinite(pageIndex)) return\n\n const pageRect = page.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = pageIndex + 1\n }\n })\n\n setActivePage((currentPage) =>\n currentPage === closestPage ? currentPage : closestPage\n )\n }, [pageCount])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n let frameId = 0\n const handleScroll = () => {\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener("scroll", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n viewport.removeEventListener("scroll", handleScroll)\n }\n }, [pageCount, updateActivePageFromViewport])\n\n const scrollToPage = React.useCallback((pageNumber: number) => {\n const viewport = viewportRef.current\n const targetPageIndex = pageNumber - 1\n const page = viewport?.querySelector<HTMLElement>(\n `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`\n )\n\n setActivePage(pageNumber)\n\n if (!viewport || !page) return\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n }, [])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n setZoomScale(DOCX_EDITOR_DEFAULT_ZOOM_SCALE)\n setActivePage(1)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n async function handleImageUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n await editor.insertImageFile(file)\n }\n\n function openLinkEditor() {\n setLinkDraft(editor.selectedLink ?? "")\n setLinkEditorOpen(true)\n }\n\n function applyLink() {\n editor.setLink(linkDraft.trim() || undefined)\n setLinkEditorOpen(false)\n }\n\n return (\n <div\n className={cn(\n "flex h-[720px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n <input\n ref={imageInputRef}\n type="file"\n accept="image/*"\n className="hidden"\n onChange={handleImageUpload}\n />\n <DocxEditorToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n editor={editor}\n isReadOnly={isReadOnly}\n onImageUploadClick={() => imageInputRef.current?.click()}\n onIsReadOnlyChange={setIsReadOnly}\n onOpenLinkEditor={openLinkEditor}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showNightRenderToggle={shouldRenderNightMode}\n zoomScale={zoomScale}\n />\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {linkEditorOpen ? (\n <div className="absolute top-3 left-1/2 z-50 flex w-[min(420px,calc(100%-2rem))] -translate-x-1/2 items-center gap-2 rounded-lg border bg-background p-2 shadow-lg">\n <Input\n value={linkDraft}\n onChange={(event) => setLinkDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === "Enter") {\n event.preventDefault()\n applyLink()\n }\n if (event.key === "Escape") {\n setLinkEditorOpen(false)\n }\n }}\n placeholder="https://example.com"\n aria-label="Link URL"\n />\n <Button type="button" size="sm" onClick={applyLink}>\n Apply\n </Button>\n <Button\n type="button"\n size="sm"\n variant="ghost"\n onClick={() => {\n editor.setLink(undefined)\n setLinkEditorOpen(false)\n }}\n >\n Clear\n </Button>\n </div>\n ) : null}\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}\n >\n <ScrollArea className="h-full" scrollFade>\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 rounded-sm border bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </>\n ) : (\n <div className="flex flex-col items-center gap-3">\n {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (\n <Button\n key={thumbnail.pageIndex}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs text-muted-foreground shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => scrollToPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n !thumbnail.isMounted &&\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n ))}\n </div>\n )}\n </div>\n </ScrollArea>\n </DocumentViewerThumbnailSidebar>\n <div\n ref={viewportRef}\n className={cn(\n "min-h-0 flex-1 overflow-auto p-4",\n rounded && "rounded-b-lg"\n )}\n style={{ backgroundColor: viewerBackgroundColor }}\n >\n {!url && !uploadedDocxFile ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm shadow-xs">\n <div className="font-medium">Upload a DOCX to edit</div>\n <div className="mt-1 text-muted-foreground">\n Pass a DOCX URL with the <code>src</code> prop or upload a\n file.\n </div>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload DOCX\n </Button>\n </div>\n </div>\n ) : loadError ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm text-destructive shadow-xs">\n <div className="font-medium">Unable to edit DOCX</div>\n <div className="mt-1 text-muted-foreground">{loadError}</div>\n </div>\n </div>\n ) : isLoadingDocument ? (\n loadingState\n ) : (\n <div className="mx-auto flex min-h-full justify-center">\n <div\n className={cn(\n "origin-top",\n editor.documentTheme === "dark" && "docx-night-reader-shell"\n )}\n style={{ zoom: zoomScale / 100 }}\n >\n <DocxEditorViewer\n editor={editor}\n mode={isReadOnly ? "read-only" : "edit"}\n showTrackedChanges={editor.showTrackedChanges}\n loadingState={loadingState}\n pageBackgroundColor={\n editor.documentTheme === "dark" ? "#0a0a0a" : undefined\n }\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={{ enabled: false }}\n deferInitialPaginationPaint={false}\n />\n </div>\n </div>\n )}\n </div>\n </div>\n </div>\n )\n}\n'+ '"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"\nimport { useTheme } from "next-themes"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/ui/document-viewer-sidebar"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { Input } from "@/components/ui/input"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/registry/new-york-v4/ui/dropdown-menu"\nimport { Separator } from "@/registry/new-york-v4/ui/separator"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_SOURCE_CACHE_LIMIT = 3\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst DOCX_EDITOR_DEFAULT_ZOOM_SCALE = 75\nconst ZOOM_OPTIONS = [50, 75, 90, 100, 110, 125, 150, 175, 200] as const\nconst FONT_FAMILIES = [\n "Calibri",\n "Arial",\n "Times New Roman",\n "Georgia",\n "Helvetica",\n "Courier New",\n] as const\nconst FONT_SIZE_OPTIONS = [\n 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48,\n] as const\nconst LINE_SPACING_OPTIONS = [1, 1.15, 1.2, 1.5, 2, 2.5, 3] as const\nconst FALLBACK_PARAGRAPH_STYLE_OPTIONS = [\n { id: "Normal", name: "Body" },\n { id: "Heading1", name: "Heading 1" },\n { id: "Heading2", name: "Heading 2" },\n { id: "Heading3", name: "Heading 3" },\n] as const\nconst HIGHLIGHT_COLORS = [\n { label: "Yellow", value: "yellow", color: "#fff59d" },\n { label: "Green", value: "green", color: "#bbf7d0" },\n { label: "Cyan", value: "cyan", color: "#a5f3fc" },\n { label: "Magenta", value: "magenta", color: "#f5d0fe" },\n { label: "Red", value: "red", color: "#fecaca" },\n { label: "Blue", value: "blue", color: "#bfdbfe" },\n] as const\nconst 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 useDocumentNightRenderPreference() {\n const [nightRenderEnabled, setNightRenderEnabled] = React.useState(false)\n const [nightRenderPrefLoaded, setNightRenderPrefLoaded] =\n React.useState(false)\n\n React.useEffect(() => {\n const storedValue = window.localStorage.getItem("docx-editor-night-render")\n setNightRenderEnabled(storedValue === "true")\n setNightRenderPrefLoaded(true)\n }, [])\n\n const updateNightRenderEnabled = React.useCallback((checked: boolean) => {\n setNightRenderEnabled(checked)\n window.localStorage.setItem("docx-editor-night-render", String(checked))\n }, [])\n\n return {\n nightRenderEnabled,\n nightRenderPrefLoaded,\n setNightRenderEnabled: updateNightRenderEnabled,\n }\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === "string" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes("padding"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\n}\n\nfunction normalizeHexColor(value?: string, fallback = "#111827") {\n if (!value) return fallback\n\n const trimmed = value.trim()\n const threeDigit = /^#([0-9a-f]{3})$/i.exec(trimmed)\n if (threeDigit?.[1]) {\n const [red, green, blue] = threeDigit[1].split("")\n return `#${red}${red}${green}${green}${blue}${blue}`.toLowerCase()\n }\n\n const sixDigit = /^#([0-9a-f]{6})$/i.exec(trimmed)\n if (sixDigit?.[1]) {\n return `#${sixDigit[1].toLowerCase()}`\n }\n\n return fallback\n}\n\nfunction 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="bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n renderDocumentPreview={false}\n isLoading={isLoading}\n hasError={hasError}\n showMetadata={false}\n className={cn(\n "w-full rounded-sm border shadow-xs transition-[border-color,box-shadow] duration-150",\n isActive && "border-primary shadow-sm"\n )}\n />\n )\n}\n\nfunction 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 onIsReadOnlyChange,\n onOpenLinkEditor,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showNightRenderToggle,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n editor: DocxEditorController\n isReadOnly: boolean\n onImageUploadClick: () => void\n onIsReadOnlyChange: (checked: boolean) => void\n onOpenLinkEditor: () => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showNightRenderToggle: boolean\n zoomScale: number\n}) {\n const { documentTheme, setDocumentTheme } = useDocxDocumentTheme(editor)\n const { layout: pageLayout } = useDocxPageLayout(editor)\n const { paragraphStyles, selectedParagraphStyleId, setParagraphStyle } =\n useDocxParagraphStyles(editor)\n const { lineSpacing, setLineSpacing } = useDocxLineSpacing(editor)\n const { borderContext, activeBorderPresets, applyBorderPreset } =\n useDocxBorders(editor)\n const { showTrackedChanges, setShowTrackedChanges } =\n useDocxTrackChanges(editor)\n const selectedRunStyle = editor.selectedRunStyle\n const selectedParagraph = editor.selectedParagraph\n const paragraphStyleOptions: 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 setDocumentTheme(documentTheme === "dark" ? "light" : "dark")\n }\n >\n <HugeiconsIcon\n icon={documentTheme === "dark" ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </ToolbarIconButton>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <ToolbarIconButton\n label="Show tracked changes"\n active={showTrackedChanges}\n disabled={controlsDisabled}\n onClick={() => setShowTrackedChanges(!showTrackedChanges)}\n >\n <HugeiconsIcon icon={FileDiffIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label={isReadOnly ? "Switch to edit mode" : "Switch to read-only"}\n active={isReadOnly}\n disabled={controlsDisabled}\n onClick={() => onIsReadOnlyChange(!isReadOnly)}\n >\n <HugeiconsIcon icon={EditOffIcon} className="size-4" />\n </ToolbarIconButton>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <ToolbarIconButton\n label="Import DOCX"\n disabled={editor.isImporting}\n onClick={onUploadClick}\n >\n {editor.isImporting ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n )}\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Download DOCX"\n disabled={controlsDisabled || editor.isImporting}\n onClick={editor.exportDocx}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex min-h-12 flex-wrap items-center gap-2 border-b px-3 py-2">\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Undo"\n disabled={!editor.canUndo || isReadOnly}\n onClick={editor.undo}\n >\n <HugeiconsIcon icon={Undo02Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Redo"\n disabled={!editor.canRedo || isReadOnly}\n onClick={editor.redo}\n >\n <HugeiconsIcon icon={Redo02Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <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 fileName,\n rounded = false,\n src,\n}: {\n className?: string\n fileName?: string\n rounded?: boolean\n src?: string\n}) {\n const { resolvedTheme } = useTheme()\n const { nightRenderEnabled, nightRenderPrefLoaded, setNightRenderEnabled } =\n useDocumentNightRenderPreference()\n const isViewerHydrated = resolvedTheme !== undefined && nightRenderPrefLoaded\n const shouldShowHydrationSpinner = useDelayedLoadingIndicator(\n !isViewerHydrated,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n\n if (!isViewerHydrated) {\n return (\n <div\n className={cn(\n "flex h-[720px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <div\n className={cn(\n "min-h-0 flex-1 overflow-hidden bg-muted/30 p-4",\n rounded && "rounded-b-lg"\n )}\n >\n <EditorLoadingSurface showSpinner={shouldShowHydrationSpinner} />\n </div>\n </div>\n )\n }\n\n const shouldRenderNightMode = resolvedTheme === "dark"\n const effectiveIsDark = shouldRenderNightMode && nightRenderEnabled\n\n return (\n <DocxEditorContent\n className={className}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={setNightRenderEnabled}\n shouldRenderNightMode={shouldRenderNightMode}\n url={src}\n />\n )\n}\n\nfunction DocxEditorContent({\n className,\n effectiveIsDark,\n fileName,\n rounded,\n setNightRenderEnabled: _setNightRenderEnabled,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n effectiveIsDark: boolean\n fileName?: string\n rounded: boolean\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const imageInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [activePage, setActivePage] = React.useState(1)\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const [zoomScale, setZoomScale] = React.useState<number>(\n DOCX_EDITOR_DEFAULT_ZOOM_SCALE\n )\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\n const [isReadOnly, setIsReadOnly] = React.useState(false)\n const [linkEditorOpen, setLinkEditorOpen] = React.useState(false)\n const [linkDraft, setLinkDraft] = React.useState("")\n const viewerBackgroundColor =\n "color-mix(in oklab, var(--muted) 40%, transparent)"\n const displayFileName = React.useMemo(\n () =>\n uploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),\n [fileName, uploadedDocxFile?.file.name, url]\n )\n const cacheKey = React.useMemo(\n () =>\n uploadedDocxFile?.identity ??\n (url ? getDocumentCacheKey(url, displayFileName) : "docx-empty"),\n [displayFileName, uploadedDocxFile?.identity, url]\n )\n const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>\n effectiveIsDark ? "dark" : "light"\n )\n const editorOptions = React.useMemo(\n () => ({\n initialDocumentTheme,\n initialFileName: displayFileName,\n }),\n [displayFileName, initialDocumentTheme]\n )\n const editor = useDocxEditor(editorOptions)\n const { importDocxFile, setDocumentTheme, status } = editor\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n []\n )\n const { thumbnails } = useDocxViewerThumbnails(editor, thumbnailOptions)\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <EditorLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const hasDocument = Boolean(url || uploadedDocxFile)\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(DOCX_EDITOR_DEFAULT_ZOOM_SCALE)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [url])\n\n React.useEffect(() => {\n setDocumentTheme(effectiveIsDark ? "dark" : "light")\n }, [effectiveIsDark, setDocumentTheme])\n\n React.useEffect(() => {\n if (\n status.startsWith("Failed to load file") ||\n status === "Only .docx files are supported"\n ) {\n setLoadError(status)\n setIsLoadingDocument(false)\n }\n }, [status])\n\n React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n if (!uploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url\n ? await loadCachedDocxFile(url, displayFileName, cacheKey)\n : null)\n if (!docxFile) return\n await importDocxFile(docxFile)\n\n if (isCurrent) {\n setIsLoadingDocument(false)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }\n } catch (error) {\n if (isCurrent) {\n setLoadError(\n error instanceof Error ? error.message : "Unknown DOCX load error"\n )\n setIsLoadingDocument(false)\n }\n }\n }\n\n void load()\n\n return () => {\n isCurrent = false\n }\n }, [cacheKey, displayFileName, importDocxFile, uploadedDocxFile, url])\n\n React.useEffect(() => {\n if (url) {\n setUploadedDocxFile(null)\n }\n }, [url])\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n let closestPage = 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>(\n \'[data-docx-page-wrapper="true"][data-index]\'\n )\n .forEach((page) => {\n const pageIndex = Number(page.dataset.index)\n if (!Number.isFinite(pageIndex)) return\n\n const pageRect = page.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = pageIndex + 1\n }\n })\n\n setActivePage((currentPage) =>\n currentPage === closestPage ? currentPage : closestPage\n )\n }, [pageCount])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n let frameId = 0\n const handleScroll = () => {\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener("scroll", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n viewport.removeEventListener("scroll", handleScroll)\n }\n }, [pageCount, updateActivePageFromViewport])\n\n const scrollToPage = React.useCallback((pageNumber: number) => {\n const viewport = viewportRef.current\n const targetPageIndex = pageNumber - 1\n const page = viewport?.querySelector<HTMLElement>(\n `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`\n )\n\n setActivePage(pageNumber)\n\n if (!viewport || !page) return\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n }, [])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n setZoomScale(DOCX_EDITOR_DEFAULT_ZOOM_SCALE)\n setActivePage(1)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n async function handleImageUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n await editor.insertImageFile(file)\n }\n\n function openLinkEditor() {\n setLinkDraft(editor.selectedLink ?? "")\n setLinkEditorOpen(true)\n }\n\n function applyLink() {\n editor.setLink(linkDraft.trim() || undefined)\n setLinkEditorOpen(false)\n }\n\n return (\n <div\n className={cn(\n "flex h-[720px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n <input\n ref={imageInputRef}\n type="file"\n accept="image/*"\n className="hidden"\n onChange={handleImageUpload}\n />\n <DocxEditorToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n editor={editor}\n isReadOnly={isReadOnly}\n onImageUploadClick={() => imageInputRef.current?.click()}\n onIsReadOnlyChange={setIsReadOnly}\n onOpenLinkEditor={openLinkEditor}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showNightRenderToggle={shouldRenderNightMode}\n zoomScale={zoomScale}\n />\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {linkEditorOpen ? (\n <div className="absolute top-3 left-1/2 z-50 flex w-[min(420px,calc(100%-2rem))] -translate-x-1/2 items-center gap-2 rounded-lg border bg-background p-2 shadow-lg">\n <Input\n value={linkDraft}\n onChange={(event) => setLinkDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === "Enter") {\n event.preventDefault()\n applyLink()\n }\n if (event.key === "Escape") {\n setLinkEditorOpen(false)\n }\n }}\n placeholder="https://example.com"\n aria-label="Link URL"\n />\n <Button type="button" size="sm" onClick={applyLink}>\n Apply\n </Button>\n <Button\n type="button"\n size="sm"\n variant="ghost"\n onClick={() => {\n editor.setLink(undefined)\n setLinkEditorOpen(false)\n }}\n >\n Clear\n </Button>\n </div>\n ) : null}\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}\n >\n <ScrollArea className="h-full" scrollFade>\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 rounded-sm border bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </>\n ) : (\n <div className="flex flex-col items-center gap-3">\n {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (\n <Button\n key={thumbnail.pageIndex}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs text-muted-foreground shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => scrollToPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n !thumbnail.isMounted &&\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n ))}\n </div>\n )}\n </div>\n </ScrollArea>\n </DocumentViewerThumbnailSidebar>\n <div\n ref={viewportRef}\n className={cn(\n "min-h-0 flex-1 overflow-auto p-4",\n rounded && "rounded-b-lg"\n )}\n style={{ backgroundColor: viewerBackgroundColor }}\n >\n {!url && !uploadedDocxFile ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm shadow-xs">\n <div className="font-medium">Upload a DOCX to edit</div>\n <div className="mt-1 text-muted-foreground">\n Pass a DOCX URL with the <code>src</code> prop or upload a\n file.\n </div>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload DOCX\n </Button>\n </div>\n </div>\n ) : loadError ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm text-destructive shadow-xs">\n <div className="font-medium">Unable to edit DOCX</div>\n <div className="mt-1 text-muted-foreground">{loadError}</div>\n </div>\n </div>\n ) : isLoadingDocument ? (\n loadingState\n ) : (\n <div className="mx-auto flex min-h-full justify-center">\n <div\n className={cn(\n "origin-top",\n editor.documentTheme === "dark" && "docx-night-reader-shell"\n )}\n style={{ zoom: zoomScale / 100 }}\n >\n <DocxEditorViewer\n editor={editor}\n mode={isReadOnly ? "read-only" : "edit"}\n showTrackedChanges={editor.showTrackedChanges}\n loadingState={loadingState}\n pageBackgroundColor={\n editor.documentTheme === "dark" ? "#0a0a0a" : undefined\n }\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={{ enabled: false }}\n deferInitialPaginationPaint={false}\n />\n </div>\n </div>\n )}\n </div>\n </div>\n </div>\n )\n}\n'export function DocxEditorSource() {return <HighlightedCodeBlock code={docxEditorSourceCode} />diff --git a/apps/v4/components/ui/docx-editor.tsx b/apps/v4/components/ui/docx-editor.tsxindex 01db2c3..bf3fcdc 100644--- a/apps/v4/components/ui/docx-editor.tsx+++ b/apps/v4/components/ui/docx-editor.tsx@@ -1,6 +1,7 @@"use client"import * as React from "react"+import { PreviewCard as PreviewCardPrimitive } from "@base-ui/react/preview-card"import {DocxEditorViewer,paragraphLetterheadFloatSideAtNodeIndex,@@ -16,6 +17,7 @@ import {type DocxBorderPreset,type DocxDocumentTheme,type DocxEditorController,+ type ParagraphStyleDefinition,} from "@extend-ai/react-docx"import {ArrowExpandDiagonal01Icon,@@ -129,7 +131,55 @@ const HIGHLIGHT_COLORS = [{ label: "Red", value: "red", color: "#fecaca" },{ label: "Blue", value: "blue", color: "#bfdbfe" },] as const+const HIGHLIGHT_PREVIEW_COLORS: Record<string, string> = {+ black: "#111827",+ white: "#ffffff",+ ...Object.fromEntries(+ HIGHLIGHT_COLORS.map((option) => [option.value, option.color])+ ),+}const DOCX_PADDING_WARNING_TEXT = "a style property during rerender"+const DEFAULT_HEADING_PREVIEW_RUN_STYLES: Record<+ 1 | 2 | 3 | 4 | 5 | 6,+ NonNullable<ParagraphStyleDefinition["runStyle"]>+> = {+ 1: {+ fontFamily: "Calibri Light",+ fontSizePt: 16,+ bold: true,+ color: "#2f5496",+ },+ 2: {+ fontFamily: "Calibri Light",+ fontSizePt: 13,+ bold: true,+ color: "#2f5496",+ },+ 3: {+ fontFamily: "Calibri",+ fontSizePt: 12,+ bold: true,+ color: "#1f3763",+ },+ 4: {+ fontFamily: "Calibri",+ fontSizePt: 11,+ bold: true,+ color: "#1f3763",+ },+ 5: {+ fontFamily: "Calibri",+ fontSizePt: 11,+ bold: true,+ color: "#1f3763",+ },+ 6: {+ fontFamily: "Calibri",+ fontSizePt: 11,+ bold: true,+ color: "#1f3763",+ },+}const docxFileCache = new Map<string, File>()const docxFilePromiseCache = new Map<string, Promise<File>>()@@ -381,6 +431,119 @@ function normalizeHexColor(value?: string, fallback = "#111827") {return fallback}+function inferParagraphStyleHeadingLevel(value?: string) {+ if (!value) return undefined++ const match = value.match(/(?:^|[\s_-])(?:heading|h)\s*([1-6])(?:$|[\s_-])/i)+ const level = match?.[1] ? Number(match[1]) : NaN++ return level >= 1 && level <= 6 ? (level as 1 | 2 | 3 | 4 | 5 | 6) : undefined+}++function resolveParagraphStyleHeadingLevel(option?: ParagraphStyleDefinition) {+ if (+ Number.isFinite(option?.headingLevel) &&+ option?.headingLevel &&+ option.headingLevel >= 1 &&+ option.headingLevel <= 6+ ) {+ return option.headingLevel as 1 | 2 | 3 | 4 | 5 | 6+ }++ return (+ inferParagraphStyleHeadingLevel(option?.id) ??+ inferParagraphStyleHeadingLevel(option?.name)+ )+}++function resolveParagraphStyleRunPreview(option?: ParagraphStyleDefinition) {+ if (!option) return undefined++ const headingLevel = resolveParagraphStyleHeadingLevel(option)+ const headingRunStyle = headingLevel+ ? DEFAULT_HEADING_PREVIEW_RUN_STYLES[headingLevel]+ : undefined++ return headingRunStyle+ ? {+ ...headingRunStyle,+ ...(option.runStyle ?? {}),+ }+ : option.runStyle+}++function resolveHighlightPreview(value?: string) {+ if (!value) return undefined++ const normalized = value.trim().toLowerCase()+ if (!normalized) return undefined++ const hex = normalizeHexColor(normalized, "")+ if (hex) return hex++ return HIGHLIGHT_PREVIEW_COLORS[normalized]+}++function themedPreviewColor(+ color: string | undefined,+ documentTheme: DocxDocumentTheme+) {+ if (documentTheme !== "dark") return color+ if (!color) return "#f3f4f6"++ const normalized = color.trim().toLowerCase()+ if (+ normalized === "#000" ||+ normalized === "#000000" ||+ normalized === "#111111" ||+ normalized === "#111827" ||+ normalized === "black" ||+ normalized === "rgb(0,0,0)" ||+ normalized === "rgb(0, 0, 0)"+ ) {+ return "#f3f4f6"+ }++ return color+}++function paragraphStylePreviewStyle(+ option: ParagraphStyleDefinition,+ documentTheme: DocxDocumentTheme+): React.CSSProperties {+ const runStyle = resolveParagraphStyleRunPreview(option)+ const textDecoration = [+ runStyle?.underline ? "underline" : "",+ runStyle?.strike ? "line-through" : "",+ ]+ .filter(Boolean)+ .join(" ")++ return {+ textAlign: option.align ?? "left",+ fontFamily: runStyle?.fontFamily,+ fontSize: runStyle?.fontSizePt ? `${runStyle.fontSizePt}pt` : "11pt",+ fontWeight:+ runStyle?.bold !== undefined ? (runStyle.bold ? 700 : 400) : undefined,+ fontStyle: runStyle?.italic ? "italic" : undefined,+ textDecoration: textDecoration || undefined,+ color:+ runStyle?.color !== undefined+ ? themedPreviewColor(normalizeHexColor(runStyle.color), documentTheme)+ : undefined,+ backgroundColor: resolveHighlightPreview(runStyle?.highlight),+ lineHeight: 1,+ whiteSpace: "pre-wrap",+ }+}++function paragraphStylePreviewTriggerId(prefix: string, styleId: string) {+ return `${prefix}-paragraph-style-preview-${styleId.replace(+ /[^a-zA-Z0-9_-]/g,+ "_"+ )}`+}+function parseToolbarSectionColumns(sectionPropertiesXml?: string): { count: number; gapPx: number } | undefined {@@ -546,6 +709,50 @@ function DocxSidebarThumbnail({)}+function ParagraphStylePreviewCard({+ documentTheme,+ option,+}: {+ documentTheme: DocxDocumentTheme+ option: ParagraphStyleDefinition+}) {+ const surfaceStyle: React.CSSProperties =+ documentTheme === "dark"+ ? {+ backgroundColor: "#111827",+ borderColor: "#374151",+ color: "#f3f4f6",+ }+ : {+ backgroundColor: "#ffffff",+ borderColor: "#d4d4d8",+ color: "#111827",+ }+ const secondaryTextColor = documentTheme === "dark" ? "#9ca3af" : "#6b7280"++ return (+ <div className="w-[260px] p-3">+ <p className="text-[10px] font-medium tracking-wide text-muted-foreground uppercase">+ Style Preview+ </p>+ <div className="mt-2 rounded-sm border p-2.5" style={surfaceStyle}>+ <p style={paragraphStylePreviewStyle(option, documentTheme)}>+ {option.name}+ </p>+ <p+ className="mt-1 text-[11px]"+ style={{+ color: secondaryTextColor,+ textAlign: option.align ?? "left",+ }}+ >+ The quick brown fox jumps over the lazy dog.+ </p>+ </div>+ </div>+ )+}+function DocxEditorToolbar({activePage,controlsDisabled,@@ -586,7 +793,7 @@ function DocxEditorToolbar({useDocxTrackChanges(editor)const selectedRunStyle = editor.selectedRunStyleconst selectedParagraph = editor.selectedParagraph- const paragraphStyleOptions =+ const paragraphStyleOptions: ParagraphStyleDefinition[] =paragraphStyles.length > 0? paragraphStyles: [...FALLBACK_PARAGRAPH_STYLE_OPTIONS]@@ -595,6 +802,27 @@ function DocxEditorToolbar({paragraphStyleOptions.find((option) => "isDefault" in option)?.id ??paragraphStyleOptions[0]?.id ??"Normal"+ const selectedParagraphStyleOption =+ paragraphStyleOptions.find(+ (option) => option.id === selectedParagraphStyleValue+ ) ??+ paragraphStyleOptions[0] ??+ FALLBACK_PARAGRAPH_STYLE_OPTIONS[0]+ const paragraphStylePreviewHandle = React.useMemo(+ () => PreviewCardPrimitive.createHandle<ParagraphStyleDefinition>(),+ []+ )+ const paragraphStylePreviewIdPrefix = React.useId()+ const [isParagraphStyleMenuOpen, setIsParagraphStyleMenuOpen] =+ React.useState(false)+ const openParagraphStylePreview = React.useCallback(+ (styleId: string) => {+ paragraphStylePreviewHandle.open(+ paragraphStylePreviewTriggerId(paragraphStylePreviewIdPrefix, styleId)+ )+ },+ [paragraphStylePreviewHandle, paragraphStylePreviewIdPrefix]+ )const selectedLineSpacingValue = React.useMemo(() => {const current = Number.isFinite(lineSpacing.multiple)? lineSpacing.multiple@@ -748,30 +976,109 @@ function DocxEditorToolbar({</ToolbarIconButton></div>- <Select- value={selectedParagraphStyleValue}- onValueChange={(value) => {- if (value) {- setParagraphStyle(value)- }+ <PreviewCardPrimitive.Root handle={paragraphStylePreviewHandle}>+ {({ payload }) => {+ const previewOption = payload ?? selectedParagraphStyleOption++ return (+ <>+ <Select+ value={selectedParagraphStyleValue}+ onOpenChange={(open) => {+ setIsParagraphStyleMenuOpen(open)++ if (!open) {+ paragraphStylePreviewHandle.close()+ return+ }++ window.requestAnimationFrame(() => {+ openParagraphStylePreview(selectedParagraphStyleValue)+ })+ }}+ onValueChange={(value) => {+ if (value) {+ setParagraphStyle(value)+ }+ }}+ disabled={!canEdit}+ modal={false}+ >+ <SelectTrigger+ size="sm"+ className="w-[136px] min-w-[136px]"+ aria-label="Paragraph style"+ >+ <SelectValue placeholder="Style" />+ </SelectTrigger>+ <SelectContent+ align="start"+ alignItemWithTrigger={false}+ className="z-[100010] min-w-[210px]"+ >+ {paragraphStyleOptions.map((option) => {+ const previewTriggerId = paragraphStylePreviewTriggerId(+ paragraphStylePreviewIdPrefix,+ option.id+ )++ return (+ <SelectItem+ key={option.id}+ value={option.id}+ label={option.name}+ className="relative min-w-[190px]"+ onFocus={() => openParagraphStylePreview(option.id)}+ onPointerEnter={() =>+ openParagraphStylePreview(option.id)+ }+ >+ <span className="block truncate">+ {option.name}+ </span>+ <PreviewCardPrimitive.Trigger+ id={previewTriggerId}+ handle={paragraphStylePreviewHandle}+ payload={option}+ delay={0}+ closeDelay={120}+ render={+ <span+ aria-hidden="true"+ className="pointer-events-none absolute inset-0 block"+ />+ }+ />+ </SelectItem>+ )+ })}+ </SelectContent>+ </Select>+ {isParagraphStyleMenuOpen && previewOption ? (+ <PreviewCardPrimitive.Portal>+ <PreviewCardPrimitive.Positioner+ side="right"+ align="start"+ sideOffset={10}+ alignOffset={-4}+ className="z-[100020] transition-[top,left,right,bottom,transform] duration-100 ease-out data-instant:transition-none"+ >+ <PreviewCardPrimitive.Popup+ data-slot="paragraph-style-preview-card"+ 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%)]"+ >+ <ParagraphStylePreviewCard+ documentTheme={documentTheme}+ option={previewOption}+ />+ </PreviewCardPrimitive.Popup>+ </PreviewCardPrimitive.Positioner>+ </PreviewCardPrimitive.Portal>+ ) : null}+ </>+ )}}- disabled={!canEdit}- >- <SelectTrigger- size="sm"- className="w-[136px] min-w-[136px]"- aria-label="Paragraph style"- >- <SelectValue placeholder="Style" />- </SelectTrigger>- <SelectContent align="start" className="z-[100010]">- {paragraphStyleOptions.map((option) => (- <SelectItem key={option.id} value={option.id}>- {option.name}- </SelectItem>- ))}- </SelectContent>- </Select>+ </PreviewCardPrimitive.Root><Selectvalue={selectedRunStyle?.fontFamily ?? "Calibri"}@@ -781,6 +1088,7 @@ function DocxEditorToolbar({}}}disabled={!canEdit}+ modal={false}><SelectTriggersize="sm"@@ -789,7 +1097,11 @@ function DocxEditorToolbar({><SelectValue placeholder="Font" /></SelectTrigger>- <SelectContent align="start" className="z-[100010]">+ <SelectContent+ align="start"+ alignItemWithTrigger={false}+ className="z-[100010]"+ >{FONT_FAMILIES.map((fontFamily) => (<SelectItem key={fontFamily} value={fontFamily}><span style={{ fontFamily }}>{fontFamily}</span>@@ -807,6 +1119,7 @@ function DocxEditorToolbar({}}}disabled={!canEdit}+ modal={false}><SelectTriggersize="sm"@@ -815,7 +1128,11 @@ function DocxEditorToolbar({><SelectValue placeholder="Size" /></SelectTrigger>- <SelectContent align="start" className="z-[100010]">+ <SelectContent+ align="start"+ alignItemWithTrigger={false}+ className="z-[100010]"+ >{FONT_SIZE_OPTIONS.map((size) => (<SelectItem key={size} value={String(size)}>{size} pt@@ -833,6 +1150,7 @@ function DocxEditorToolbar({}}}disabled={!canEdit}+ modal={false}><SelectTriggersize="sm"@@ -841,7 +1159,11 @@ function DocxEditorToolbar({><SelectValue placeholder="Spacing" /></SelectTrigger>- <SelectContent align="start" className="z-[100010]">+ <SelectContent+ align="start"+ alignItemWithTrigger={false}+ className="z-[100010]"+ >{LINE_SPACING_OPTIONS.map((spacing) => (<SelectItem key={spacing} value={String(spacing)}>{spacing}x