Skip to content

armgit / ui

Public Imported from GitHub
0
TypeScript

Fix PDF editor file name precedence

Andrew Luo182a7cb7382e
diff --git a/apps/v4/components/extend/pdf-editor.tsx b/apps/v4/components/extend/pdf-editor.tsx
index 34f7e1e..9ddcacb 100644
--- a/apps/v4/components/extend/pdf-editor.tsx
+++ b/apps/v4/components/extend/pdf-editor.tsx
@@ -3982,9 +3982,7 @@ function PdfEditorDocumentLoader({
)
}, [documentManager, source])
- const fileName = fileNameOverride
- ? getPdfFileName(fileNameOverride)
- : (source?.name ?? getPdfFileName(undefined))
+ const fileName = source?.name ?? getPdfFileName(fileNameOverride)
const isRequestedDocument =
requestedDocument?.sourceKey === source?.key &&
requestedDocument?.documentId === activeDocumentId
diff --git a/apps/v4/components/pdf-editor-source-code.tsx b/apps/v4/components/pdf-editor-source-code.tsx
index 5cecc4f..7cd4068 100644
--- a/apps/v4/components/pdf-editor-source-code.tsx
+++ b/apps/v4/components/pdf-editor-source-code.tsx
@@ -6,7 +6,7 @@ import { DocsSourceCodeBlock } from "@/components/docs-code-block"
export const pdfEditorSourceFiles: Array<{ fileName: string; code: string }> = [
{
fileName: "components/extend/pdf-editor.tsx",
- code: '"use client"\n\nimport * as React from "react"\nimport { createPluginRegistration } from "@embedpdf/core"\nimport {\n EmbedPDF,\n useDocumentPermissions,\n useDocumentState,\n useRegistry,\n} from "@embedpdf/core/react"\nimport {\n PdfAnnotationSubtype,\n PdfErrorCode,\n PdfPageFlattenFlag,\n uuidV4,\n type PdfAnnotationObject,\n type PdfDocumentObject,\n type PdfEngine,\n type PdfLinkAnnoObject,\n type PdfPrintOptions,\n} from "@embedpdf/models"\nimport {\n AnnotationLayer,\n AnnotationPluginPackage,\n getSelectedAnnotations,\n LockModeType,\n useAnnotation,\n useAnnotationCapability,\n type AnnotationEvent,\n type AnnotationSelectionMenuProps,\n type AnnotationTransferItem,\n type GroupSelectionMenuProps,\n} from "@embedpdf/plugin-annotation/react"\nimport { AttachmentPluginPackage } from "@embedpdf/plugin-attachment/react"\nimport { BookmarkPluginPackage } from "@embedpdf/plugin-bookmark/react"\nimport {\n CapturePluginPackage,\n MarqueeCapture,\n useCapture,\n type CaptureAreaEvent,\n} from "@embedpdf/plugin-capture/react"\nimport {\n DocumentManagerPluginPackage,\n useActiveDocument,\n useDocumentManagerCapability,\n} from "@embedpdf/plugin-document-manager/react"\nimport { ExportPluginPackage, useExport } from "@embedpdf/plugin-export/react"\nimport {\n FormPluginPackage,\n useFormCapability,\n} from "@embedpdf/plugin-form/react"\nimport {\n FullscreenPluginPackage,\n useFullscreen,\n} from "@embedpdf/plugin-fullscreen/react"\nimport {\n HistoryPluginPackage,\n useHistoryCapability,\n} from "@embedpdf/plugin-history/react"\nimport {\n GlobalPointerProvider,\n InteractionManagerPluginPackage,\n PagePointerProvider,\n} from "@embedpdf/plugin-interaction-manager/react"\nimport { PanPluginPackage, usePan } from "@embedpdf/plugin-pan/react"\nimport { PrintPluginPackage, usePrint } from "@embedpdf/plugin-print/react"\nimport {\n RedactionLayer,\n RedactionMode,\n RedactionPluginPackage,\n useRedaction,\n type RedactionSelectionMenuProps,\n} from "@embedpdf/plugin-redaction/react"\nimport { RenderLayer, RenderPluginPackage } from "@embedpdf/plugin-render/react"\nimport {\n Rotate,\n RotatePluginPackage,\n useRotate,\n} from "@embedpdf/plugin-rotate/react"\nimport {\n Scroller,\n ScrollPluginPackage,\n ScrollStrategy,\n useScroll,\n useScrollCapability,\n type PageLayout,\n} from "@embedpdf/plugin-scroll/react"\nimport {\n SearchLayer,\n SearchPluginPackage,\n useSearch,\n} from "@embedpdf/plugin-search/react"\nimport {\n CopyToClipboard,\n SelectionLayer,\n SelectionPluginPackage,\n useSelectionCapability,\n type SelectionSelectionMenuProps,\n} from "@embedpdf/plugin-selection/react"\nimport {\n deserializeEntries,\n serializeEntries,\n SignatureMode,\n SignaturePluginPackage,\n useSignatureCapability,\n} from "@embedpdf/plugin-signature/react"\nimport {\n SpreadMode,\n SpreadPluginPackage,\n useSpread,\n} from "@embedpdf/plugin-spread/react"\nimport { StampPluginPackage } from "@embedpdf/plugin-stamp/react"\nimport { ThumbnailPluginPackage } from "@embedpdf/plugin-thumbnail/react"\nimport { TilingLayer, TilingPluginPackage } from "@embedpdf/plugin-tiling/react"\nimport {\n useIsViewportGated,\n useViewportCapability,\n useViewportElement,\n useViewportRef,\n ViewportElementContext,\n ViewportPluginPackage,\n} from "@embedpdf/plugin-viewport/react"\nimport {\n MarqueeZoom,\n useZoom,\n ZoomMode,\n ZoomPluginPackage,\n} from "@embedpdf/plugin-zoom/react"\n\nimport { loadSharedPdfEngine } from "@/lib/pdf-thumbnail-utils"\nimport { cn } from "@/lib/utils"\nimport { Badge } from "@/components/ui/badge"\nimport { Button } from "@/components/ui/button"\nimport { ColorPicker } from "@/components/ui/color-picker"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuGroup,\n DropdownMenuItem,\n DropdownMenuLabel,\n DropdownMenuRadioGroup,\n DropdownMenuRadioItem,\n DropdownMenuSeparator,\n DropdownMenuShortcut,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { Input } from "@/components/ui/input"\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from "@/components/ui/popover"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Spinner } from "@/components/ui/spinner"\nimport { ToastPrimitive, ToastProvider } from "@/components/ui/toast"\nimport { TooltipProvider } from "@/components/ui/tooltip"\nimport {\n DocumentViewerSidebarSkeleton,\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/extend/document-viewer-sidebar"\nimport {\n PdfEditorCaptureDialog,\n PdfEditorConfirmDialog,\n PdfEditorLinkDialog,\n PdfEditorPasswordPrompt,\n PdfEditorPrintDialog,\n PdfEditorPropertiesDialog,\n PdfEditorSecurityDialog,\n PdfEditorShortcutsDialog,\n PdfEditorSignatureDialog,\n} from "@/components/extend/pdf-editor-dialogs"\nimport {\n PdfEditorAttachmentsPanel,\n PdfEditorCommentsPanel,\n PdfEditorFormsPanel,\n PdfEditorOutlinePanel,\n PdfEditorPagesPanel,\n PdfEditorRedactionsPanel,\n PdfEditorSignaturesPanel,\n PdfEditorStampsPanel,\n PdfEditorThumbnailsPanel,\n} from "@/components/extend/pdf-editor-panels"\nimport { PdfEditorPropertiesPanel } from "@/components/extend/pdf-editor-properties"\nimport {\n BookOpenGlyph,\n CameraGlyph,\n ChevronLeftGlyph,\n ChevronRightGlyph,\n CloseGlyph,\n CommentGlyph,\n CommentsGlyph,\n CopyGlyph,\n CursorGlyph,\n downloadArrayBuffer,\n downloadBlob,\n DownloadGlyph,\n EditGlyph,\n ExitFullscreenGlyph,\n ExternalLinkGlyph,\n EyeOffGlyph,\n FileTextGlyph,\n FullscreenGlyph,\n getPdfFileName,\n GridGlyph,\n GroupGlyph,\n HandGlyph,\n HighlighterGlyph,\n InfoGlyph,\n isTypingTarget,\n KeyboardGlyph,\n LayersGlyph,\n LinkGlyph,\n ListTreeGlyph,\n LockGlyph,\n MarqueeZoomGlyph,\n MoreGlyph,\n noop,\n PaletteGlyph,\n PanelLeftGlyph,\n PanelRightGlyph,\n PaperclipGlyph,\n PDF_EDITOR_ANNOTATION_TOOL_GROUPS,\n PDF_EDITOR_DEFAULT_COLOR_PRESETS,\n PDF_EDITOR_DEFAULT_FEATURES,\n PDF_EDITOR_DEFAULT_SIGNATURE_FONTS_URL,\n PDF_EDITOR_DEFAULT_STAMP_MANIFEST_URL,\n PDF_EDITOR_FORM_TOOLS,\n PDF_EDITOR_MODE_OPTIONS,\n PDF_EDITOR_SELECTION_COLOR,\n PdfEditorContextProvider,\n PdfEditorScrollArea,\n PdfEditorScrollAreaResolverContext,\n PdfEditorToolbarSeparator,\n PdfEditorToolButton,\n PdfEditorTooltip,\n PlusGlyph,\n PrintGlyph,\n RedactAreaGlyph,\n RedoGlyph,\n resolveDefaultScrollAreaViewport,\n RotateGlyph,\n SearchGlyph,\n ShieldGlyph,\n SignatureGlyph,\n SlidersGlyph,\n StampGlyph,\n StrikethroughGlyph,\n TextFieldGlyph,\n TextGlyph,\n toNormalizedRect,\n TrashGlyph,\n UnderlineGlyph,\n UndoGlyph,\n UngroupGlyph,\n UnlockGlyph,\n UploadGlyph,\n usePdfEditor,\n ZoomInGlyph,\n ZoomOutGlyph,\n type PdfEditorContextValue,\n type PdfEditorDialogRequest,\n type PdfEditorFeatureFlags,\n type PdfEditorGlyph,\n type PdfEditorLeftPanel,\n type PdfEditorMode,\n type PdfEditorNoticeTone,\n type PdfEditorResolvedFeatures,\n type PdfEditorRightPanel,\n type PdfEditorScrollAreaViewportResolver,\n type PdfEditorSelectionAction,\n type PdfEditorSelectionPage,\n type PdfEditorSelectionPayload,\n} from "@/components/extend/pdf-editor-shared"\n\nexport type {\n PdfEditorFeatureFlags,\n PdfEditorLeftPanel,\n PdfEditorMode,\n PdfEditorNormalizedRect,\n PdfEditorRightPanel,\n PdfEditorSelectionAction,\n PdfEditorSelectionPayload,\n} from "@/components/extend/pdf-editor-shared"\n\n/* -------------------------------------------------------------------------- */\n/* Public types */\n/* -------------------------------------------------------------------------- */\n\nexport type PDFEditorPageOverlayProps = {\n pageNumber: number\n pageWidth: number\n pageHeight: number\n scale: number\n rotation: number\n}\n\nexport type PDFEditorZoomLevel = number | "fit-page" | "fit-width" | "automatic"\n\nexport type PDFEditorToast = {\n message: string\n tone: PdfEditorNoticeTone\n}\n\nexport type PDFEditorHandle = {\n /** Current PDF bytes including annotations, form values, and pending security changes. */\n getDocumentBuffer: () => Promise<ArrayBuffer>\n download: (fileName?: string) => Promise<void>\n print: (options?: PdfPrintOptions) => Promise<void>\n exportAnnotations: () => Promise<AnnotationTransferItem[]>\n importAnnotations: (items: AnnotationTransferItem[]) => void\n getFormValues: () => Record<string, string>\n setFormValues: (values: Record<string, string>) => Promise<void>\n /** Permanently applies every pending redaction mark. */\n applyRedactions: () => Promise<void>\n setMode: (mode: PdfEditorMode) => void\n /** Activates an EmbedPDF annotation tool id such as `highlight` or `ink`; `null` returns to selection. */\n setActiveTool: (toolId: string | null) => void\n scrollToPage: (pageNumber: number, options?: ScrollIntoViewOptions) => void\n undo: () => void\n redo: () => void\n getViewportElement: () => HTMLDivElement | null\n}\n\nexport type PDFEditorProps = {\n className?: string\n /** A URL, or the PDF bytes as an ArrayBuffer, Uint8Array, Blob, or File. */\n src?: string | ArrayBuffer | Uint8Array | Blob\n fileName?: string\n defaultZoom?: PDFEditorZoomLevel\n defaultMode?: PdfEditorMode\n /** Author written into new annotations. Defaults to "Guest". */\n annotationAuthor?: string\n colorPresets?: string[]\n /** Turn individual editing capabilities off. Everything is enabled by default. */\n features?: PdfEditorFeatureFlags\n showToolbar?: boolean\n showUpload?: boolean\n showDownload?: boolean\n toolbarActions?: React.ReactNode\n /** Extra actions for the text selection menu. Each receives normalized page coordinates. */\n selectionActions?: PdfEditorSelectionAction[]\n /** Persist saved signatures in localStorage. Pass a string to use a custom storage key. */\n persistSignatures?: boolean | string\n /** Additional rubber stamp manifests to load next to the built-in library. */\n stampManifests?: string[]\n /** Stylesheet used for the typed-signature fonts. Pass `null` to skip loading web fonts. */\n signatureFontsStylesheetUrl?: string | null\n resolveScrollAreaViewport?: PdfEditorScrollAreaViewportResolver\n renderPageOverlay?: (props: PDFEditorPageOverlayProps) => React.ReactNode\n onDocumentLoadSuccess?: (info: {\n numPages: number\n documentId: string\n fileName: string\n }) => void\n onDocumentLoadError?: (message: string) => void\n onActivePageChange?: (pageNumber: number) => void\n onModeChange?: (mode: PdfEditorMode) => void\n onAnnotationEvent?: (event: AnnotationEvent) => void\n /** Fires with the full annotation set after every committed change (debounced). */\n onAnnotationsChange?: (items: AnnotationTransferItem[]) => void\n onFormValuesChange?: (values: Record<string, string>) => void\n onRedactionsApplied?: () => void\n onSave?: (result: { buffer: ArrayBuffer; fileName: string }) => void\n onCapture?: (event: CaptureAreaEvent) => void\n onPdfUpload?: (file: File) => void\n /** Routes editor notices to a host-owned toast system instead of the built-in viewport. */\n onToast?: (toast: PDFEditorToast) => void\n onSelectionAction?: (\n actionId: string,\n payload: PdfEditorSelectionPayload\n ) => void\n}\n\n/* -------------------------------------------------------------------------- */\n/* Constants */\n/* -------------------------------------------------------------------------- */\n\nconst PAGE_GAP = 24\nconst THUMBNAIL_PAGE_WIDTH = 92\nconst THUMBNAIL_IMAGE_PADDING = 8\nconst THUMBNAIL_WIDTH = THUMBNAIL_PAGE_WIDTH + THUMBNAIL_IMAGE_PADDING * 2\nconst THUMBNAIL_LABEL_HEIGHT = 24\nconst THUMBNAIL_GAP = 12\nconst THUMBNAIL_PANE_PADDING_Y = 16\nconst LEFT_SIDEBAR_WIDTH_CLASS = "w-56"\nconst LEFT_SIDEBAR_CLOSED_CLASS = "-ml-56"\nconst RIGHT_PANEL_WIDTH_CLASS = "w-84"\nconst RIGHT_PANEL_INLINE_MIN_WIDTH = 1100\nconst TOOLBAR_STACK_MAX_WIDTH = 640\nconst ZOOM_PRESETS = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 3, 4]\nconst MIN_ZOOM = 0.1\nconst MAX_ZOOM = 8\nconst PAGE_BASE_RENDER_MAX_SCALE = 1\nconst PAGE_BASE_RENDER_DPR = 1\nconst SEARCH_DEBOUNCE_MS = 300\nconst NOTICE_DURATION_MS = 4200\nconst TOOLTIP_DELAY_MS = 5\nconst SELECTION_MENU_OFFSET = 8\nconst SELECTION_MENU_HEIGHT = 36\nconst DEFAULT_SIGNATURE_STORAGE_KEY = "pdf-editor:signatures"\nconst DEFAULT_ANNOTATION_AUTHOR = "Guest"\n\nconst ZOOM_MODE_LABELS: Record<ZoomMode, string> = {\n [ZoomMode.FitPage]: "Fit page",\n [ZoomMode.FitWidth]: "Fit width",\n [ZoomMode.Automatic]: "Automatic",\n}\nconst SPREAD_MODE_OPTIONS = [\n { label: "Single page", value: SpreadMode.None },\n { label: "Two pages", value: SpreadMode.Odd },\n { label: "Two pages, cover", value: SpreadMode.Even },\n]\nconst SCROLL_DIRECTION_OPTIONS = [\n { label: "Scroll down", value: "vertical" },\n { label: "Scroll sideways", value: "horizontal" },\n]\n\nfunction toZoomLevel(level: PDFEditorZoomLevel): ZoomMode | number {\n if (level === "fit-page") return ZoomMode.FitPage\n if (level === "fit-width") return ZoomMode.FitWidth\n if (level === "automatic") return ZoomMode.Automatic\n return level\n}\n\nfunction isZoomMode(value: unknown): value is ZoomMode {\n return (\n value === ZoomMode.FitPage ||\n value === ZoomMode.FitWidth ||\n value === ZoomMode.Automatic\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Engine + document source */\n/* -------------------------------------------------------------------------- */\n\nfunction useSharedPdfEngine() {\n const [engine, setEngine] = React.useState<PdfEngine | null>(null)\n const [error, setError] = React.useState<Error | null>(null)\n\n React.useEffect(() => {\n let cancelled = false\n\n loadSharedPdfEngine().then(\n (loadedEngine) => {\n if (!cancelled) setEngine(loadedEngine)\n },\n (loadError: Error) => {\n if (!cancelled) setError(loadError)\n }\n )\n\n return () => {\n cancelled = true\n }\n }, [])\n\n return { engine, error }\n}\n\ntype EditorSource =\n | { key: string; kind: "url"; url: string; name: string }\n | { key: string; kind: "buffer"; buffer: ArrayBuffer; name: string }\n\nlet sourceCounter = 0\n\nfunction nextSourceKey() {\n sourceCounter += 1\n return `pdf-editor-source-${sourceCounter}`\n}\n\nfunction bytesToArrayBuffer(bytes: Uint8Array) {\n const copy = new ArrayBuffer(bytes.byteLength)\n new Uint8Array(copy).set(bytes)\n return copy\n}\n\nfunction useEditorSource(\n src: PDFEditorProps["src"],\n fileName: string | undefined\n) {\n const [state, setState] = React.useState<{\n src: PDFEditorProps["src"]\n source: EditorSource | null\n loading: boolean\n }>({ src: undefined, source: null, loading: false })\n\n React.useEffect(() => {\n if (src === undefined || src === null) {\n setState({ src, source: null, loading: false })\n return\n }\n\n if (typeof src === "string") {\n setState({\n src,\n source: {\n key: nextSourceKey(),\n kind: "url",\n url: src,\n name: getPdfFileName(fileName, src),\n },\n loading: false,\n })\n return\n }\n\n if (src instanceof ArrayBuffer) {\n setState({\n src,\n source: {\n key: nextSourceKey(),\n kind: "buffer",\n buffer: src.slice(0),\n name: getPdfFileName(fileName),\n },\n loading: false,\n })\n return\n }\n\n if (src instanceof Uint8Array) {\n setState({\n src,\n source: {\n key: nextSourceKey(),\n kind: "buffer",\n buffer: bytesToArrayBuffer(src),\n name: getPdfFileName(fileName),\n },\n loading: false,\n })\n return\n }\n\n let cancelled = false\n const blobName = fileName ?? (src instanceof File ? src.name : undefined)\n\n setState({ src, source: null, loading: true })\n src.arrayBuffer().then((buffer) => {\n if (cancelled) return\n\n setState({\n src,\n source: {\n key: nextSourceKey(),\n kind: "buffer",\n buffer,\n name: getPdfFileName(blobName),\n },\n loading: false,\n })\n })\n\n return () => {\n cancelled = true\n }\n }, [fileName, src])\n\n const replace = React.useCallback((buffer: ArrayBuffer, name: string) => {\n setState((previous) => ({\n ...previous,\n source: { key: nextSourceKey(), kind: "buffer", buffer, name },\n loading: false,\n }))\n }, [])\n\n return { source: state.source, loading: state.loading, replace }\n}\n\n/* -------------------------------------------------------------------------- */\n/* Annotation JSON serialization */\n/* -------------------------------------------------------------------------- */\n\nfunction arrayBufferToBase64(buffer: ArrayBuffer) {\n const bytes = new Uint8Array(buffer)\n let binary = ""\n\n for (let index = 0; index < bytes.length; index += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000))\n }\n\n return btoa(binary)\n}\n\nfunction base64ToArrayBuffer(value: string) {\n const binary = atob(value)\n const bytes = new Uint8Array(binary.length)\n\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index)\n }\n\n return bytes.buffer\n}\n\ntype SerializedAnnotationItem = {\n annotation: PdfAnnotationObject\n ctx?: { data: string; mimeType?: string }\n}\n\nexport function serializeAnnotationItems(items: AnnotationTransferItem[]) {\n return {\n format: "extend-ui/pdf-editor-annotations",\n version: 1,\n exportedAt: new Date().toISOString(),\n annotations: items.map((item): SerializedAnnotationItem => {\n const context = item.ctx as\n | { data?: ArrayBuffer; mimeType?: string }\n | undefined\n\n return {\n annotation: item.annotation,\n ...(context?.data instanceof ArrayBuffer\n ? {\n ctx: {\n data: arrayBufferToBase64(context.data),\n mimeType: context.mimeType,\n },\n }\n : {}),\n }\n }),\n }\n}\n\nexport function deserializeAnnotationItems(\n payload: unknown\n): AnnotationTransferItem[] {\n const list = Array.isArray(payload)\n ? payload\n : payload &&\n typeof payload === "object" &&\n Array.isArray((payload as { annotations?: unknown }).annotations)\n ? (payload as { annotations: unknown[] }).annotations\n : null\n\n if (!list) throw new Error("Unrecognized annotation export.")\n\n return list.map((entry) => {\n const item = entry as SerializedAnnotationItem\n\n if (!item || typeof item !== "object" || !item.annotation) {\n throw new Error("Unrecognized annotation export.")\n }\n\n return {\n annotation: item.annotation,\n ...(item.ctx?.data\n ? {\n ctx: {\n data: base64ToArrayBuffer(item.ctx.data),\n mimeType: item.ctx.mimeType,\n } as AnnotationTransferItem["ctx"],\n }\n : {}),\n }\n })\n}\n\n/* -------------------------------------------------------------------------- */\n/* Viewport */\n/* -------------------------------------------------------------------------- */\n\nfunction PdfEditorViewport({\n children,\n className,\n documentId,\n}: {\n children: React.ReactNode\n className?: string\n documentId: string\n}) {\n const viewportRef = useViewportRef(documentId)\n const { provides: viewport } = useViewportCapability()\n const isGated = useIsViewportGated(documentId)\n const viewportGap = viewport?.getViewportGap() ?? 0\n\n return (\n <ViewportElementContext.Provider value={viewportRef}>\n <PdfEditorScrollArea\n className={className}\n orientation="both"\n scrollbarGutter={false}\n viewportClassName="relative select-none selection:bg-transparent selection:text-inherit"\n viewportProps={{ style: { padding: viewportGap } }}\n viewportRef={viewportRef}\n >\n {isGated ? null : children}\n </PdfEditorScrollArea>\n </ViewportElementContext.Provider>\n )\n}\n\nfunction PdfEditorViewportBridge({\n viewportElementRef,\n}: {\n viewportElementRef: React.MutableRefObject<HTMLDivElement | null>\n}) {\n const elementRef = useViewportElement()\n\n React.useEffect(() => {\n viewportElementRef.current = elementRef?.current ?? null\n })\n\n return null\n}\n\n/* -------------------------------------------------------------------------- */\n/* Selection menus rendered inside the page layers */\n/* -------------------------------------------------------------------------- */\n\nfunction SelectionMenuShell({\n rect,\n placement,\n menuWrapperProps,\n children,\n}: {\n rect: SelectionSelectionMenuProps["rect"]\n placement: SelectionSelectionMenuProps["placement"]\n menuWrapperProps: SelectionSelectionMenuProps["menuWrapperProps"]\n children: React.ReactNode\n}) {\n return (\n <div {...menuWrapperProps}>\n <div\n data-slot="pdf-editor-selection-menu"\n className="flex items-center gap-0.5 rounded-lg border bg-popover p-1 text-popover-foreground shadow-lg"\n style={{\n position: "absolute",\n left: 0,\n top: placement.suggestTop\n ? -(SELECTION_MENU_HEIGHT + SELECTION_MENU_OFFSET)\n : rect.size.height + SELECTION_MENU_OFFSET,\n pointerEvents: "auto",\n cursor: "default",\n whiteSpace: "nowrap",\n }}\n onPointerDown={(event) => event.stopPropagation()}\n >\n <TooltipProvider delay={TOOLTIP_DELAY_MS}>{children}</TooltipProvider>\n </div>\n </div>\n )\n}\n\nfunction MenuButton({\n label,\n glyph: Glyph,\n onClick,\n disabled,\n destructive,\n}: {\n label: string\n glyph: PdfEditorGlyph\n onClick: () => void\n disabled?: boolean\n destructive?: boolean\n}) {\n return (\n <PdfEditorToolButton\n label={label}\n size="icon-xs"\n disabled={disabled}\n className={cn(destructive && "text-destructive hover:text-destructive")}\n onClick={(event) => {\n event.stopPropagation()\n onClick()\n }}\n >\n <Glyph className="size-3.5" />\n </PdfEditorToolButton>\n )\n}\n\nasync function buildSelectionPayload(\n documentId: string,\n document: PdfDocumentObject | null,\n selectionScope: ReturnType<\n NonNullable<\n ReturnType<typeof useSelectionCapability>["provides"]\n >["forDocument"]\n >\n): Promise<PdfEditorSelectionPayload | null> {\n const formatted = selectionScope.getFormattedSelection()\n\n if (formatted.length === 0) return null\n\n let text = ""\n\n try {\n const lines = await selectionScope.getSelectedText().toPromise()\n text = lines.join("\\n")\n } catch {\n text = ""\n }\n\n const pages: PdfEditorSelectionPage[] = formatted.map((page) => {\n const pageSize = document?.pages[page.pageIndex]?.size ?? {\n width: 1,\n height: 1,\n }\n\n return {\n pageIndex: page.pageIndex,\n pageNumber: page.pageIndex + 1,\n pageSize,\n rect: page.rect,\n rects: page.segmentRects,\n normalizedRect: toNormalizedRect(page.rect, pageSize),\n normalizedRects: page.segmentRects.map((rect) =>\n toNormalizedRect(rect, pageSize)\n ),\n }\n })\n\n return { documentId, text, pages, ...pages[0] }\n}\n\nfunction PdfEditorTextSelectionMenu({\n documentId,\n rect,\n placement,\n menuWrapperProps,\n}: SelectionSelectionMenuProps & { documentId: string }) {\n const { provides: selectionCapability } = useSelectionCapability()\n const { provides: annotationCapability } = useAnnotationCapability()\n const { provides: annotation } = useAnnotation(documentId)\n const { provides: redaction } = useRedaction(documentId)\n const editor = usePdfEditor()\n const selectionScope = React.useMemo(\n () => selectionCapability?.forDocument(documentId) ?? null,\n [documentId, selectionCapability]\n )\n const canAnnotate =\n editor.features.annotate && editor.permissions.canModifyAnnotations\n const canRedact =\n editor.features.redact && editor.permissions.canModifyContents\n\n const createMarkup = (\n toolId: string,\n subtype:\n | PdfAnnotationSubtype.HIGHLIGHT\n | PdfAnnotationSubtype.UNDERLINE\n | PdfAnnotationSubtype.STRIKEOUT,\n options: { select?: boolean; openComments?: boolean } = {}\n ) => {\n if (!selectionScope || !annotation) return\n\n const formatted = selectionScope.getFormattedSelection()\n\n if (formatted.length === 0) return\n\n const defaults = (annotationCapability?.getTool(toolId)?.defaults ??\n {}) as Record<string, unknown>\n\n const finish = (text: string[]) => {\n let firstId: { pageIndex: number; id: string } | null = null\n\n for (const page of formatted) {\n const id = uuidV4()\n\n annotation.createAnnotation(page.pageIndex, {\n ...defaults,\n id,\n type: subtype,\n pageIndex: page.pageIndex,\n rect: page.rect,\n segmentRects: page.segmentRects,\n author: editor.annotationAuthor,\n created: new Date(),\n modified: new Date(),\n flags: ["print"],\n custom: text.length ? { text: text.join("\\n") } : undefined,\n } as PdfAnnotationObject)\n\n firstId ??= { pageIndex: page.pageIndex, id }\n }\n\n selectionScope.clear()\n\n if (options.select && firstId) {\n annotation.selectAnnotation(firstId.pageIndex, firstId.id)\n }\n\n if (options.openComments) editor.setRightPanel("comments")\n }\n\n selectionScope.getSelectedText().wait(finish, () => finish([]))\n }\n\n const runCustomAction = async (action: PdfEditorSelectionAction) => {\n if (!selectionScope) return\n\n const payload = await buildSelectionPayload(\n documentId,\n editor.document,\n selectionScope\n )\n\n if (!payload) return\n\n action.onSelect?.(payload)\n editor.onSelectionAction?.(action.id, payload)\n\n if (!action.keepSelection) selectionScope.clear()\n }\n\n return (\n <SelectionMenuShell\n rect={rect}\n placement={placement}\n menuWrapperProps={menuWrapperProps}\n >\n <MenuButton\n label="Copy"\n glyph={CopyGlyph}\n onClick={() => {\n selectionScope?.copyToClipboard()\n selectionScope?.clear()\n }}\n />\n {canAnnotate ? (\n <>\n <PdfEditorToolbarSeparator />\n <MenuButton\n label="Highlight"\n glyph={HighlighterGlyph}\n onClick={() =>\n createMarkup("highlight", PdfAnnotationSubtype.HIGHLIGHT)\n }\n />\n <MenuButton\n label="Underline"\n glyph={UnderlineGlyph}\n onClick={() =>\n createMarkup("underline", PdfAnnotationSubtype.UNDERLINE)\n }\n />\n <MenuButton\n label="Strikethrough"\n glyph={StrikethroughGlyph}\n onClick={() =>\n createMarkup("strikeout", PdfAnnotationSubtype.STRIKEOUT)\n }\n />\n {editor.features.comments ? (\n <MenuButton\n label="Comment"\n glyph={CommentGlyph}\n onClick={() =>\n createMarkup("highlight", PdfAnnotationSubtype.HIGHLIGHT, {\n select: true,\n openComments: true,\n })\n }\n />\n ) : null}\n <MenuButton\n label="Add link"\n glyph={LinkGlyph}\n onClick={() =>\n editor.openDialog({ type: "link", source: "selection" })\n }\n />\n </>\n ) : null}\n {canRedact ? (\n <>\n <PdfEditorToolbarSeparator />\n <MenuButton\n label="Mark for redaction"\n glyph={EyeOffGlyph}\n onClick={() => {\n redaction?.queueCurrentSelectionAsPending().wait(\n () => {\n selectionScope?.clear()\n editor.setRightPanel("redactions")\n },\n () =>\n editor.notify("The selection could not be marked.", "error")\n )\n }}\n />\n </>\n ) : null}\n {editor.selectionActions.length > 0 ? (\n <>\n <PdfEditorToolbarSeparator />\n {editor.selectionActions.map((action) => (\n <PdfEditorTooltip key={action.id} label={action.label}>\n <Button\n type="button"\n size="xs"\n variant="ghost"\n onClick={(event) => {\n event.stopPropagation()\n void runCustomAction(action)\n }}\n >\n {action.icon}\n {action.label}\n </Button>\n </PdfEditorTooltip>\n ))}\n </>\n ) : null}\n </SelectionMenuShell>\n )\n}\n\nconst STAMP_SOURCE_TYPES = new Set<PdfAnnotationSubtype>([\n PdfAnnotationSubtype.INK,\n PdfAnnotationSubtype.SQUARE,\n PdfAnnotationSubtype.CIRCLE,\n PdfAnnotationSubtype.LINE,\n PdfAnnotationSubtype.POLYLINE,\n PdfAnnotationSubtype.POLYGON,\n PdfAnnotationSubtype.FREETEXT,\n PdfAnnotationSubtype.STAMP,\n PdfAnnotationSubtype.TEXT,\n])\n\nfunction PdfEditorAnnotationMenu({\n documentId,\n selected,\n context,\n rect,\n placement,\n menuWrapperProps,\n}: AnnotationSelectionMenuProps & { documentId: string }) {\n const { provides: annotation } = useAnnotation(documentId)\n const { provides: redaction } = useRedaction(documentId)\n const editor = usePdfEditor()\n\n if (!selected || !annotation) return null\n\n const object = context.annotation.object\n const { pageIndex, id } = object\n const isRedact = object.type === PdfAnnotationSubtype.REDACT\n const isWidget = object.type === PdfAnnotationSubtype.WIDGET\n const isLink = object.type === PdfAnnotationSubtype.LINK\n const isLocked = (object.flags ?? []).includes("locked")\n const canModify = editor.permissions.canModifyAnnotations\n const canDelete = canModify && !context.structurallyLocked\n\n const remove = () => annotation.deleteAnnotation(pageIndex, id)\n\n if (isRedact) {\n return (\n <SelectionMenuShell\n rect={rect}\n placement={placement}\n menuWrapperProps={menuWrapperProps}\n >\n <MenuButton\n label="Apply redaction"\n glyph={EyeOffGlyph}\n disabled={!editor.permissions.canModifyContents}\n onClick={() =>\n editor.openDialog({\n type: "confirm",\n title: "Apply this redaction?",\n description: "The marked content is removed permanently.",\n confirmLabel: "Apply",\n onConfirm: () => {\n redaction\n ?.commitPending(pageIndex, id)\n .wait(noop, () =>\n editor.notify(\n "The redaction could not be applied.",\n "error"\n )\n )\n },\n })\n }\n />\n <MenuButton\n label="Style"\n glyph={SlidersGlyph}\n onClick={() => editor.setRightPanel("properties")}\n />\n <MenuButton\n label="Remove mark"\n glyph={TrashGlyph}\n destructive\n onClick={remove}\n />\n </SelectionMenuShell>\n )\n }\n\n if (isLink) {\n const target = (object as PdfLinkAnnoObject).target\n\n return (\n <SelectionMenuShell\n rect={rect}\n placement={placement}\n menuWrapperProps={menuWrapperProps}\n >\n <MenuButton\n label="Open link"\n glyph={ExternalLinkGlyph}\n disabled={!target}\n onClick={() => {\n if (!target) return\n\n annotation.navigateTarget(target).wait((result) => {\n if (result.outcome === "uri") {\n window.open(result.uri, "_blank", "noopener")\n }\n }, noop)\n }}\n />\n <MenuButton\n label="Edit link"\n glyph={EditGlyph}\n disabled={!canModify}\n onClick={() =>\n editor.openDialog({ type: "link", source: "annotation" })\n }\n />\n <MenuButton\n label="Delete"\n glyph={TrashGlyph}\n destructive\n disabled={!canDelete}\n onClick={remove}\n />\n </SelectionMenuShell>\n )\n }\n\n return (\n <SelectionMenuShell\n rect={rect}\n placement={placement}\n menuWrapperProps={menuWrapperProps}\n >\n {!isWidget && editor.features.comments ? (\n <MenuButton\n label="Comment"\n glyph={CommentGlyph}\n onClick={() => editor.setRightPanel("comments")}\n />\n ) : null}\n <MenuButton\n label="Properties"\n glyph={SlidersGlyph}\n onClick={() => editor.setRightPanel("properties")}\n />\n {!isWidget && canModify ? (\n <MenuButton\n label="Add link"\n glyph={LinkGlyph}\n onClick={() =>\n editor.openDialog({ type: "link", source: "annotation" })\n }\n />\n ) : null}\n {!isWidget &&\n editor.features.stamps &&\n canModify &&\n STAMP_SOURCE_TYPES.has(object.type) ? (\n <MenuButton\n label="Save as stamp"\n glyph={StampGlyph}\n onClick={() => editor.setRightPanel("stamps")}\n />\n ) : null}\n {!isWidget && canModify ? (\n <MenuButton\n label={isLocked ? "Unlock" : "Lock"}\n glyph={isLocked ? UnlockGlyph : LockGlyph}\n onClick={() => {\n const flags = object.flags ?? []\n annotation.updateAnnotation(pageIndex, id, {\n flags: isLocked\n ? flags.filter((flag) => flag !== "locked")\n : [...flags, "locked"],\n })\n }}\n />\n ) : null}\n <MenuButton\n label="Delete"\n glyph={TrashGlyph}\n destructive\n disabled={!canDelete}\n onClick={remove}\n />\n </SelectionMenuShell>\n )\n}\n\nfunction PdfEditorGroupMenu({\n documentId,\n selected,\n context,\n rect,\n placement,\n menuWrapperProps,\n}: GroupSelectionMenuProps & { documentId: string }) {\n const { provides: annotation } = useAnnotation(documentId)\n const editor = usePdfEditor()\n\n if (!selected || !annotation) return null\n\n const groupingAction = annotation.getGroupingAction()\n const canModify = editor.permissions.canModifyAnnotations\n\n return (\n <SelectionMenuShell\n rect={rect}\n placement={placement}\n menuWrapperProps={menuWrapperProps}\n >\n <span className="px-1.5 text-xs text-muted-foreground">\n {context.annotations.length} selected\n </span>\n <MenuButton\n label={groupingAction === "ungroup" ? "Ungroup" : "Group"}\n glyph={groupingAction === "ungroup" ? UngroupGlyph : GroupGlyph}\n disabled={!canModify || groupingAction === "disabled"}\n onClick={() => {\n if (groupingAction === "ungroup") {\n annotation.ungroupAnnotations(context.annotations[0].object.id)\n } else {\n annotation.groupAnnotations()\n }\n }}\n />\n <MenuButton\n label="Properties"\n glyph={SlidersGlyph}\n onClick={() => editor.setRightPanel("properties")}\n />\n <MenuButton\n label="Delete all"\n glyph={TrashGlyph}\n destructive\n disabled={!canModify}\n onClick={() =>\n annotation.deleteAnnotations(\n context.annotations.map((item) => ({\n pageIndex: item.object.pageIndex,\n id: item.object.id,\n }))\n )\n }\n />\n </SelectionMenuShell>\n )\n}\n\nfunction PdfEditorRedactionMenu({\n documentId,\n selected,\n context,\n rect,\n placement,\n menuWrapperProps,\n}: RedactionSelectionMenuProps & { documentId: string }) {\n const { provides: redaction } = useRedaction(documentId)\n const editor = usePdfEditor()\n\n if (!selected || !redaction) return null\n\n const { page, id } = context.item\n\n return (\n <SelectionMenuShell\n rect={rect}\n placement={placement}\n menuWrapperProps={menuWrapperProps}\n >\n <MenuButton\n label="Apply redaction"\n glyph={EyeOffGlyph}\n disabled={!editor.permissions.canModifyContents}\n onClick={() =>\n editor.openDialog({\n type: "confirm",\n title: "Apply this redaction?",\n description: "The marked content is removed permanently.",\n confirmLabel: "Apply",\n onConfirm: () => {\n redaction\n .commitPending(page, id)\n .wait(noop, () =>\n editor.notify("The redaction could not be applied.", "error")\n )\n },\n })\n }\n />\n <MenuButton\n label="Remove mark"\n glyph={TrashGlyph}\n destructive\n onClick={() => redaction.removePending(page, id)}\n />\n </SelectionMenuShell>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Toolbar controls */\n/* -------------------------------------------------------------------------- */\n\nfunction PdfEditorPageControl({\n activePage,\n numPages,\n disabled,\n onPageChange,\n}: {\n activePage: number\n numPages: number\n disabled: boolean\n onPageChange: (pageNumber: number) => void\n}) {\n const inputRef = React.useRef<HTMLInputElement>(null)\n const displayPage = numPages ? activePage : 1\n const [isEditing, setIsEditing] = React.useState(false)\n const [draftPage, setDraftPage] = React.useState(() => String(displayPage))\n\n React.useEffect(() => {\n if (!isEditing) return\n\n inputRef.current?.focus()\n inputRef.current?.select()\n }, [isEditing])\n\n const applyPageDraft = React.useCallback(\n (value: string) => {\n const trimmedValue = value.trim()\n\n if (!trimmedValue) return\n\n const parsedPage = Number(trimmedValue)\n\n if (!Number.isInteger(parsedPage)) return\n\n onPageChange(Math.min(Math.max(parsedPage, 1), Math.max(numPages, 1)))\n },\n [numPages, onPageChange]\n )\n\n return (\n <div className="flex items-center text-sm whitespace-nowrap text-primary">\n <span>Page</span>\n {isEditing ? (\n <Input\n ref={inputRef}\n aria-label="Page number"\n inputMode="numeric"\n pattern="[0-9]*"\n size="sm"\n value={draftPage}\n className="mx-1 w-14 min-w-14 rounded-md [&_[data-slot=input]]:text-center"\n onBlur={() => setIsEditing(false)}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) => {\n const nextValue = event.target.value\n\n setDraftPage(nextValue)\n applyPageDraft(nextValue)\n }}\n onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key === "Enter" || event.key === "Escape") {\n event.currentTarget.blur()\n }\n }}\n />\n ) : (\n <Button\n type="button"\n variant="ghost"\n size="sm"\n className="font-normal"\n aria-label={`Current page ${displayPage}. Edit page number`}\n disabled={disabled || !numPages}\n onClick={() => {\n setDraftPage(String(displayPage))\n setIsEditing(true)\n }}\n >\n {displayPage}\n </Button>\n )}\n <span>of {numPages || "–"}</span>\n </div>\n )\n}\n\nfunction PdfEditorZoomControl({\n documentId,\n disabled,\n}: {\n documentId: string\n disabled: boolean\n}) {\n const { state, provides: zoom } = useZoom(documentId)\n const current = state.currentZoomLevel\n const selectValue = isZoomMode(state.zoomLevel)\n ? state.zoomLevel\n : String(Number(current.toFixed(2)))\n const presets = ZOOM_PRESETS.includes(Number(current.toFixed(2)))\n ? ZOOM_PRESETS\n : [...ZOOM_PRESETS, Number(current.toFixed(2))].sort((a, b) => a - b)\n\n return (\n <div className="flex items-center gap-0.5">\n <PdfEditorToolButton\n label="Zoom out"\n shortcut="mod+-"\n disabled={disabled || current <= MIN_ZOOM}\n onClick={() => zoom?.zoomOut()}\n >\n <ZoomOutGlyph className="size-4" />\n </PdfEditorToolButton>\n <Select\n value={selectValue}\n disabled={disabled}\n modal={false}\n onValueChange={(value) => {\n const next = String(value)\n zoom?.requestZoom(isZoomMode(next) ? next : Number(next))\n }}\n >\n <SelectTrigger\n size="sm"\n className="w-[104px] min-w-[104px]"\n aria-label="Zoom level"\n >\n <SelectValue placeholder="Zoom">\n {Math.round(current * 100)}%\n </SelectValue>\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {(Object.keys(ZOOM_MODE_LABELS) as ZoomMode[]).map((mode) => (\n <SelectItem key={mode} value={mode}>\n {ZOOM_MODE_LABELS[mode]}\n </SelectItem>\n ))}\n {presets.map((preset) => (\n <SelectItem key={preset} value={String(preset)}>\n {Math.round(preset * 100)}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <PdfEditorToolButton\n label="Zoom in"\n shortcut="mod+="\n disabled={disabled || current >= MAX_ZOOM}\n onClick={() => zoom?.zoomIn()}\n >\n <ZoomInGlyph className="size-4" />\n </PdfEditorToolButton>\n </div>\n )\n}\n\nfunction PdfEditorSearchControl({\n documentId,\n disabled,\n open,\n onOpenChange,\n}: {\n documentId: string\n disabled: boolean\n open: boolean\n onOpenChange: (open: boolean) => void\n}) {\n const { state, provides } = useSearch(documentId)\n const { provides: scroll } = useScroll(documentId)\n const [draft, setDraft] = React.useState("")\n const [query, setQuery] = React.useState("")\n const [isSearching, setIsSearching] = React.useState(false)\n const providesRef = React.useRef(provides)\n const scrollRef = React.useRef(scroll)\n const requestIdRef = React.useRef(0)\n const inputRef = React.useRef<HTMLInputElement>(null)\n\n React.useEffect(() => {\n providesRef.current = provides\n scrollRef.current = scroll\n }, [provides, scroll])\n\n React.useEffect(() => {\n if (!open) return\n\n const frame = window.requestAnimationFrame(() => inputRef.current?.focus())\n\n return () => window.cancelAnimationFrame(frame)\n }, [open])\n\n const scrollToResult = React.useCallback(\n (index: number) => {\n const result = state.results[index]\n if (!result || !scroll) return\n\n const firstRect = result.rects[0]\n\n scroll.scrollToPage({\n pageNumber: result.pageIndex + 1,\n ...(firstRect\n ? {\n pageCoordinates: { x: firstRect.origin.x, y: firstRect.origin.y },\n alignY: 30,\n }\n : {}),\n behavior: "auto",\n })\n },\n [scroll, state.results]\n )\n\n const runSearch = React.useCallback((rawQuery: string) => {\n const nextQuery = rawQuery.trim()\n const requestId = requestIdRef.current + 1\n requestIdRef.current = requestId\n setQuery(nextQuery)\n\n const searchProvider = providesRef.current\n const scrollProvider = scrollRef.current\n\n if (!searchProvider) {\n setIsSearching(false)\n return\n }\n\n if (!nextQuery) {\n searchProvider.stopSearch()\n setIsSearching(false)\n return\n }\n\n setIsSearching(true)\n searchProvider.startSearch()\n searchProvider.searchAllPages(nextQuery).wait(\n (result) => {\n if (requestIdRef.current !== requestId) return\n\n const first = result.results[0]\n\n if (first && scrollProvider) {\n searchProvider.goToResult(0)\n const firstRect = first.rects[0]\n\n scrollProvider.scrollToPage({\n pageNumber: first.pageIndex + 1,\n ...(firstRect\n ? {\n pageCoordinates: {\n x: firstRect.origin.x,\n y: firstRect.origin.y,\n },\n alignY: 30,\n }\n : {}),\n behavior: "auto",\n })\n }\n\n setIsSearching(false)\n },\n () => {\n if (requestIdRef.current === requestId) setIsSearching(false)\n }\n )\n }, [])\n\n React.useEffect(() => {\n if (!draft.trim()) return\n\n const timeout = window.setTimeout(\n () => runSearch(draft),\n SEARCH_DEBOUNCE_MS\n )\n\n return () => window.clearTimeout(timeout)\n }, [draft, runSearch])\n\n const clear = () => {\n requestIdRef.current += 1\n setDraft("")\n setQuery("")\n setIsSearching(false)\n provides?.stopSearch()\n }\n\n const navigate = (direction: 1 | -1) => {\n if (!provides || state.total === 0) return\n\n scrollToResult(\n direction === 1 ? provides.nextResult() : provides.previousResult()\n )\n }\n\n const resultLabel = isSearching\n ? "Searching…"\n : !query\n ? "Type to search"\n : state.total\n ? `${state.activeResultIndex + 1} / ${state.total}`\n : "No results"\n\n return (\n <Popover open={open} onOpenChange={onOpenChange}>\n <PdfEditorTooltip label="Search" shortcut="mod+F">\n <PopoverTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search"\n disabled={disabled}\n className={cn(query && "text-primary")}\n >\n <SearchGlyph className="size-4" />\n </Button>\n </PopoverTrigger>\n </PdfEditorTooltip>\n <PopoverContent align="end" className="w-72 p-3">\n <div className="space-y-3">\n <Input\n ref={inputRef}\n placeholder="Search text"\n value={draft}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) => {\n const next = event.target.value\n setDraft(next)\n\n if (next.trim()) {\n setIsSearching(true)\n } else {\n clear()\n }\n }}\n onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key !== "Enter") return\n\n event.preventDefault()\n\n if (state.total) {\n navigate(event.shiftKey ? -1 : 1)\n } else if (draft.trim()) {\n runSearch(draft)\n }\n }}\n />\n <div className="flex items-center justify-between gap-2">\n <div className="min-w-0 truncate text-xs text-muted-foreground">\n {resultLabel}\n </div>\n <div className="flex shrink-0 items-center gap-1">\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Previous result"\n disabled={isSearching || state.total === 0}\n onClick={() => navigate(-1)}\n >\n <ChevronLeftGlyph className="size-4" />\n </Button>\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Next result"\n disabled={isSearching || state.total === 0}\n onClick={() => navigate(1)}\n >\n <ChevronRightGlyph className="size-4" />\n </Button>\n <Button type="button" variant="outline" size="sm" onClick={clear}>\n Clear\n </Button>\n </div>\n </div>\n </div>\n </PopoverContent>\n </Popover>\n )\n}\n\nfunction PdfEditorModeSwitch({\n mode,\n features,\n compact = false,\n onModeChange,\n}: {\n mode: PdfEditorMode\n features: PdfEditorResolvedFeatures\n compact?: boolean\n onModeChange: (mode: PdfEditorMode) => void\n}) {\n const options = PDF_EDITOR_MODE_OPTIONS.filter(\n (option) => option.feature === null || features[option.feature]\n )\n\n return (\n <div\n role="group"\n aria-label="Editor mode"\n className="flex shrink-0 items-center gap-0.5 rounded-lg bg-muted p-0.5"\n >\n {options.map((option) => {\n const Glyph = option.glyph\n const active = option.id === mode\n\n return (\n <Button\n key={option.id}\n type="button"\n size={compact ? "icon-xs" : "xs"}\n variant={active ? "default" : "ghost"}\n aria-pressed={active}\n aria-label={option.label}\n className={cn("gap-1.5", !active && "text-muted-foreground")}\n onClick={() => onModeChange(option.id)}\n >\n <Glyph className="size-3.5" />\n {compact ? null : (\n <span className="hidden md:inline">{option.label}</span>\n )}\n </Button>\n )\n })}\n </div>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Side panel shells */\n/* -------------------------------------------------------------------------- */\n\nfunction PanelTabStrip<T extends string>({\n tabs,\n value,\n onChange,\n onClose,\n label,\n}: {\n tabs: Array<{ id: T; label: string; glyph: PdfEditorGlyph }>\n value: T | null\n onChange: (value: T) => void\n onClose: () => void\n label: string\n}) {\n return (\n <div className="flex shrink-0 items-center justify-between gap-1 border-b px-1.5 py-1">\n <TooltipProvider delay={TOOLTIP_DELAY_MS}>\n <div\n className="flex min-w-0 items-center gap-0.5 overflow-x-auto"\n role="tablist"\n aria-label={label}\n >\n {tabs.map((tab) => {\n const Glyph = tab.glyph\n\n return (\n <PdfEditorToolButton\n key={tab.id}\n label={tab.label}\n active={value === tab.id}\n role="tab"\n aria-selected={value === tab.id}\n onClick={() => onChange(tab.id)}\n >\n <Glyph className="size-4" />\n </PdfEditorToolButton>\n )\n })}\n </div>\n <PdfEditorToolButton\n label="Close panel"\n size="icon-xs"\n onClick={onClose}\n >\n <CloseGlyph className="size-3.5" />\n </PdfEditorToolButton>\n </TooltipProvider>\n </div>\n )\n}\n\nfunction PdfEditorRightPanelShell({\n open,\n inline,\n children,\n}: {\n open: boolean\n inline: boolean\n children: React.ReactNode\n}) {\n return (\n <aside\n data-slot="pdf-editor-right-panel"\n data-panel-open={open ? "true" : "false"}\n className={cn(\n "absolute inset-y-0 right-0 z-30 flex shrink-0 flex-col overflow-hidden border-l bg-sidebar shadow-lg transition-[translate,margin-right] duration-200 ease-out",\n RIGHT_PANEL_WIDTH_CLASS,\n inline && "relative z-auto translate-x-0 shadow-none",\n open\n ? "mr-0 translate-x-0"\n : inline\n ? "-mr-84 border-l-0"\n : "pointer-events-none translate-x-full border-l-0"\n )}\n >\n {children}\n </aside>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Signature persistence + engine warm-up utilities */\n/* -------------------------------------------------------------------------- */\n\nfunction PdfEditorSignaturePersistence({\n storageKey,\n}: {\n storageKey: string | null\n}) {\n const { provides: signatureCapability } = useSignatureCapability()\n\n React.useEffect(() => {\n if (!signatureCapability || !storageKey) return\n\n try {\n const raw = window.localStorage.getItem(storageKey)\n\n if (raw && signatureCapability.getEntries().length === 0) {\n signatureCapability.loadEntries(deserializeEntries(JSON.parse(raw)))\n }\n } catch {\n // Ignore corrupt or unavailable storage.\n }\n\n return signatureCapability.onEntriesChange((entries) => {\n try {\n window.localStorage.setItem(\n storageKey,\n JSON.stringify(serializeEntries(entries))\n )\n } catch {\n // Storage may be unavailable (private mode, quota).\n }\n })\n }, [signatureCapability, storageKey])\n\n return null\n}\n\n/* -------------------------------------------------------------------------- */\n/* Fallback shell (engine loading, document loading, errors, empty) */\n/* -------------------------------------------------------------------------- */\n\nfunction PdfEditorFallbackShell({\n className,\n fileName,\n showToolbar,\n showUpload,\n state,\n errorMessage = "The PDF could not be loaded.",\n onUploadFile,\n children,\n}: {\n className?: string\n fileName?: string\n showToolbar: boolean\n showUpload: boolean\n state: "loading" | "error" | "empty" | "password"\n errorMessage?: string\n onUploadFile?: (file: File) => void\n children?: React.ReactNode\n}) {\n const inputRef = React.useRef<HTMLInputElement>(null)\n\n return (\n <div\n data-slot="pdf-editor"\n data-state={state}\n className={cn(\n "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n {showToolbar ? (\n <div className="flex min-h-12 items-center justify-between gap-2 border-b px-3 py-2">\n <div className="flex min-w-0 items-center gap-2 text-sm">\n <FileTextGlyph className="size-4 shrink-0 text-muted-foreground" />\n <span className="truncate text-muted-foreground">\n {fileName ?? "PDF editor"}\n </span>\n </div>\n {showUpload && onUploadFile ? (\n <>\n <input\n ref={inputRef}\n type="file"\n accept="application/pdf,.pdf"\n className="sr-only"\n tabIndex={-1}\n onChange={(event) => {\n const file = event.target.files?.[0]\n if (file) onUploadFile(file)\n event.currentTarget.value = ""\n }}\n />\n <Button\n type="button"\n size="sm"\n variant="outline"\n onClick={() => inputRef.current?.click()}\n >\n <UploadGlyph className="size-4" />\n Open PDF\n </Button>\n </>\n ) : null}\n </div>\n ) : null}\n <div className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30">\n {children ? (\n children\n ) : state === "loading" ? (\n <div className="grid flex-1 place-items-center">\n <Spinner className="size-4" />\n </div>\n ) : state === "error" ? (\n <div className="grid flex-1 place-items-center p-6 text-center text-sm text-muted-foreground">\n {errorMessage}\n </div>\n ) : (\n <div className="grid flex-1 place-items-center p-6 text-center text-sm text-muted-foreground">\n <div className="max-w-sm space-y-3">\n <div className="font-medium text-foreground">\n Open a PDF to start editing\n </div>\n <div>\n Pass a URL or file with the <code>src</code> prop, or use the\n upload control.\n </div>\n </div>\n </div>\n )}\n </div>\n </div>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Editor (per loaded document) */\n/* -------------------------------------------------------------------------- */\n\ntype EditorHandleImpl = PDFEditorHandle\n\ntype PdfEditorInnerProps = {\n documentId: string\n document: PdfDocumentObject | null\n fileName: string\n className?: string\n defaultZoom: PDFEditorZoomLevel\n defaultMode: PdfEditorMode\n leftPanel: PdfEditorLeftPanel | null\n setLeftPanel: React.Dispatch<React.SetStateAction<PdfEditorLeftPanel | null>>\n formDesignMode: boolean\n setFormDesignMode: React.Dispatch<React.SetStateAction<boolean>>\n annotationAuthor: string\n features: PdfEditorResolvedFeatures\n showToolbar: boolean\n showUpload: boolean\n showDownload: boolean\n toolbarActions?: React.ReactNode\n selectionActions: PdfEditorSelectionAction[]\n signatureFontsStylesheetUrl: string | null\n renderPageOverlay?: (props: PDFEditorPageOverlayProps) => React.ReactNode\n handleRef: React.MutableRefObject<EditorHandleImpl | null>\n onReplaceDocument: (buffer: ArrayBuffer, fileName: string) => void\n onUploadFile: (file: File) => void\n onActivePageChange?: (pageNumber: number) => void\n onModeChange?: (mode: PdfEditorMode) => void\n onAnnotationEvent?: (event: AnnotationEvent) => void\n onAnnotationsChange?: (items: AnnotationTransferItem[]) => void\n onFormValuesChange?: (values: Record<string, string>) => void\n onRedactionsApplied?: () => void\n onSave?: (result: { buffer: ArrayBuffer; fileName: string }) => void\n onCapture?: (event: CaptureAreaEvent) => void\n onToast?: (toast: PDFEditorToast) => void\n onSelectionAction?: (\n actionId: string,\n payload: PdfEditorSelectionPayload\n ) => void\n}\n\nconst LEFT_PANEL_TABS: Array<{\n id: PdfEditorLeftPanel\n label: string\n glyph: PdfEditorGlyph\n feature: keyof PdfEditorFeatureFlags | null\n}> = [\n { id: "thumbnails", label: "Thumbnails", glyph: GridGlyph, feature: null },\n { id: "outline", label: "Outline", glyph: ListTreeGlyph, feature: "outline" },\n {\n id: "attachments",\n label: "Attachments",\n glyph: PaperclipGlyph,\n feature: "attachments",\n },\n {\n id: "pages",\n label: "Organize pages",\n glyph: LayersGlyph,\n feature: "pages",\n },\n]\n\nconst RIGHT_PANEL_TABS: Array<{\n id: PdfEditorRightPanel\n label: string\n glyph: PdfEditorGlyph\n feature: keyof PdfEditorFeatureFlags | null\n}> = [\n { id: "properties", label: "Properties", glyph: SlidersGlyph, feature: null },\n {\n id: "comments",\n label: "Comments",\n glyph: CommentsGlyph,\n feature: "comments",\n },\n {\n id: "redactions",\n label: "Redactions",\n glyph: EyeOffGlyph,\n feature: "redact",\n },\n { id: "stamps", label: "Stamps", glyph: StampGlyph, feature: "stamps" },\n {\n id: "signatures",\n label: "Signatures",\n glyph: SignatureGlyph,\n feature: "sign",\n },\n {\n id: "forms",\n label: "Form fields",\n glyph: TextFieldGlyph,\n feature: "forms",\n },\n]\n\nfunction PdfEditorInner({\n documentId,\n document: pdfDocument,\n fileName,\n className,\n defaultZoom,\n defaultMode,\n leftPanel,\n setLeftPanel,\n formDesignMode,\n setFormDesignMode,\n annotationAuthor,\n features,\n showToolbar,\n showUpload,\n showDownload,\n toolbarActions,\n selectionActions,\n signatureFontsStylesheetUrl,\n renderPageOverlay,\n handleRef,\n onReplaceDocument,\n onUploadFile,\n onActivePageChange,\n onModeChange,\n onAnnotationEvent,\n onAnnotationsChange,\n onFormValuesChange,\n onRedactionsApplied,\n onSave,\n onCapture,\n onToast,\n onSelectionAction,\n}: PdfEditorInnerProps) {\n const { registry } = useRegistry()\n const permissions = useDocumentPermissions(documentId)\n const { state: scrollState, provides: scroll } = useScroll(documentId)\n const { provides: scrollCapability } = useScrollCapability()\n const { state: zoomState, provides: zoom } = useZoom(documentId)\n const { provides: rotate } = useRotate(documentId)\n const { spreadMode, provides: spread } = useSpread(documentId)\n const { provides: pan, isPanning } = usePan(documentId)\n const { state: captureState, provides: capture } = useCapture(documentId)\n const { provides: fullscreen, state: fullscreenState } = useFullscreen()\n const { provides: historyCapability } = useHistoryCapability()\n const { provides: annotationCapability } = useAnnotationCapability()\n const { state: annotationState, provides: annotation } =\n useAnnotation(documentId)\n const { state: redactionState, provides: redaction } =\n useRedaction(documentId)\n const { provides: exportScope } = useExport(documentId)\n const { provides: print } = usePrint(documentId)\n const { provides: formCapability } = useFormCapability()\n const { provides: selectionCapability } = useSelectionCapability()\n\n const [mode, setModeState] = React.useState<PdfEditorMode>(defaultMode)\n const [rightPanel, setRightPanel] =\n React.useState<PdfEditorRightPanel | null>(null)\n const [dialog, setDialog] = React.useState<PdfEditorDialogRequest | null>(\n null\n )\n const [searchOpen, setSearchOpen] = React.useState(false)\n const [historyState, setHistoryState] = React.useState({\n canUndo: false,\n canRedo: false,\n })\n const [horizontalScroll, setHorizontalScroll] = React.useState(false)\n const [isDownloading, setIsDownloading] = React.useState(false)\n\n const rootRef = React.useRef<HTMLDivElement | null>(null)\n const [toastContainer, setToastContainer] =\n React.useState<HTMLDivElement | null>(null)\n const [editorToastManager] = React.useState(() =>\n ToastPrimitive.createToastManager()\n )\n const viewportElementRef = React.useRef<HTMLDivElement | null>(null)\n const uploadInputRef = React.useRef<HTMLInputElement>(null)\n const annotationImportInputRef = React.useRef<HTMLInputElement>(null)\n const [shellRef, shellWidth] = useElementWidth<HTMLDivElement>()\n const leftInline = useInlineThumbnailSidebar(shellWidth)\n const rightInline = shellWidth >= RIGHT_PANEL_INLINE_MIN_WIDTH\n const compactToolbar = shellWidth > 0 && shellWidth <= TOOLBAR_STACK_MAX_WIDTH\n\n const activePage = scrollState.currentPage\n const numPages = pdfDocument?.pageCount ?? 0\n const isLoading = !pdfDocument\n const controlsDisabled = !numPages\n const currentZoom = zoomState.currentZoomLevel\n const selectedAnnotations = React.useMemo(\n () => getSelectedAnnotations(annotationState),\n [annotationState]\n )\n const activeToolId = annotationState.activeToolId\n const activeTool = React.useMemo(\n () =>\n activeToolId && annotationCapability\n ? annotationCapability.getTool(activeToolId)\n : null,\n [activeToolId, annotationCapability]\n )\n const historyScope = React.useMemo(\n () => historyCapability?.forDocument(documentId) ?? null,\n [documentId, historyCapability]\n )\n const formScope = React.useMemo(\n () => formCapability?.forDocument(documentId) ?? null,\n [documentId, formCapability]\n )\n const selectionScope = React.useMemo(\n () => selectionCapability?.forDocument(documentId) ?? null,\n [documentId, selectionCapability]\n )\n\n /* ---- notices ---------------------------------------------------------- */\n\n const notify = React.useCallback(\n (message: string, tone: PdfEditorNoticeTone = "info") => {\n if (onToast) {\n onToast({ message, tone })\n return\n }\n\n editorToastManager.add({ title: message, type: tone })\n },\n [editorToastManager, onToast]\n )\n\n const setRootElement = React.useCallback((element: HTMLDivElement | null) => {\n rootRef.current = element\n setToastContainer(element)\n }, [])\n\n /* ---- tool helpers ----------------------------------------------------- */\n\n const deactivateTools = React.useCallback(() => {\n annotation?.setActiveTool(null)\n if (redactionState.isRedacting) redaction?.endRedact()\n if (isPanning) pan?.disablePan()\n if (captureState.isMarqueeCaptureActive) capture?.disableMarqueeCapture()\n if (zoomState.isMarqueeZoomActive) zoom?.disableMarqueeZoom()\n }, [\n annotation,\n capture,\n captureState.isMarqueeCaptureActive,\n isPanning,\n pan,\n redaction,\n redactionState.isRedacting,\n zoom,\n zoomState.isMarqueeZoomActive,\n ])\n\n const setActiveTool = React.useCallback(\n (toolId: string | null) => {\n if (!annotation) return\n\n if (isPanning) pan?.disablePan()\n if (captureState.isMarqueeCaptureActive) capture?.disableMarqueeCapture()\n if (zoomState.isMarqueeZoomActive) zoom?.disableMarqueeZoom()\n if (redactionState.isRedacting) redaction?.endRedact()\n\n annotation.setActiveTool(\n toolId !== null && annotationState.activeToolId === toolId\n ? null\n : toolId\n )\n },\n [\n annotation,\n annotationState.activeToolId,\n capture,\n captureState.isMarqueeCaptureActive,\n isPanning,\n pan,\n redaction,\n redactionState.isRedacting,\n zoom,\n zoomState.isMarqueeZoomActive,\n ]\n )\n\n const setMode = React.useCallback(\n (nextMode: PdfEditorMode) => {\n setModeState((previous) => {\n if (previous === nextMode) return previous\n\n onModeChange?.(nextMode)\n return nextMode\n })\n\n const defaultPanel: Record<PdfEditorMode, PdfEditorRightPanel | null> = {\n view: null,\n annotate: "properties",\n sign: "signatures",\n forms: "forms",\n redact: "redactions",\n }\n const panel = defaultPanel[nextMode]\n\n if (panel) setRightPanel(panel)\n else setRightPanel(null)\n },\n [onModeChange]\n )\n\n React.useEffect(() => {\n deactivateTools()\n annotation?.deselectAnnotation()\n // Only react to mode changes here; tool state is otherwise managed by the toolbar.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [mode])\n\n React.useEffect(() => {\n annotation?.setLocked(\n mode === "forms" && formDesignMode\n ? { type: LockModeType.None }\n : { type: LockModeType.Include, categories: ["form"] }\n )\n }, [annotation, formDesignMode, mode])\n\n React.useEffect(() => {\n if (mode !== "forms" && formDesignMode) setFormDesignMode(false)\n }, [formDesignMode, mode, setFormDesignMode])\n\n /* ---- history ---------------------------------------------------------- */\n\n React.useEffect(() => {\n if (!historyScope) return\n\n const sync = () => {\n const state = historyScope.getHistoryState()\n setHistoryState({\n canUndo: state.global.canUndo,\n canRedo: state.global.canRedo,\n })\n }\n\n sync()\n return historyScope.onHistoryChange(sync)\n }, [historyScope])\n\n /* ---- callbacks: page, annotations, forms, redactions ------------------ */\n\n React.useEffect(() => {\n if (activePage > 0) onActivePageChange?.(activePage)\n }, [activePage, onActivePageChange])\n\n const onAnnotationEventRef = React.useRef(onAnnotationEvent)\n const onAnnotationsChangeRef = React.useRef(onAnnotationsChange)\n const onFormValuesChangeRef = React.useRef(onFormValuesChange)\n const onRedactionsAppliedRef = React.useRef(onRedactionsApplied)\n\n React.useEffect(() => {\n onAnnotationEventRef.current = onAnnotationEvent\n onAnnotationsChangeRef.current = onAnnotationsChange\n onFormValuesChangeRef.current = onFormValuesChange\n onRedactionsAppliedRef.current = onRedactionsApplied\n })\n\n React.useEffect(() => {\n if (!annotation) return\n\n let timeout: number | null = null\n\n const unsubscribe = annotation.onAnnotationEvent((event) => {\n onAnnotationEventRef.current?.(event)\n\n if (!onAnnotationsChangeRef.current) return\n if (event.type === "loaded" || !event.committed) return\n\n if (timeout !== null) window.clearTimeout(timeout)\n\n timeout = window.setTimeout(() => {\n timeout = null\n annotation.exportAnnotations().wait((items) => {\n onAnnotationsChangeRef.current?.(items)\n }, noop)\n }, 400)\n })\n\n return () => {\n if (timeout !== null) window.clearTimeout(timeout)\n unsubscribe()\n }\n }, [annotation])\n\n React.useEffect(() => {\n if (!formScope) return\n\n return formScope.onFieldValueChange(() => {\n onFormValuesChangeRef.current?.(formScope.getFormValues())\n })\n }, [formScope])\n\n React.useEffect(() => {\n if (!redaction) return\n\n return redaction.onRedactionEvent((event) => {\n if (event.type !== "commit") return\n\n if (event.success) {\n notify(\n "Redactions applied. The content was removed from the document.",\n "success"\n )\n onRedactionsAppliedRef.current?.()\n } else {\n notify("The redactions could not be applied.", "error")\n }\n })\n }, [notify, redaction])\n\n /* ---- initial zoom (numeric defaults never lift the viewport gate) ----- */\n\n const initialZoomDocumentRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n if (!pdfDocument || !zoom) return\n if (initialZoomDocumentRef.current === documentId) return\n\n initialZoomDocumentRef.current = documentId\n zoom.requestZoom(toZoomLevel(defaultZoom))\n }, [defaultZoom, documentId, pdfDocument, zoom])\n\n /* ---- document actions ------------------------------------------------- */\n\n const scrollToPage = React.useCallback(\n (\n pageNumber: number,\n options?: { smooth?: boolean } | ScrollIntoViewOptions\n ) => {\n const smooth =\n options && "smooth" in options\n ? options.smooth\n : options && "behavior" in options\n ? options.behavior === "smooth"\n : false\n\n scroll?.scrollToPage({ pageNumber, behavior: smooth ? "smooth" : "auto" })\n },\n [scroll]\n )\n\n const scrollToAnnotation = React.useCallback(\n (target: PdfAnnotationObject) => {\n scroll?.scrollToPage({\n pageNumber: target.pageIndex + 1,\n pageCoordinates: { x: target.rect.origin.x, y: target.rect.origin.y },\n alignX: 50,\n alignY: 25,\n behavior: "smooth",\n })\n },\n [scroll]\n )\n\n const getDocumentBuffer = React.useCallback(async () => {\n if (!exportScope) throw new Error("The document is not ready.")\n\n if (annotation && annotationState.hasPendingChanges) {\n try {\n await annotation.commit().toPromise()\n } catch {\n // Continue with whatever the engine currently holds.\n }\n }\n\n return exportScope.saveAsCopy().toPromise()\n }, [annotation, annotationState.hasPendingChanges, exportScope])\n\n const downloadDocument = React.useCallback(\n async (name?: string) => {\n const targetName = getPdfFileName(name ?? fileName)\n\n setIsDownloading(true)\n\n try {\n const buffer = await getDocumentBuffer()\n downloadArrayBuffer(buffer, targetName)\n onSave?.({ buffer, fileName: targetName })\n } catch (error) {\n console.error(error)\n notify("The document could not be saved.", "error")\n } finally {\n setIsDownloading(false)\n }\n },\n [fileName, getDocumentBuffer, notify, onSave]\n )\n\n const flattenDocument = React.useCallback(() => {\n setDialog({\n type: "confirm",\n title: "Flatten annotations and form fields?",\n description:\n "Annotations and filled form fields become part of the page content and can no longer be edited.",\n confirmLabel: "Flatten",\n destructive: true,\n onConfirm: async () => {\n if (!registry || !pdfDocument) return\n\n try {\n if (annotation && annotationState.hasPendingChanges) {\n await annotation.commit().toPromise()\n }\n\n const engine = registry.getEngine()\n\n for (const page of pdfDocument.pages) {\n await engine\n .flattenPage(pdfDocument, page, {\n flag: PdfPageFlattenFlag.Display,\n })\n .toPromise()\n }\n\n const buffer = await engine.saveAsCopy(pdfDocument).toPromise()\n onReplaceDocument(buffer, fileName)\n notify("Annotations flattened into the page content.", "success")\n } catch (error) {\n console.error(error)\n notify("The document could not be flattened.", "error")\n }\n },\n })\n }, [\n annotation,\n annotationState.hasPendingChanges,\n fileName,\n notify,\n onReplaceDocument,\n pdfDocument,\n registry,\n ])\n\n const exportAnnotationsJson = React.useCallback(() => {\n if (!annotation) return\n\n annotation.exportAnnotations().wait(\n (items) => {\n downloadBlob(\n new Blob([JSON.stringify(serializeAnnotationItems(items), null, 2)], {\n type: "application/json",\n }),\n `${fileName.replace(/\\.pdf$/i, "")}-annotations.json`\n )\n notify(\n `Exported ${items.length} annotation${items.length === 1 ? "" : "s"}.`,\n "success"\n )\n },\n () => notify("The annotations could not be exported.", "error")\n )\n }, [annotation, fileName, notify])\n\n const importAnnotationsFile = React.useCallback(\n async (file: File) => {\n if (!annotation) return\n\n try {\n const items = deserializeAnnotationItems(JSON.parse(await file.text()))\n annotation.importAnnotations(items)\n notify(\n `Imported ${items.length} annotation${items.length === 1 ? "" : "s"}.`,\n "success"\n )\n } catch {\n notify("The file is not a valid annotation export.", "error")\n }\n },\n [annotation, notify]\n )\n\n const deleteSelectedAnnotations = React.useCallback(() => {\n if (!annotation || selectedAnnotations.length === 0) return\n\n const deletable = selectedAnnotations.filter(\n (item) => !annotation.isAnnotationStructurallyLocked(item.object)\n )\n\n if (deletable.length === 0) return\n\n annotation.deleteAnnotations(\n deletable.map((item) => ({\n pageIndex: item.object.pageIndex,\n id: item.object.id,\n }))\n )\n }, [annotation, selectedAnnotations])\n\n const applyAllRedactions = React.useCallback(() => {\n if (!redaction || redactionState.pendingCount === 0) return\n\n setDialog({\n type: "confirm",\n title: `Apply ${redactionState.pendingCount} redaction${redactionState.pendingCount === 1 ? "" : "s"}?`,\n description:\n "Redaction permanently removes the marked content from the document. This cannot be undone.",\n confirmLabel: "Apply redactions",\n onConfirm: () => {\n redaction.commitAllPending().wait(noop, noop)\n },\n })\n }, [redaction, redactionState.pendingCount])\n\n /* ---- imperative handle ------------------------------------------------ */\n\n React.useEffect(() => {\n handleRef.current = {\n getDocumentBuffer,\n download: downloadDocument,\n print: async (options) => {\n if (!print) throw new Error("Printing is not available.")\n await print.print(options).toPromise()\n },\n exportAnnotations: async () => {\n if (!annotation) return []\n return annotation.exportAnnotations().toPromise()\n },\n importAnnotations: (items) => annotation?.importAnnotations(items),\n getFormValues: () => formScope?.getFormValues() ?? {},\n setFormValues: async (values) => {\n if (!formScope) return\n await formScope.setFormValues(values).toPromise()\n },\n applyRedactions: async () => {\n if (!redaction) return\n await redaction.commitAllPending().toPromise()\n },\n setMode,\n setActiveTool: (toolId) => annotation?.setActiveTool(toolId),\n scrollToPage: (pageNumber, options) => scrollToPage(pageNumber, options),\n undo: () => historyScope?.undo(),\n redo: () => historyScope?.redo(),\n getViewportElement: () => viewportElementRef.current,\n }\n\n return () => {\n handleRef.current = null\n }\n }, [\n annotation,\n downloadDocument,\n formScope,\n getDocumentBuffer,\n handleRef,\n historyScope,\n print,\n redaction,\n scrollToPage,\n setMode,\n ])\n\n /* ---- keyboard shortcuts ----------------------------------------------- */\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLDivElement>) => {\n const key = event.key\n const mod = event.metaKey || event.ctrlKey\n\n if (isTypingTarget(event.target)) {\n if (key === "Escape") (event.target as HTMLElement).blur()\n return\n }\n\n if (key === "Escape") {\n deactivateTools()\n annotation?.deselectAnnotation()\n selectionScope?.clear()\n setSearchOpen(false)\n event.preventDefault()\n return\n }\n\n if (\n (key === "Delete" || key === "Backspace") &&\n selectedAnnotations.length > 0\n ) {\n deleteSelectedAnnotations()\n event.preventDefault()\n return\n }\n\n if (mod && key.toLowerCase() === "z") {\n if (event.shiftKey) historyScope?.redo()\n else historyScope?.undo()\n event.preventDefault()\n return\n }\n\n if (mod && key.toLowerCase() === "y") {\n historyScope?.redo()\n event.preventDefault()\n return\n }\n\n if (mod && (key === "=" || key === "+")) {\n zoom?.zoomIn()\n event.preventDefault()\n return\n }\n\n if (mod && key === "-") {\n zoom?.zoomOut()\n event.preventDefault()\n return\n }\n\n if (mod && key === "0") {\n zoom?.requestZoom(ZoomMode.FitPage)\n event.preventDefault()\n return\n }\n\n if (mod && key.toLowerCase() === "p" && features.print) {\n setDialog({ type: "print" })\n event.preventDefault()\n return\n }\n\n if (mod && key.toLowerCase() === "s" && showDownload) {\n void downloadDocument()\n event.preventDefault()\n return\n }\n\n if (mod && key.toLowerCase() === "f") {\n setSearchOpen(true)\n event.preventDefault()\n return\n }\n\n if (mod && key.toLowerCase() === "a" && annotation && mode !== "view") {\n const ids = annotationState.pages[Math.max(0, activePage - 1)] ?? []\n\n if (ids.length > 0) {\n annotation.setSelection(ids)\n event.preventDefault()\n }\n return\n }\n\n if (!mod && !event.altKey && key.toLowerCase() === "h") {\n pan?.togglePan()\n event.preventDefault()\n return\n }\n\n if (!mod && !event.altKey && key.toLowerCase() === "v") {\n deactivateTools()\n event.preventDefault()\n }\n },\n [\n activePage,\n annotation,\n annotationState.pages,\n deactivateTools,\n deleteSelectedAnnotations,\n downloadDocument,\n features.print,\n historyScope,\n mode,\n pan,\n selectedAnnotations.length,\n selectionScope,\n showDownload,\n zoom,\n ]\n )\n\n const handlePointerDownCapture = React.useCallback(\n (event: React.PointerEvent<HTMLDivElement>) => {\n const root = rootRef.current\n if (!root) return\n\n const active = window.document.activeElement\n\n if (active && root.contains(active) && active !== root) return\n if (!(event.target instanceof Node) || !root.contains(event.target))\n return\n if (isTypingTarget(event.target)) return\n\n root.focus({ preventScroll: true })\n },\n []\n )\n\n /* ---- context ---------------------------------------------------------- */\n\n const openDialog = React.useCallback(\n (request: PdfEditorDialogRequest) => setDialog(request),\n []\n )\n const toggleLeftPanel = React.useCallback(\n (panel: PdfEditorLeftPanel) =>\n setLeftPanel((previous) => (previous === panel ? null : panel)),\n [setLeftPanel]\n )\n const toggleRightPanel = React.useCallback(\n (panel: PdfEditorRightPanel) =>\n setRightPanel((previous) => (previous === panel ? null : panel)),\n []\n )\n\n const contextValue = React.useMemo<PdfEditorContextValue>(\n () => ({\n documentId,\n document: pdfDocument,\n fileName,\n mode,\n setMode,\n leftPanel,\n setLeftPanel,\n toggleLeftPanel,\n rightPanel,\n setRightPanel,\n toggleRightPanel,\n openDialog,\n notify,\n features,\n permissions,\n annotationAuthor,\n selectionActions,\n formDesignMode,\n setFormDesignMode,\n replaceDocument: (buffer, name) =>\n onReplaceDocument(buffer, name ?? fileName),\n downloadDocument,\n getDocumentBuffer,\n scrollToPage,\n scrollToAnnotation,\n onCapture,\n onSelectionAction,\n signatureFontsStylesheetUrl,\n }),\n [\n annotationAuthor,\n documentId,\n downloadDocument,\n features,\n fileName,\n formDesignMode,\n getDocumentBuffer,\n leftPanel,\n mode,\n notify,\n onCapture,\n onReplaceDocument,\n onSelectionAction,\n openDialog,\n pdfDocument,\n permissions,\n rightPanel,\n scrollToAnnotation,\n scrollToPage,\n selectionActions,\n setFormDesignMode,\n setLeftPanel,\n setMode,\n signatureFontsStylesheetUrl,\n toggleLeftPanel,\n toggleRightPanel,\n ]\n )\n\n /* ---- page renderer ---------------------------------------------------- */\n\n const renderPage = React.useCallback(\n (page: PageLayout) => (\n <Rotate documentId={documentId} pageIndex={page.pageIndex}>\n <PagePointerProvider\n documentId={documentId}\n pageIndex={page.pageIndex}\n data-pdf-editor-page={page.pageNumber}\n className="relative border border-transparent bg-transparent shadow-xs select-none selection:bg-transparent selection:text-inherit"\n style={{ backgroundColor: "transparent" }}\n >\n <div\n aria-hidden="true"\n className="pointer-events-none absolute inset-0 bg-white"\n />\n <RenderLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n scale={Math.min(currentZoom, PAGE_BASE_RENDER_MAX_SCALE)}\n dpr={PAGE_BASE_RENDER_DPR}\n className="pointer-events-none absolute inset-0 h-full w-full object-fill opacity-100 blur-[0.35px] transition-none"\n />\n <TilingLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n className="pointer-events-none opacity-100 transition-none [&_img]:opacity-100 [&_img]:transition-none"\n />\n <SearchLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n className="pointer-events-none"\n highlightColor="rgba(253, 224, 71, 0.45)"\n activeHighlightColor="rgba(249, 115, 22, 0.55)"\n />\n <MarqueeZoom documentId={documentId} pageIndex={page.pageIndex} />\n <MarqueeCapture documentId={documentId} pageIndex={page.pageIndex} />\n <SelectionLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n textStyle={{ background: "rgba(59, 130, 246, 0.3)" }}\n selectionMenu={(props) => (\n <PdfEditorTextSelectionMenu {...props} documentId={documentId} />\n )}\n />\n <AnnotationLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n selectionOutline={{\n color: PDF_EDITOR_SELECTION_COLOR,\n style: "solid",\n width: 1,\n offset: 2,\n }}\n groupSelectionOutline={{\n color: PDF_EDITOR_SELECTION_COLOR,\n style: "dashed",\n width: 1,\n offset: 3,\n }}\n resizeUI={{ size: 10, color: PDF_EDITOR_SELECTION_COLOR }}\n vertexUI={{ size: 10, color: PDF_EDITOR_SELECTION_COLOR }}\n rotationUI={{\n size: 18,\n color: "#ffffff",\n iconColor: PDF_EDITOR_SELECTION_COLOR,\n connectorColor: PDF_EDITOR_SELECTION_COLOR,\n showConnector: true,\n }}\n selectionMenu={(props) => (\n <PdfEditorAnnotationMenu {...props} documentId={documentId} />\n )}\n groupSelectionMenu={(props) => (\n <PdfEditorGroupMenu {...props} documentId={documentId} />\n )}\n />\n <RedactionLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n selectionMenu={(props) => (\n <PdfEditorRedactionMenu {...props} documentId={documentId} />\n )}\n />\n {renderPageOverlay?.({\n pageNumber: page.pageNumber,\n pageWidth: page.width,\n pageHeight: page.height,\n scale: currentZoom,\n rotation: 0,\n })}\n </PagePointerProvider>\n </Rotate>\n ),\n [currentZoom, documentId, renderPageOverlay]\n )\n\n /* ---- toolbar pieces --------------------------------------------------- */\n\n const activeToolColorKey = React.useMemo(() => {\n if (!activeTool) return null\n\n const defaults = activeTool.defaults as Record<string, unknown>\n\n if ("fontColor" in defaults) return "fontColor"\n if ("strokeColor" in defaults) return "strokeColor"\n if ("color" in defaults) return "color"\n return null\n }, [activeTool])\n const activeToolColor = activeToolColorKey\n ? String(\n (activeTool?.defaults as Record<string, unknown>)[activeToolColorKey] ??\n "#111827"\n )\n : null\n\n const visibleLeftTabs = LEFT_PANEL_TABS.filter(\n (tab) => tab.feature === null || features[tab.feature]\n )\n const visibleRightTabs = RIGHT_PANEL_TABS.filter(\n (tab) => tab.feature === null || features[tab.feature]\n )\n\n const canAnnotate = features.annotate && permissions.canModifyAnnotations\n const canRedact = features.redact && permissions.canModifyContents\n const canDesignForms = features.forms && permissions.canModifyAnnotations\n\n const selectToolButton = (\n <PdfEditorToolButton\n label="Select"\n shortcut="V"\n active={\n !activeToolId &&\n !isPanning &&\n !captureState.isMarqueeCaptureActive &&\n !zoomState.isMarqueeZoomActive &&\n !redactionState.isRedacting\n }\n onClick={deactivateTools}\n >\n <CursorGlyph className="size-4" />\n </PdfEditorToolButton>\n )\n\n const renderToolButton = (\n tool: { id: string; label: string; glyph: PdfEditorGlyph; hint?: string },\n disabled: boolean\n ) => {\n const Glyph = tool.glyph\n\n return (\n <PdfEditorToolButton\n key={tool.id}\n label={tool.hint ? `${tool.label} · ${tool.hint}` : tool.label}\n active={activeToolId === tool.id}\n disabled={disabled}\n onClick={() => setActiveTool(tool.id)}\n >\n <Glyph className="size-4" />\n </PdfEditorToolButton>\n )\n }\n\n let ribbon: React.ReactNode = null\n\n if (mode === "view") {\n ribbon = (\n <>\n {selectToolButton}\n <PdfEditorToolButton\n label="Hand tool"\n shortcut="H"\n active={isPanning}\n onClick={() => pan?.togglePan()}\n >\n <HandGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Zoom to area"\n active={zoomState.isMarqueeZoomActive}\n onClick={() => zoom?.toggleMarqueeZoom()}\n >\n <MarqueeZoomGlyph className="size-4" />\n </PdfEditorToolButton>\n {features.capture ? (\n <PdfEditorToolButton\n label="Capture area as image"\n active={captureState.isMarqueeCaptureActive}\n onClick={() => capture?.toggleMarqueeCapture()}\n >\n <CameraGlyph className="size-4" />\n </PdfEditorToolButton>\n ) : null}\n <PdfEditorToolbarSeparator />\n <Select\n items={SPREAD_MODE_OPTIONS}\n value={spreadMode}\n disabled={controlsDisabled}\n modal={false}\n onValueChange={(value) =>\n spread?.setSpreadMode(String(value) as SpreadMode)\n }\n >\n <SelectTrigger\n size="sm"\n className="w-[132px]"\n aria-label="Page layout"\n >\n <BookOpenGlyph className="size-4 text-muted-foreground" />\n <SelectValue placeholder="Layout" />\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {SPREAD_MODE_OPTIONS.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <Select\n items={SCROLL_DIRECTION_OPTIONS}\n value={horizontalScroll ? "horizontal" : "vertical"}\n disabled={controlsDisabled}\n modal={false}\n onValueChange={(value) => {\n const horizontal = value === "horizontal"\n setHorizontalScroll(horizontal)\n scrollCapability?.setScrollStrategy(\n horizontal ? ScrollStrategy.Horizontal : ScrollStrategy.Vertical,\n documentId\n )\n }}\n >\n <SelectTrigger\n size="sm"\n className="w-[128px]"\n aria-label="Scroll direction"\n >\n <SelectValue placeholder="Scroll" />\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {SCROLL_DIRECTION_OPTIONS.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </>\n )\n } else if (mode === "annotate") {\n ribbon = (\n <>\n {selectToolButton}\n {PDF_EDITOR_ANNOTATION_TOOL_GROUPS.map((group) => (\n <React.Fragment key={group.id}>\n <PdfEditorToolbarSeparator />\n {group.tools.map((tool) => renderToolButton(tool, !canAnnotate))}\n </React.Fragment>\n ))}\n {features.stamps ? (\n <PdfEditorToolButton\n label="Rubber stamps"\n active={rightPanel === "stamps"}\n disabled={!canAnnotate}\n onClick={() => toggleRightPanel("stamps")}\n >\n <StampGlyph className="size-4" />\n </PdfEditorToolButton>\n ) : null}\n {activeTool && activeToolColorKey && activeToolColor ? (\n <>\n <PdfEditorToolbarSeparator />\n <ColorPicker\n label={`${activeTool.name} color`}\n icon={PaletteGlyph}\n color={activeToolColor}\n onChange={(color) =>\n annotationCapability?.setToolDefaults(activeTool.id, {\n [activeToolColorKey]: color,\n })\n }\n />\n </>\n ) : null}\n <div className="ml-auto flex items-center gap-0.5">\n <PdfEditorToolButton\n label="Delete selected"\n shortcut="Delete"\n disabled={selectedAnnotations.length === 0}\n onClick={deleteSelectedAnnotations}\n >\n <TrashGlyph className="size-4" />\n </PdfEditorToolButton>\n {features.comments ? (\n <PdfEditorToolButton\n label="Comments"\n active={rightPanel === "comments"}\n onClick={() => toggleRightPanel("comments")}\n >\n <CommentsGlyph className="size-4" />\n </PdfEditorToolButton>\n ) : null}\n <PdfEditorToolButton\n label="Properties"\n active={rightPanel === "properties"}\n onClick={() => toggleRightPanel("properties")}\n >\n <SlidersGlyph className="size-4" />\n </PdfEditorToolButton>\n </div>\n </>\n )\n } else if (mode === "sign") {\n ribbon = (\n <>\n {selectToolButton}\n <PdfEditorToolbarSeparator />\n <Button\n type="button"\n size="sm"\n variant="outline"\n disabled={!canAnnotate}\n onClick={() => setDialog({ type: "signature" })}\n >\n <PlusGlyph className="size-4" />\n Create signature\n </Button>\n <PdfEditorToolButton\n label="Saved signatures"\n active={rightPanel === "signatures"}\n onClick={() => toggleRightPanel("signatures")}\n >\n <SignatureGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolbarSeparator />\n {renderToolButton(\n {\n id: "freeText",\n label: "Text box",\n glyph: TextGlyph,\n hint: "Click to add text",\n },\n !canAnnotate\n )}\n <PdfEditorToolButton\n label="Date · Click to add today\'s date"\n disabled={!canAnnotate}\n active={\n activeToolId === "freeText" &&\n Boolean(annotationState.activeToolContext?.date)\n }\n onClick={() => {\n if (!annotation) return\n\n annotationCapability?.setToolDefaults("freeText", {\n contents: new Date().toLocaleDateString(),\n })\n annotation.setActiveTool("freeText", { date: true })\n }}\n >\n <FileTextGlyph className="size-4" />\n </PdfEditorToolButton>\n {renderToolButton(\n { id: "ink", label: "Draw", glyph: EditGlyph, hint: "Sign by hand" },\n !canAnnotate\n )}\n </>\n )\n } else if (mode === "forms") {\n ribbon = (\n <>\n {selectToolButton}\n <PdfEditorToolbarSeparator />\n <div\n role="group"\n aria-label="Form mode"\n className="flex shrink-0 items-center gap-0.5 rounded-lg bg-muted p-0.5"\n >\n <Button\n type="button"\n size="xs"\n variant={formDesignMode ? "ghost" : "default"}\n aria-pressed={!formDesignMode}\n onClick={() => setFormDesignMode(false)}\n >\n Fill\n </Button>\n <Button\n type="button"\n size="xs"\n variant={formDesignMode ? "default" : "ghost"}\n aria-pressed={formDesignMode}\n disabled={!canDesignForms}\n onClick={() => setFormDesignMode(true)}\n >\n Design\n </Button>\n </div>\n {formDesignMode ? (\n <>\n <PdfEditorToolbarSeparator />\n {PDF_EDITOR_FORM_TOOLS.map((tool) =>\n renderToolButton(tool, !canDesignForms)\n )}\n </>\n ) : null}\n <div className="ml-auto flex items-center gap-0.5">\n <PdfEditorToolButton\n label="Delete selected"\n shortcut="Delete"\n disabled={selectedAnnotations.length === 0 || !formDesignMode}\n onClick={deleteSelectedAnnotations}\n >\n <TrashGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Form fields"\n active={rightPanel === "forms"}\n onClick={() => toggleRightPanel("forms")}\n >\n <TextFieldGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Properties"\n active={rightPanel === "properties"}\n onClick={() => toggleRightPanel("properties")}\n >\n <SlidersGlyph className="size-4" />\n </PdfEditorToolButton>\n </div>\n </>\n )\n } else if (mode === "redact") {\n const activeType = redactionState.activeType\n const pendingCount = redactionState.pendingCount\n\n ribbon = (\n <>\n {selectToolButton}\n <PdfEditorToolbarSeparator />\n <PdfEditorToolButton\n label="Redact · Select text or drag an area"\n active={activeType === RedactionMode.Redact}\n disabled={!canRedact}\n onClick={() => {\n deactivateTools()\n if (activeType !== RedactionMode.Redact) redaction?.enableRedact()\n }}\n >\n <EyeOffGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Mark text"\n active={activeType === RedactionMode.RedactSelection}\n disabled={!canRedact}\n onClick={() => {\n deactivateTools()\n if (activeType !== RedactionMode.RedactSelection)\n redaction?.enableRedactSelection()\n }}\n >\n <StrikethroughGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Mark area"\n active={activeType === RedactionMode.MarqueeRedact}\n disabled={!canRedact}\n onClick={() => {\n deactivateTools()\n if (activeType !== RedactionMode.MarqueeRedact)\n redaction?.enableMarqueeRedact()\n }}\n >\n <RedactAreaGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolbarSeparator />\n <Badge\n variant={pendingCount > 0 ? "secondary" : "outline"}\n className="me-1 tabular-nums"\n >\n {pendingCount} pending\n </Badge>\n <Button\n type="button"\n size="sm"\n disabled={!canRedact || pendingCount === 0}\n onClick={applyAllRedactions}\n >\n Apply all\n </Button>\n <Button\n type="button"\n size="sm"\n variant="ghost"\n disabled={pendingCount === 0}\n onClick={() => redaction?.clearPending()}\n >\n Clear\n </Button>\n <div className="ml-auto flex items-center gap-0.5">\n <PdfEditorToolButton\n label="Redactions"\n active={rightPanel === "redactions"}\n onClick={() => toggleRightPanel("redactions")}\n >\n <EyeOffGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Properties"\n active={rightPanel === "properties"}\n onClick={() => toggleRightPanel("properties")}\n >\n <SlidersGlyph className="size-4" />\n </PdfEditorToolButton>\n </div>\n </>\n )\n }\n\n let rightPanelContent: React.ReactNode = null\n\n switch (rightPanel) {\n case "properties":\n rightPanelContent = <PdfEditorPropertiesPanel documentId={documentId} />\n break\n case "comments":\n rightPanelContent = <PdfEditorCommentsPanel documentId={documentId} />\n break\n case "redactions":\n rightPanelContent = <PdfEditorRedactionsPanel documentId={documentId} />\n break\n case "stamps":\n rightPanelContent = <PdfEditorStampsPanel documentId={documentId} />\n break\n case "signatures":\n rightPanelContent = <PdfEditorSignaturesPanel documentId={documentId} />\n break\n case "forms":\n rightPanelContent = <PdfEditorFormsPanel documentId={documentId} />\n break\n default:\n rightPanelContent = null\n }\n\n let leftPanelContent: React.ReactNode = null\n\n switch (leftPanel) {\n case "thumbnails":\n leftPanelContent = (\n <PdfEditorThumbnailsPanel\n documentId={documentId}\n activePage={activePage}\n pageCount={numPages}\n onSelectPage={(pageNumber) => scrollToPage(pageNumber)}\n />\n )\n break\n case "outline":\n leftPanelContent = <PdfEditorOutlinePanel documentId={documentId} />\n break\n case "attachments":\n leftPanelContent = <PdfEditorAttachmentsPanel documentId={documentId} />\n break\n case "pages":\n leftPanelContent = (\n <PdfEditorPagesPanel documentId={documentId} activePage={activePage} />\n )\n break\n default:\n leftPanelContent = null\n }\n\n return (\n <PdfEditorContextProvider value={contextValue}>\n <ToastProvider\n limit={3}\n timeout={NOTICE_DURATION_MS}\n toastManager={editorToastManager}\n portalProps={{ container: toastContainer }}\n viewportProps={{ className: "absolute" }}\n >\n <div\n data-slot="pdf-editor"\n data-mode={mode}\n data-fullscreen={fullscreenState.isFullscreen ? "" : undefined}\n className={cn(\n "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className,\n // The fullscreen plugin auto-mounts a wrapper around the EmbedPDF\n // tree; when that wrapper is fullscreen, fill it instead of the\n // consumer-provided height.\n fullscreenState.isFullscreen && "h-full max-h-full"\n )}\n >\n <div\n ref={setRootElement}\n tabIndex={-1}\n className="relative flex h-full min-h-0 flex-1 flex-col outline-none"\n onKeyDown={handleKeyDown}\n onPointerDownCapture={handlePointerDownCapture}\n >\n <input\n ref={uploadInputRef}\n type="file"\n accept="application/pdf,.pdf"\n className="sr-only"\n tabIndex={-1}\n onChange={(event) => {\n const file = event.target.files?.[0]\n if (file) onUploadFile(file)\n event.currentTarget.value = ""\n }}\n />\n <input\n ref={annotationImportInputRef}\n type="file"\n accept="application/json,.json"\n className="sr-only"\n tabIndex={-1}\n onChange={(event) => {\n const file = event.target.files?.[0]\n if (file) void importAnnotationsFile(file)\n event.currentTarget.value = ""\n }}\n />\n\n {showToolbar ? (\n <TooltipProvider delay={TOOLTIP_DELAY_MS}>\n <div\n data-slot="pdf-editor-toolbar"\n className={cn(\n "flex min-h-12 flex-wrap items-center justify-between gap-2 border-b bg-background px-3 py-2",\n compactToolbar && "gap-0 px-0 py-0"\n )}\n >\n <div\n className={cn(\n "flex min-w-0 items-center gap-2",\n compactToolbar && "w-full px-3 py-2"\n )}\n >\n <PdfEditorToolButton\n label="Pages sidebar"\n active={leftPanel !== null}\n disabled={controlsDisabled}\n onClick={() => toggleLeftPanel("thumbnails")}\n >\n <PanelLeftGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorPageControl\n activePage={activePage}\n numPages={numPages}\n disabled={controlsDisabled}\n onPageChange={(pageNumber) => scrollToPage(pageNumber)}\n />\n </div>\n <ScrollArea\n orientation="horizontal"\n scrollFade\n scrollbarOverflowOnly\n className={cn(\n "min-w-0 flex-1",\n compactToolbar && "h-12 w-full flex-none border-t"\n )}\n viewportClassName={cn(compactToolbar && "px-3 py-2")}\n >\n <div\n className={cn(\n "flex w-max min-w-full items-center gap-1",\n compactToolbar ? "justify-start" : "justify-end"\n )}\n >\n <div className="flex items-center gap-0.5">\n <PdfEditorToolButton\n label="Undo"\n shortcut="mod+Z"\n disabled={!historyState.canUndo}\n onClick={() => historyScope?.undo()}\n >\n <UndoGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Redo"\n shortcut="mod+shift+Z"\n disabled={!historyState.canRedo}\n onClick={() => historyScope?.redo()}\n >\n <RedoGlyph className="size-4" />\n </PdfEditorToolButton>\n </div>\n <PdfEditorToolbarSeparator />\n <PdfEditorZoomControl\n documentId={documentId}\n disabled={controlsDisabled}\n />\n <PdfEditorToolbarSeparator />\n <div className="flex items-center gap-0.5">\n <PdfEditorToolButton\n label="Rotate counterclockwise"\n disabled={controlsDisabled}\n onClick={() => rotate?.rotateBackward()}\n >\n <RotateGlyph className="size-4 -scale-x-100" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Rotate clockwise"\n disabled={controlsDisabled}\n onClick={() => rotate?.rotateForward()}\n >\n <RotateGlyph className="size-4" />\n </PdfEditorToolButton>\n </div>\n <PdfEditorToolbarSeparator />\n <PdfEditorSearchControl\n documentId={documentId}\n disabled={controlsDisabled}\n open={searchOpen}\n onOpenChange={setSearchOpen}\n />\n <PdfEditorToolButton\n label="Details panel"\n active={rightPanel !== null}\n disabled={controlsDisabled}\n onClick={() => toggleRightPanel("properties")}\n >\n <PanelRightGlyph className="size-4" />\n </PdfEditorToolButton>\n {toolbarActions ? (\n <>\n <PdfEditorToolbarSeparator />\n {toolbarActions}\n </>\n ) : null}\n <PdfEditorToolbarSeparator />\n {showDownload ? (\n <PdfEditorToolButton\n label="Download"\n shortcut="mod+S"\n disabled={controlsDisabled || isDownloading}\n onClick={() => void downloadDocument()}\n >\n {isDownloading ? (\n <Spinner className="size-4" />\n ) : (\n <DownloadGlyph className="size-4" />\n )}\n </PdfEditorToolButton>\n ) : null}\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="More actions"\n >\n <MoreGlyph className="size-4" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="w-60">\n <DropdownMenuGroup>\n <DropdownMenuLabel className="truncate">\n {fileName}\n </DropdownMenuLabel>\n {showUpload ? (\n <DropdownMenuItem\n onClick={() => uploadInputRef.current?.click()}\n >\n <UploadGlyph className="size-4" />\n Open PDF…\n </DropdownMenuItem>\n ) : null}\n {showDownload ? (\n <DropdownMenuItem\n disabled={controlsDisabled}\n onClick={() => void downloadDocument()}\n >\n <DownloadGlyph className="size-4" />\n Download\n <DropdownMenuShortcut>⌘S</DropdownMenuShortcut>\n </DropdownMenuItem>\n ) : null}\n {features.print ? (\n <DropdownMenuItem\n disabled={\n controlsDisabled || !permissions.canPrint\n }\n onClick={() => setDialog({ type: "print" })}\n >\n <PrintGlyph className="size-4" />\n Print…\n <DropdownMenuShortcut>⌘P</DropdownMenuShortcut>\n </DropdownMenuItem>\n ) : null}\n {features.capture ? (\n <DropdownMenuItem\n disabled={controlsDisabled}\n onClick={() => capture?.toggleMarqueeCapture()}\n >\n <CameraGlyph className="size-4" />\n Capture area as image\n </DropdownMenuItem>\n ) : null}\n {features.fullscreen ? (\n <DropdownMenuItem\n onClick={() => fullscreen?.toggleFullscreen()}\n >\n {fullscreenState.isFullscreen ? (\n <ExitFullscreenGlyph className="size-4" />\n ) : (\n <FullscreenGlyph className="size-4" />\n )}\n {fullscreenState.isFullscreen\n ? "Exit full screen"\n : "Full screen"}\n </DropdownMenuItem>\n ) : null}\n </DropdownMenuGroup>\n <DropdownMenuSeparator />\n <DropdownMenuGroup>\n <DropdownMenuItem\n disabled={controlsDisabled}\n onClick={() => setDialog({ type: "properties" })}\n >\n <InfoGlyph className="size-4" />\n Document properties…\n </DropdownMenuItem>\n {features.security ? (\n <DropdownMenuItem\n disabled={controlsDisabled}\n onClick={() => setDialog({ type: "security" })}\n >\n <ShieldGlyph className="size-4" />\n Security…\n </DropdownMenuItem>\n ) : null}\n <DropdownMenuItem\n disabled={\n controlsDisabled ||\n !permissions.canModifyContents\n }\n onClick={flattenDocument}\n >\n <LayersGlyph className="size-4" />\n Flatten annotations…\n </DropdownMenuItem>\n </DropdownMenuGroup>\n <DropdownMenuSeparator />\n <DropdownMenuGroup>\n <DropdownMenuItem\n disabled={controlsDisabled}\n onClick={exportAnnotationsJson}\n >\n <DownloadGlyph className="size-4" />\n Export annotations (JSON)\n </DropdownMenuItem>\n <DropdownMenuItem\n disabled={\n controlsDisabled ||\n !permissions.canModifyAnnotations\n }\n onClick={() =>\n annotationImportInputRef.current?.click()\n }\n >\n <UploadGlyph className="size-4" />\n Import annotations (JSON)…\n </DropdownMenuItem>\n </DropdownMenuGroup>\n <DropdownMenuSeparator />\n <DropdownMenuGroup>\n <DropdownMenuLabel>Page layout</DropdownMenuLabel>\n <DropdownMenuRadioGroup\n value={spreadMode}\n onValueChange={(value) =>\n spread?.setSpreadMode(\n String(value) as SpreadMode\n )\n }\n >\n <DropdownMenuRadioItem value={SpreadMode.None}>\n Single page\n </DropdownMenuRadioItem>\n <DropdownMenuRadioItem value={SpreadMode.Odd}>\n Two pages\n </DropdownMenuRadioItem>\n <DropdownMenuRadioItem value={SpreadMode.Even}>\n Two pages, cover first\n </DropdownMenuRadioItem>\n </DropdownMenuRadioGroup>\n </DropdownMenuGroup>\n <DropdownMenuSeparator />\n <DropdownMenuItem\n onClick={() => setDialog({ type: "shortcuts" })}\n >\n <KeyboardGlyph className="size-4" />\n Keyboard shortcuts\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n </div>\n </ScrollArea>\n </div>\n <div\n data-slot="pdf-editor-ribbon"\n className="flex min-h-10 items-center gap-1 border-b bg-muted/30 px-3 py-1.5"\n >\n <PdfEditorModeSwitch\n mode={mode}\n features={features}\n compact={compactToolbar}\n onModeChange={setMode}\n />\n <PdfEditorToolbarSeparator className="mx-1.5" />\n <ScrollArea\n orientation="horizontal"\n scrollFade\n scrollbarOverflowOnly\n className="min-w-0 flex-1 self-stretch"\n >\n <div className="flex w-max min-w-full items-center gap-0.5 py-0.5">\n {ribbon}\n </div>\n </ScrollArea>\n </div>\n </TooltipProvider>\n ) : null}\n\n <div\n ref={shellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {isLoading ? (\n <div className="absolute inset-0 z-20 flex bg-muted/30">\n {leftPanel ? (\n <DocumentViewerSidebarSkeleton\n className={LEFT_SIDEBAR_WIDTH_CLASS}\n inline={leftInline}\n />\n ) : null}\n <div className="grid min-w-0 flex-1 place-items-center">\n <Spinner className="size-4" />\n </div>\n </div>\n ) : null}\n <div className="flex h-full max-h-full min-h-0 w-full flex-1 overflow-hidden">\n <DocumentViewerThumbnailSidebar\n closedInlineClassName={LEFT_SIDEBAR_CLOSED_CLASS}\n inline={leftInline}\n open={leftPanel !== null && !isLoading}\n widthClassName={LEFT_SIDEBAR_WIDTH_CLASS}\n >\n {leftPanel !== null && !isLoading ? (\n <div className="flex h-full flex-col">\n <PanelTabStrip\n tabs={visibleLeftTabs}\n value={leftPanel}\n onChange={setLeftPanel}\n onClose={() => setLeftPanel(null)}\n label="Sidebar panels"\n />\n <div className="min-h-0 flex-1">{leftPanelContent}</div>\n </div>\n ) : null}\n </DocumentViewerThumbnailSidebar>\n\n <PdfEditorViewport\n documentId={documentId}\n className="relative h-full max-h-full min-h-0 min-w-0 flex-1"\n >\n <PdfEditorViewportBridge\n viewportElementRef={viewportElementRef}\n />\n <GlobalPointerProvider documentId={documentId}>\n <Scroller documentId={documentId} renderPage={renderPage} />\n </GlobalPointerProvider>\n <CopyToClipboard />\n </PdfEditorViewport>\n\n <PdfEditorRightPanelShell\n open={rightPanel !== null && !isLoading}\n inline={rightInline}\n >\n {rightPanel !== null && !isLoading ? (\n <div className="flex h-full flex-col">\n <PanelTabStrip\n tabs={visibleRightTabs}\n value={rightPanel}\n onChange={setRightPanel}\n onClose={() => setRightPanel(null)}\n label="Detail panels"\n />\n <div className="min-h-0 flex-1 overflow-hidden">\n {rightPanel === "properties" ? (\n <PdfEditorScrollArea\n className="h-full w-full"\n scrollbarGutter={false}\n >\n {rightPanelContent}\n </PdfEditorScrollArea>\n ) : (\n rightPanelContent\n )}\n </div>\n </div>\n ) : null}\n </PdfEditorRightPanelShell>\n </div>\n </div>\n\n <PdfEditorSignaturePersistence storageKey={null} />\n {features.capture ? (\n <PdfEditorCaptureDialog documentId={documentId} />\n ) : null}\n <PdfEditorPrintDialog\n documentId={documentId}\n open={dialog?.type === "print"}\n onOpenChange={(open) => {\n if (!open) setDialog(null)\n }}\n />\n <PdfEditorSecurityDialog\n documentId={documentId}\n open={dialog?.type === "security"}\n onOpenChange={(open) => {\n if (!open) setDialog(null)\n }}\n />\n <PdfEditorPropertiesDialog\n documentId={documentId}\n open={dialog?.type === "properties"}\n onOpenChange={(open) => {\n if (!open) setDialog(null)\n }}\n />\n <PdfEditorShortcutsDialog\n open={dialog?.type === "shortcuts"}\n onOpenChange={(open) => {\n if (!open) setDialog(null)\n }}\n />\n <PdfEditorSignatureDialog\n open={dialog?.type === "signature"}\n onOpenChange={(open) => {\n if (!open) setDialog(null)\n }}\n />\n <PdfEditorLinkDialog\n documentId={documentId}\n open={dialog?.type === "link"}\n source={dialog?.type === "link" ? dialog.source : "selection"}\n onOpenChange={(open) => {\n if (!open) setDialog(null)\n }}\n />\n <PdfEditorConfirmDialog\n open={dialog?.type === "confirm"}\n title={dialog?.type === "confirm" ? dialog.title : ""}\n description={\n dialog?.type === "confirm" ? dialog.description : undefined\n }\n confirmLabel={\n dialog?.type === "confirm" ? dialog.confirmLabel : undefined\n }\n destructive={\n dialog?.type === "confirm" ? dialog.destructive : false\n }\n onConfirm={() => {\n if (dialog?.type === "confirm") dialog.onConfirm()\n }}\n onOpenChange={(open) => {\n if (!open) setDialog(null)\n }}\n />\n </div>\n </div>\n </ToastProvider>\n </PdfEditorContextProvider>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Document loader */\n/* -------------------------------------------------------------------------- */\n\ntype PdfEditorDocumentLoaderProps = Omit<\n PdfEditorInnerProps,\n | "documentId"\n | "document"\n | "fileName"\n | "leftPanel"\n | "setLeftPanel"\n | "formDesignMode"\n | "setFormDesignMode"\n> & {\n source: EditorSource | null\n sourceLoading: boolean\n fileNameOverride?: string\n signatureStorageKey: string | null\n onDocumentLoadSuccess?: PDFEditorProps["onDocumentLoadSuccess"]\n onDocumentLoadError?: PDFEditorProps["onDocumentLoadError"]\n}\n\nfunction PdfEditorDocumentLoader({\n source,\n sourceLoading,\n fileNameOverride,\n signatureStorageKey,\n onDocumentLoadSuccess,\n onDocumentLoadError,\n ...innerProps\n}: PdfEditorDocumentLoaderProps) {\n const { provides: documentManager } = useDocumentManagerCapability()\n const { activeDocumentId, activeDocument } = useActiveDocument()\n const [loadError, setLoadError] = React.useState<string | null>(null)\n const [leftPanel, setLeftPanel] = React.useState<PdfEditorLeftPanel | null>(\n null\n )\n const [formDesignMode, setFormDesignMode] = React.useState(false)\n const openedSourceRef = React.useRef<string | null>(null)\n const successRef = React.useRef(onDocumentLoadSuccess)\n const errorRef = React.useRef(onDocumentLoadError)\n\n React.useEffect(() => {\n successRef.current = onDocumentLoadSuccess\n errorRef.current = onDocumentLoadError\n })\n\n React.useEffect(() => {\n if (!documentManager || !source) return\n if (openedSourceRef.current === source.key) return\n\n openedSourceRef.current = source.key\n setLoadError(null)\n\n const previousIds = documentManager\n .getOpenDocuments()\n .map((item) => item.id)\n const fail = (message: string) => {\n if (openedSourceRef.current !== source.key) return\n\n setLoadError(message)\n errorRef.current?.(message)\n }\n\n const task =\n source.kind === "url"\n ? documentManager.openDocumentUrl({\n url: source.url,\n name: source.name,\n mode: source.url.startsWith("blob:") ? "full-fetch" : "auto",\n autoActivate: previousIds.length === 0,\n })\n : documentManager.openDocumentBuffer({\n buffer: source.buffer.slice(0),\n name: source.name,\n autoActivate: previousIds.length === 0,\n })\n\n task.wait(\n (response) => {\n response.task.wait(\n (openedDocument) => {\n documentManager.setActiveDocument(response.documentId)\n successRef.current?.({\n numPages: openedDocument.pageCount,\n documentId: response.documentId,\n fileName: source.name,\n })\n previousIds.forEach((id) => {\n if (id !== response.documentId) {\n documentManager.closeDocument(id).wait(noop, noop)\n }\n })\n },\n (failure) => {\n // Password prompts are handled through the document state.\n if (failure?.reason?.code === PdfErrorCode.Password) return\n fail(failure?.reason?.message ?? "The PDF could not be loaded.")\n }\n )\n },\n (failure) =>\n fail(failure?.reason?.message ?? "The PDF could not be loaded.")\n )\n }, [documentManager, source])\n\n const fileName = fileNameOverride\n ? getPdfFileName(fileNameOverride)\n : (source?.name ?? getPdfFileName(undefined))\n const passwordRequired =\n activeDocument?.status === "error" &&\n activeDocument.errorCode === PdfErrorCode.Password\n const documentFailed =\n loadError !== null ||\n (activeDocument?.status === "error" && !passwordRequired)\n\n if (\n !source ||\n sourceLoading ||\n !activeDocumentId ||\n documentFailed ||\n passwordRequired\n ) {\n return (\n <PdfEditorFallbackShell\n className={innerProps.className}\n fileName={source?.name}\n showToolbar={innerProps.showToolbar}\n showUpload={innerProps.showUpload}\n state={\n !source && !sourceLoading\n ? "empty"\n : passwordRequired\n ? "password"\n : documentFailed\n ? "error"\n : "loading"\n }\n errorMessage={loadError ?? activeDocument?.error ?? undefined}\n onUploadFile={innerProps.onUploadFile}\n >\n {passwordRequired && activeDocument ? (\n <div className="flex-1">\n <PdfEditorPasswordPrompt documentState={activeDocument} />\n </div>\n ) : null}\n </PdfEditorFallbackShell>\n )\n }\n\n const document =\n activeDocument?.status === "loaded" ? activeDocument.document : null\n\n return (\n <>\n <PdfEditorSignaturePersistence storageKey={signatureStorageKey} />\n <PdfEditorInner\n key={activeDocumentId}\n {...innerProps}\n documentId={activeDocumentId}\n document={document}\n fileName={fileName}\n leftPanel={leftPanel}\n setLeftPanel={setLeftPanel}\n formDesignMode={formDesignMode}\n setFormDesignMode={setFormDesignMode}\n />\n </>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Root */\n/* -------------------------------------------------------------------------- */\n\nexport const PDFEditor = React.forwardRef<PDFEditorHandle, PDFEditorProps>(\n function PDFEditor(\n {\n className,\n src,\n fileName,\n defaultZoom = "fit-width",\n defaultMode = "view",\n annotationAuthor = DEFAULT_ANNOTATION_AUTHOR,\n colorPresets = PDF_EDITOR_DEFAULT_COLOR_PRESETS,\n features,\n showToolbar = true,\n showUpload = true,\n showDownload = true,\n toolbarActions,\n selectionActions,\n persistSignatures = true,\n stampManifests,\n signatureFontsStylesheetUrl = PDF_EDITOR_DEFAULT_SIGNATURE_FONTS_URL,\n resolveScrollAreaViewport,\n renderPageOverlay,\n onDocumentLoadSuccess,\n onDocumentLoadError,\n onActivePageChange,\n onModeChange,\n onAnnotationEvent,\n onAnnotationsChange,\n onFormValuesChange,\n onRedactionsApplied,\n onSave,\n onCapture,\n onPdfUpload,\n onToast,\n onSelectionAction,\n },\n ref\n ) {\n const { engine, error: engineError } = useSharedPdfEngine()\n const {\n source,\n loading: sourceLoading,\n replace,\n } = useEditorSource(src, fileName)\n const handleRef = React.useRef<EditorHandleImpl | null>(null)\n const resolvedFeatures = React.useMemo<PdfEditorResolvedFeatures>(\n () => ({ ...PDF_EDITOR_DEFAULT_FEATURES, ...features }),\n [features]\n )\n const resolvedSelectionActions = React.useMemo(\n () => selectionActions ?? [],\n [selectionActions]\n )\n const signatureStorageKey =\n persistSignatures === false\n ? null\n : typeof persistSignatures === "string"\n ? persistSignatures\n : DEFAULT_SIGNATURE_STORAGE_KEY\n\n const handleUploadFile = React.useCallback(\n (file: File) => {\n file.arrayBuffer().then((buffer) => {\n replace(buffer, getPdfFileName(file.name))\n onPdfUpload?.(file)\n })\n },\n [onPdfUpload, replace]\n )\n\n // Plugin registrations are created once per editor instance.\n const [plugins] = React.useState(() => [\n createPluginRegistration(DocumentManagerPluginPackage),\n createPluginRegistration(ViewportPluginPackage, {\n viewportGap: PAGE_GAP,\n }),\n createPluginRegistration(ScrollPluginPackage, {\n defaultPageGap: PAGE_GAP,\n defaultBufferSize: 2,\n }),\n createPluginRegistration(RenderPluginPackage),\n createPluginRegistration(TilingPluginPackage, {\n tileSize: 768,\n overlapPx: 2.5,\n extraRings: 0,\n }),\n createPluginRegistration(InteractionManagerPluginPackage),\n createPluginRegistration(SelectionPluginPackage, {\n menuHeight: SELECTION_MENU_HEIGHT,\n }),\n createPluginRegistration(SearchPluginPackage, { showAllResults: true }),\n createPluginRegistration(ThumbnailPluginPackage, {\n width: THUMBNAIL_WIDTH,\n gap: THUMBNAIL_GAP,\n imagePadding: THUMBNAIL_IMAGE_PADDING,\n labelHeight: THUMBNAIL_LABEL_HEIGHT,\n paddingY: THUMBNAIL_PANE_PADDING_Y,\n buffer: 3,\n autoScroll: true,\n scrollBehavior: "auto",\n }),\n createPluginRegistration(ZoomPluginPackage, {\n defaultZoomLevel: toZoomLevel(defaultZoom),\n minZoom: MIN_ZOOM,\n maxZoom: MAX_ZOOM,\n }),\n createPluginRegistration(RotatePluginPackage),\n createPluginRegistration(SpreadPluginPackage, {\n defaultSpreadMode: SpreadMode.None,\n }),\n createPluginRegistration(PanPluginPackage, { defaultMode: "never" }),\n createPluginRegistration(HistoryPluginPackage),\n createPluginRegistration(AnnotationPluginPackage, {\n annotationAuthor,\n colorPresets,\n autoCommit: true,\n selectAfterCreate: true,\n deactivateToolAfterCreate: false,\n locked: { type: LockModeType.Include, categories: ["form"] },\n }),\n createPluginRegistration(FormPluginPackage),\n createPluginRegistration(RedactionPluginPackage, {\n drawBlackBoxes: true,\n useAnnotationMode: true,\n }),\n createPluginRegistration(StampPluginPackage, {\n defaultLibrary: {\n id: "custom",\n name: "Custom stamps",\n categories: ["custom", "sidebar"],\n },\n ...(stampManifests && stampManifests.length > 0\n ? {\n manifests: [\n {\n url: PDF_EDITOR_DEFAULT_STAMP_MANIFEST_URL,\n fallbackLocale: "en",\n },\n ...stampManifests.map((url) => ({ url })),\n ],\n }\n : {}),\n }),\n createPluginRegistration(SignaturePluginPackage, {\n mode: SignatureMode.SignatureAndInitials,\n defaultSize: { width: 160, height: 56 },\n }),\n createPluginRegistration(ExportPluginPackage, {\n defaultFileName: "document.pdf",\n }),\n createPluginRegistration(PrintPluginPackage),\n createPluginRegistration(CapturePluginPackage, {\n scale: 2,\n imageType: "image/png",\n withAnnotations: true,\n }),\n createPluginRegistration(FullscreenPluginPackage),\n createPluginRegistration(BookmarkPluginPackage),\n createPluginRegistration(AttachmentPluginPackage),\n ])\n\n React.useImperativeHandle(\n ref,\n () => ({\n getDocumentBuffer: () =>\n handleRef.current?.getDocumentBuffer() ??\n Promise.reject(new Error("The document is not ready.")),\n download: (name) =>\n handleRef.current?.download(name) ?? Promise.resolve(),\n print: (options) =>\n handleRef.current?.print(options) ?? Promise.resolve(),\n exportAnnotations: () =>\n handleRef.current?.exportAnnotations() ?? Promise.resolve([]),\n importAnnotations: (items) =>\n handleRef.current?.importAnnotations(items),\n getFormValues: () => handleRef.current?.getFormValues() ?? {},\n setFormValues: (values) =>\n handleRef.current?.setFormValues(values) ?? Promise.resolve(),\n applyRedactions: () =>\n handleRef.current?.applyRedactions() ?? Promise.resolve(),\n setMode: (mode) => handleRef.current?.setMode(mode),\n setActiveTool: (toolId) => handleRef.current?.setActiveTool(toolId),\n scrollToPage: (pageNumber, options) =>\n handleRef.current?.scrollToPage(pageNumber, options),\n undo: () => handleRef.current?.undo(),\n redo: () => handleRef.current?.redo(),\n getViewportElement: () =>\n handleRef.current?.getViewportElement() ?? null,\n }),\n []\n )\n\n if (engineError) {\n return (\n <PdfEditorFallbackShell\n className={className}\n fileName={source?.name}\n showToolbar={showToolbar}\n showUpload={showUpload}\n state="error"\n errorMessage="The PDF engine could not be loaded."\n onUploadFile={handleUploadFile}\n />\n )\n }\n\n if (!engine) {\n return (\n <PdfEditorFallbackShell\n className={className}\n fileName={source?.name}\n showToolbar={showToolbar}\n showUpload={showUpload}\n state="loading"\n onUploadFile={handleUploadFile}\n />\n )\n }\n\n return (\n <PdfEditorScrollAreaResolverContext.Provider\n value={resolveScrollAreaViewport ?? resolveDefaultScrollAreaViewport}\n >\n <EmbedPDF engine={engine} plugins={plugins}>\n <PdfEditorDocumentLoader\n source={source}\n sourceLoading={sourceLoading}\n fileNameOverride={fileName}\n signatureStorageKey={signatureStorageKey}\n className={className}\n defaultZoom={defaultZoom}\n defaultMode={defaultMode}\n annotationAuthor={annotationAuthor}\n features={resolvedFeatures}\n showToolbar={showToolbar}\n showUpload={showUpload}\n showDownload={showDownload}\n toolbarActions={toolbarActions}\n selectionActions={resolvedSelectionActions}\n signatureFontsStylesheetUrl={signatureFontsStylesheetUrl}\n renderPageOverlay={renderPageOverlay}\n handleRef={handleRef}\n onReplaceDocument={replace}\n onUploadFile={handleUploadFile}\n onDocumentLoadSuccess={onDocumentLoadSuccess}\n onDocumentLoadError={onDocumentLoadError}\n onActivePageChange={onActivePageChange}\n onModeChange={onModeChange}\n onAnnotationEvent={onAnnotationEvent}\n onAnnotationsChange={onAnnotationsChange}\n onFormValuesChange={onFormValuesChange}\n onRedactionsApplied={onRedactionsApplied}\n onSave={onSave}\n onCapture={onCapture}\n onToast={onToast}\n onSelectionAction={onSelectionAction}\n />\n </EmbedPDF>\n </PdfEditorScrollAreaResolverContext.Provider>\n )\n }\n)\n',
+ code: '"use client"\n\nimport * as React from "react"\nimport { createPluginRegistration } from "@embedpdf/core"\nimport {\n EmbedPDF,\n useDocumentPermissions,\n useDocumentState,\n useRegistry,\n} from "@embedpdf/core/react"\nimport {\n PdfAnnotationSubtype,\n PdfErrorCode,\n PdfPageFlattenFlag,\n uuidV4,\n type PdfAnnotationObject,\n type PdfDocumentObject,\n type PdfEngine,\n type PdfLinkAnnoObject,\n type PdfPrintOptions,\n} from "@embedpdf/models"\nimport {\n AnnotationLayer,\n AnnotationPluginPackage,\n getSelectedAnnotations,\n LockModeType,\n useAnnotation,\n useAnnotationCapability,\n type AnnotationEvent,\n type AnnotationSelectionMenuProps,\n type AnnotationTransferItem,\n type GroupSelectionMenuProps,\n} from "@embedpdf/plugin-annotation/react"\nimport { AttachmentPluginPackage } from "@embedpdf/plugin-attachment/react"\nimport { BookmarkPluginPackage } from "@embedpdf/plugin-bookmark/react"\nimport {\n CapturePluginPackage,\n MarqueeCapture,\n useCapture,\n type CaptureAreaEvent,\n} from "@embedpdf/plugin-capture/react"\nimport {\n DocumentManagerPluginPackage,\n useActiveDocument,\n useDocumentManagerCapability,\n} from "@embedpdf/plugin-document-manager/react"\nimport { ExportPluginPackage, useExport } from "@embedpdf/plugin-export/react"\nimport {\n FormPluginPackage,\n useFormCapability,\n} from "@embedpdf/plugin-form/react"\nimport {\n FullscreenPluginPackage,\n useFullscreen,\n} from "@embedpdf/plugin-fullscreen/react"\nimport {\n HistoryPluginPackage,\n useHistoryCapability,\n} from "@embedpdf/plugin-history/react"\nimport {\n GlobalPointerProvider,\n InteractionManagerPluginPackage,\n PagePointerProvider,\n} from "@embedpdf/plugin-interaction-manager/react"\nimport { PanPluginPackage, usePan } from "@embedpdf/plugin-pan/react"\nimport { PrintPluginPackage, usePrint } from "@embedpdf/plugin-print/react"\nimport {\n RedactionLayer,\n RedactionMode,\n RedactionPluginPackage,\n useRedaction,\n type RedactionSelectionMenuProps,\n} from "@embedpdf/plugin-redaction/react"\nimport { RenderLayer, RenderPluginPackage } from "@embedpdf/plugin-render/react"\nimport {\n Rotate,\n RotatePluginPackage,\n useRotate,\n} from "@embedpdf/plugin-rotate/react"\nimport {\n Scroller,\n ScrollPluginPackage,\n ScrollStrategy,\n useScroll,\n useScrollCapability,\n type PageLayout,\n} from "@embedpdf/plugin-scroll/react"\nimport {\n SearchLayer,\n SearchPluginPackage,\n useSearch,\n} from "@embedpdf/plugin-search/react"\nimport {\n CopyToClipboard,\n SelectionLayer,\n SelectionPluginPackage,\n useSelectionCapability,\n type SelectionSelectionMenuProps,\n} from "@embedpdf/plugin-selection/react"\nimport {\n deserializeEntries,\n serializeEntries,\n SignatureMode,\n SignaturePluginPackage,\n useSignatureCapability,\n} from "@embedpdf/plugin-signature/react"\nimport {\n SpreadMode,\n SpreadPluginPackage,\n useSpread,\n} from "@embedpdf/plugin-spread/react"\nimport { StampPluginPackage } from "@embedpdf/plugin-stamp/react"\nimport { ThumbnailPluginPackage } from "@embedpdf/plugin-thumbnail/react"\nimport { TilingLayer, TilingPluginPackage } from "@embedpdf/plugin-tiling/react"\nimport {\n useIsViewportGated,\n useViewportCapability,\n useViewportElement,\n useViewportRef,\n ViewportElementContext,\n ViewportPluginPackage,\n} from "@embedpdf/plugin-viewport/react"\nimport {\n MarqueeZoom,\n useZoom,\n ZoomMode,\n ZoomPluginPackage,\n} from "@embedpdf/plugin-zoom/react"\n\nimport { loadSharedPdfEngine } from "@/lib/pdf-thumbnail-utils"\nimport { cn } from "@/lib/utils"\nimport { Badge } from "@/components/ui/badge"\nimport { Button } from "@/components/ui/button"\nimport { ColorPicker } from "@/components/ui/color-picker"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuGroup,\n DropdownMenuItem,\n DropdownMenuLabel,\n DropdownMenuRadioGroup,\n DropdownMenuRadioItem,\n DropdownMenuSeparator,\n DropdownMenuShortcut,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { Input } from "@/components/ui/input"\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from "@/components/ui/popover"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Spinner } from "@/components/ui/spinner"\nimport { ToastPrimitive, ToastProvider } from "@/components/ui/toast"\nimport { TooltipProvider } from "@/components/ui/tooltip"\nimport {\n DocumentViewerSidebarSkeleton,\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/extend/document-viewer-sidebar"\nimport {\n PdfEditorCaptureDialog,\n PdfEditorConfirmDialog,\n PdfEditorLinkDialog,\n PdfEditorPasswordPrompt,\n PdfEditorPrintDialog,\n PdfEditorPropertiesDialog,\n PdfEditorSecurityDialog,\n PdfEditorShortcutsDialog,\n PdfEditorSignatureDialog,\n} from "@/components/extend/pdf-editor-dialogs"\nimport {\n PdfEditorAttachmentsPanel,\n PdfEditorCommentsPanel,\n PdfEditorFormsPanel,\n PdfEditorOutlinePanel,\n PdfEditorPagesPanel,\n PdfEditorRedactionsPanel,\n PdfEditorSignaturesPanel,\n PdfEditorStampsPanel,\n PdfEditorThumbnailsPanel,\n} from "@/components/extend/pdf-editor-panels"\nimport { PdfEditorPropertiesPanel } from "@/components/extend/pdf-editor-properties"\nimport {\n BookOpenGlyph,\n CameraGlyph,\n ChevronLeftGlyph,\n ChevronRightGlyph,\n CloseGlyph,\n CommentGlyph,\n CommentsGlyph,\n CopyGlyph,\n CursorGlyph,\n downloadArrayBuffer,\n downloadBlob,\n DownloadGlyph,\n EditGlyph,\n ExitFullscreenGlyph,\n ExternalLinkGlyph,\n EyeOffGlyph,\n FileTextGlyph,\n FullscreenGlyph,\n getPdfFileName,\n GridGlyph,\n GroupGlyph,\n HandGlyph,\n HighlighterGlyph,\n InfoGlyph,\n isTypingTarget,\n KeyboardGlyph,\n LayersGlyph,\n LinkGlyph,\n ListTreeGlyph,\n LockGlyph,\n MarqueeZoomGlyph,\n MoreGlyph,\n noop,\n PaletteGlyph,\n PanelLeftGlyph,\n PanelRightGlyph,\n PaperclipGlyph,\n PDF_EDITOR_ANNOTATION_TOOL_GROUPS,\n PDF_EDITOR_DEFAULT_COLOR_PRESETS,\n PDF_EDITOR_DEFAULT_FEATURES,\n PDF_EDITOR_DEFAULT_SIGNATURE_FONTS_URL,\n PDF_EDITOR_DEFAULT_STAMP_MANIFEST_URL,\n PDF_EDITOR_FORM_TOOLS,\n PDF_EDITOR_MODE_OPTIONS,\n PDF_EDITOR_SELECTION_COLOR,\n PdfEditorContextProvider,\n PdfEditorScrollArea,\n PdfEditorScrollAreaResolverContext,\n PdfEditorToolbarSeparator,\n PdfEditorToolButton,\n PdfEditorTooltip,\n PlusGlyph,\n PrintGlyph,\n RedactAreaGlyph,\n RedoGlyph,\n resolveDefaultScrollAreaViewport,\n RotateGlyph,\n SearchGlyph,\n ShieldGlyph,\n SignatureGlyph,\n SlidersGlyph,\n StampGlyph,\n StrikethroughGlyph,\n TextFieldGlyph,\n TextGlyph,\n toNormalizedRect,\n TrashGlyph,\n UnderlineGlyph,\n UndoGlyph,\n UngroupGlyph,\n UnlockGlyph,\n UploadGlyph,\n usePdfEditor,\n ZoomInGlyph,\n ZoomOutGlyph,\n type PdfEditorContextValue,\n type PdfEditorDialogRequest,\n type PdfEditorFeatureFlags,\n type PdfEditorGlyph,\n type PdfEditorLeftPanel,\n type PdfEditorMode,\n type PdfEditorNoticeTone,\n type PdfEditorResolvedFeatures,\n type PdfEditorRightPanel,\n type PdfEditorScrollAreaViewportResolver,\n type PdfEditorSelectionAction,\n type PdfEditorSelectionPage,\n type PdfEditorSelectionPayload,\n} from "@/components/extend/pdf-editor-shared"\n\nexport type {\n PdfEditorFeatureFlags,\n PdfEditorLeftPanel,\n PdfEditorMode,\n PdfEditorNormalizedRect,\n PdfEditorRightPanel,\n PdfEditorSelectionAction,\n PdfEditorSelectionPayload,\n} from "@/components/extend/pdf-editor-shared"\n\n/* -------------------------------------------------------------------------- */\n/* Public types */\n/* -------------------------------------------------------------------------- */\n\nexport type PDFEditorPageOverlayProps = {\n pageNumber: number\n pageWidth: number\n pageHeight: number\n scale: number\n rotation: number\n}\n\nexport type PDFEditorZoomLevel = number | "fit-page" | "fit-width" | "automatic"\n\nexport type PDFEditorToast = {\n message: string\n tone: PdfEditorNoticeTone\n}\n\nexport type PDFEditorHandle = {\n /** Current PDF bytes including annotations, form values, and pending security changes. */\n getDocumentBuffer: () => Promise<ArrayBuffer>\n download: (fileName?: string) => Promise<void>\n print: (options?: PdfPrintOptions) => Promise<void>\n exportAnnotations: () => Promise<AnnotationTransferItem[]>\n importAnnotations: (items: AnnotationTransferItem[]) => void\n getFormValues: () => Record<string, string>\n setFormValues: (values: Record<string, string>) => Promise<void>\n /** Permanently applies every pending redaction mark. */\n applyRedactions: () => Promise<void>\n setMode: (mode: PdfEditorMode) => void\n /** Activates an EmbedPDF annotation tool id such as `highlight` or `ink`; `null` returns to selection. */\n setActiveTool: (toolId: string | null) => void\n scrollToPage: (pageNumber: number, options?: ScrollIntoViewOptions) => void\n undo: () => void\n redo: () => void\n getViewportElement: () => HTMLDivElement | null\n}\n\nexport type PDFEditorProps = {\n className?: string\n /** A URL, or the PDF bytes as an ArrayBuffer, Uint8Array, Blob, or File. */\n src?: string | ArrayBuffer | Uint8Array | Blob\n fileName?: string\n defaultZoom?: PDFEditorZoomLevel\n defaultMode?: PdfEditorMode\n /** Author written into new annotations. Defaults to "Guest". */\n annotationAuthor?: string\n colorPresets?: string[]\n /** Turn individual editing capabilities off. Everything is enabled by default. */\n features?: PdfEditorFeatureFlags\n showToolbar?: boolean\n showUpload?: boolean\n showDownload?: boolean\n toolbarActions?: React.ReactNode\n /** Extra actions for the text selection menu. Each receives normalized page coordinates. */\n selectionActions?: PdfEditorSelectionAction[]\n /** Persist saved signatures in localStorage. Pass a string to use a custom storage key. */\n persistSignatures?: boolean | string\n /** Additional rubber stamp manifests to load next to the built-in library. */\n stampManifests?: string[]\n /** Stylesheet used for the typed-signature fonts. Pass `null` to skip loading web fonts. */\n signatureFontsStylesheetUrl?: string | null\n resolveScrollAreaViewport?: PdfEditorScrollAreaViewportResolver\n renderPageOverlay?: (props: PDFEditorPageOverlayProps) => React.ReactNode\n onDocumentLoadSuccess?: (info: {\n numPages: number\n documentId: string\n fileName: string\n }) => void\n onDocumentLoadError?: (message: string) => void\n onActivePageChange?: (pageNumber: number) => void\n onModeChange?: (mode: PdfEditorMode) => void\n onAnnotationEvent?: (event: AnnotationEvent) => void\n /** Fires with the full annotation set after every committed change (debounced). */\n onAnnotationsChange?: (items: AnnotationTransferItem[]) => void\n onFormValuesChange?: (values: Record<string, string>) => void\n onRedactionsApplied?: () => void\n onSave?: (result: { buffer: ArrayBuffer; fileName: string }) => void\n onCapture?: (event: CaptureAreaEvent) => void\n onPdfUpload?: (file: File) => void\n /** Routes editor notices to a host-owned toast system instead of the built-in viewport. */\n onToast?: (toast: PDFEditorToast) => void\n onSelectionAction?: (\n actionId: string,\n payload: PdfEditorSelectionPayload\n ) => void\n}\n\n/* -------------------------------------------------------------------------- */\n/* Constants */\n/* -------------------------------------------------------------------------- */\n\nconst PAGE_GAP = 24\nconst THUMBNAIL_PAGE_WIDTH = 92\nconst THUMBNAIL_IMAGE_PADDING = 8\nconst THUMBNAIL_WIDTH = THUMBNAIL_PAGE_WIDTH + THUMBNAIL_IMAGE_PADDING * 2\nconst THUMBNAIL_LABEL_HEIGHT = 24\nconst THUMBNAIL_GAP = 12\nconst THUMBNAIL_PANE_PADDING_Y = 16\nconst LEFT_SIDEBAR_WIDTH_CLASS = "w-56"\nconst LEFT_SIDEBAR_CLOSED_CLASS = "-ml-56"\nconst RIGHT_PANEL_WIDTH_CLASS = "w-84"\nconst RIGHT_PANEL_INLINE_MIN_WIDTH = 1100\nconst TOOLBAR_STACK_MAX_WIDTH = 640\nconst ZOOM_PRESETS = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 3, 4]\nconst MIN_ZOOM = 0.1\nconst MAX_ZOOM = 8\nconst PAGE_BASE_RENDER_MAX_SCALE = 1\nconst PAGE_BASE_RENDER_DPR = 1\nconst SEARCH_DEBOUNCE_MS = 300\nconst NOTICE_DURATION_MS = 4200\nconst TOOLTIP_DELAY_MS = 5\nconst SELECTION_MENU_OFFSET = 8\nconst SELECTION_MENU_HEIGHT = 36\nconst DEFAULT_SIGNATURE_STORAGE_KEY = "pdf-editor:signatures"\nconst DEFAULT_ANNOTATION_AUTHOR = "Guest"\n\nconst ZOOM_MODE_LABELS: Record<ZoomMode, string> = {\n [ZoomMode.FitPage]: "Fit page",\n [ZoomMode.FitWidth]: "Fit width",\n [ZoomMode.Automatic]: "Automatic",\n}\nconst SPREAD_MODE_OPTIONS = [\n { label: "Single page", value: SpreadMode.None },\n { label: "Two pages", value: SpreadMode.Odd },\n { label: "Two pages, cover", value: SpreadMode.Even },\n]\nconst SCROLL_DIRECTION_OPTIONS = [\n { label: "Scroll down", value: "vertical" },\n { label: "Scroll sideways", value: "horizontal" },\n]\n\nfunction toZoomLevel(level: PDFEditorZoomLevel): ZoomMode | number {\n if (level === "fit-page") return ZoomMode.FitPage\n if (level === "fit-width") return ZoomMode.FitWidth\n if (level === "automatic") return ZoomMode.Automatic\n return level\n}\n\nfunction isZoomMode(value: unknown): value is ZoomMode {\n return (\n value === ZoomMode.FitPage ||\n value === ZoomMode.FitWidth ||\n value === ZoomMode.Automatic\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Engine + document source */\n/* -------------------------------------------------------------------------- */\n\nfunction useSharedPdfEngine() {\n const [engine, setEngine] = React.useState<PdfEngine | null>(null)\n const [error, setError] = React.useState<Error | null>(null)\n\n React.useEffect(() => {\n let cancelled = false\n\n loadSharedPdfEngine().then(\n (loadedEngine) => {\n if (!cancelled) setEngine(loadedEngine)\n },\n (loadError: Error) => {\n if (!cancelled) setError(loadError)\n }\n )\n\n return () => {\n cancelled = true\n }\n }, [])\n\n return { engine, error }\n}\n\ntype EditorSource =\n | { key: string; kind: "url"; url: string; name: string }\n | { key: string; kind: "buffer"; buffer: ArrayBuffer; name: string }\n\nlet sourceCounter = 0\n\nfunction nextSourceKey() {\n sourceCounter += 1\n return `pdf-editor-source-${sourceCounter}`\n}\n\nfunction bytesToArrayBuffer(bytes: Uint8Array) {\n const copy = new ArrayBuffer(bytes.byteLength)\n new Uint8Array(copy).set(bytes)\n return copy\n}\n\nfunction useEditorSource(\n src: PDFEditorProps["src"],\n fileName: string | undefined\n) {\n const [state, setState] = React.useState<{\n src: PDFEditorProps["src"]\n source: EditorSource | null\n loading: boolean\n }>({ src: undefined, source: null, loading: false })\n\n React.useEffect(() => {\n if (src === undefined || src === null) {\n setState({ src, source: null, loading: false })\n return\n }\n\n if (typeof src === "string") {\n setState({\n src,\n source: {\n key: nextSourceKey(),\n kind: "url",\n url: src,\n name: getPdfFileName(fileName, src),\n },\n loading: false,\n })\n return\n }\n\n if (src instanceof ArrayBuffer) {\n setState({\n src,\n source: {\n key: nextSourceKey(),\n kind: "buffer",\n buffer: src.slice(0),\n name: getPdfFileName(fileName),\n },\n loading: false,\n })\n return\n }\n\n if (src instanceof Uint8Array) {\n setState({\n src,\n source: {\n key: nextSourceKey(),\n kind: "buffer",\n buffer: bytesToArrayBuffer(src),\n name: getPdfFileName(fileName),\n },\n loading: false,\n })\n return\n }\n\n let cancelled = false\n const blobName = fileName ?? (src instanceof File ? src.name : undefined)\n\n setState({ src, source: null, loading: true })\n src.arrayBuffer().then((buffer) => {\n if (cancelled) return\n\n setState({\n src,\n source: {\n key: nextSourceKey(),\n kind: "buffer",\n buffer,\n name: getPdfFileName(blobName),\n },\n loading: false,\n })\n })\n\n return () => {\n cancelled = true\n }\n }, [fileName, src])\n\n const replace = React.useCallback((buffer: ArrayBuffer, name: string) => {\n setState((previous) => ({\n ...previous,\n source: { key: nextSourceKey(), kind: "buffer", buffer, name },\n loading: false,\n }))\n }, [])\n\n return { source: state.source, loading: state.loading, replace }\n}\n\n/* -------------------------------------------------------------------------- */\n/* Annotation JSON serialization */\n/* -------------------------------------------------------------------------- */\n\nfunction arrayBufferToBase64(buffer: ArrayBuffer) {\n const bytes = new Uint8Array(buffer)\n let binary = ""\n\n for (let index = 0; index < bytes.length; index += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000))\n }\n\n return btoa(binary)\n}\n\nfunction base64ToArrayBuffer(value: string) {\n const binary = atob(value)\n const bytes = new Uint8Array(binary.length)\n\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index)\n }\n\n return bytes.buffer\n}\n\ntype SerializedAnnotationItem = {\n annotation: PdfAnnotationObject\n ctx?: { data: string; mimeType?: string }\n}\n\nexport function serializeAnnotationItems(items: AnnotationTransferItem[]) {\n return {\n format: "extend-ui/pdf-editor-annotations",\n version: 1,\n exportedAt: new Date().toISOString(),\n annotations: items.map((item): SerializedAnnotationItem => {\n const context = item.ctx as\n | { data?: ArrayBuffer; mimeType?: string }\n | undefined\n\n return {\n annotation: item.annotation,\n ...(context?.data instanceof ArrayBuffer\n ? {\n ctx: {\n data: arrayBufferToBase64(context.data),\n mimeType: context.mimeType,\n },\n }\n : {}),\n }\n }),\n }\n}\n\nexport function deserializeAnnotationItems(\n payload: unknown\n): AnnotationTransferItem[] {\n const list = Array.isArray(payload)\n ? payload\n : payload &&\n typeof payload === "object" &&\n Array.isArray((payload as { annotations?: unknown }).annotations)\n ? (payload as { annotations: unknown[] }).annotations\n : null\n\n if (!list) throw new Error("Unrecognized annotation export.")\n\n return list.map((entry) => {\n const item = entry as SerializedAnnotationItem\n\n if (!item || typeof item !== "object" || !item.annotation) {\n throw new Error("Unrecognized annotation export.")\n }\n\n return {\n annotation: item.annotation,\n ...(item.ctx?.data\n ? {\n ctx: {\n data: base64ToArrayBuffer(item.ctx.data),\n mimeType: item.ctx.mimeType,\n } as AnnotationTransferItem["ctx"],\n }\n : {}),\n }\n })\n}\n\n/* -------------------------------------------------------------------------- */\n/* Viewport */\n/* -------------------------------------------------------------------------- */\n\nfunction PdfEditorViewport({\n children,\n className,\n documentId,\n}: {\n children: React.ReactNode\n className?: string\n documentId: string\n}) {\n const viewportRef = useViewportRef(documentId)\n const { provides: viewport } = useViewportCapability()\n const isGated = useIsViewportGated(documentId)\n const viewportGap = viewport?.getViewportGap() ?? 0\n\n return (\n <ViewportElementContext.Provider value={viewportRef}>\n <PdfEditorScrollArea\n className={className}\n orientation="both"\n scrollbarGutter={false}\n viewportClassName="relative select-none selection:bg-transparent selection:text-inherit"\n viewportProps={{ style: { padding: viewportGap } }}\n viewportRef={viewportRef}\n >\n {isGated ? null : children}\n </PdfEditorScrollArea>\n </ViewportElementContext.Provider>\n )\n}\n\nfunction PdfEditorViewportBridge({\n viewportElementRef,\n}: {\n viewportElementRef: React.MutableRefObject<HTMLDivElement | null>\n}) {\n const elementRef = useViewportElement()\n\n React.useEffect(() => {\n viewportElementRef.current = elementRef?.current ?? null\n })\n\n return null\n}\n\n/* -------------------------------------------------------------------------- */\n/* Selection menus rendered inside the page layers */\n/* -------------------------------------------------------------------------- */\n\nfunction SelectionMenuShell({\n rect,\n placement,\n menuWrapperProps,\n children,\n}: {\n rect: SelectionSelectionMenuProps["rect"]\n placement: SelectionSelectionMenuProps["placement"]\n menuWrapperProps: SelectionSelectionMenuProps["menuWrapperProps"]\n children: React.ReactNode\n}) {\n return (\n <div {...menuWrapperProps}>\n <div\n data-slot="pdf-editor-selection-menu"\n className="flex items-center gap-0.5 rounded-lg border bg-popover p-1 text-popover-foreground shadow-lg"\n style={{\n position: "absolute",\n left: 0,\n top: placement.suggestTop\n ? -(SELECTION_MENU_HEIGHT + SELECTION_MENU_OFFSET)\n : rect.size.height + SELECTION_MENU_OFFSET,\n pointerEvents: "auto",\n cursor: "default",\n whiteSpace: "nowrap",\n }}\n onPointerDown={(event) => event.stopPropagation()}\n >\n <TooltipProvider delay={TOOLTIP_DELAY_MS}>{children}</TooltipProvider>\n </div>\n </div>\n )\n}\n\nfunction MenuButton({\n label,\n glyph: Glyph,\n onClick,\n disabled,\n destructive,\n}: {\n label: string\n glyph: PdfEditorGlyph\n onClick: () => void\n disabled?: boolean\n destructive?: boolean\n}) {\n return (\n <PdfEditorToolButton\n label={label}\n size="icon-xs"\n disabled={disabled}\n className={cn(destructive && "text-destructive hover:text-destructive")}\n onClick={(event) => {\n event.stopPropagation()\n onClick()\n }}\n >\n <Glyph className="size-3.5" />\n </PdfEditorToolButton>\n )\n}\n\nasync function buildSelectionPayload(\n documentId: string,\n document: PdfDocumentObject | null,\n selectionScope: ReturnType<\n NonNullable<\n ReturnType<typeof useSelectionCapability>["provides"]\n >["forDocument"]\n >\n): Promise<PdfEditorSelectionPayload | null> {\n const formatted = selectionScope.getFormattedSelection()\n\n if (formatted.length === 0) return null\n\n let text = ""\n\n try {\n const lines = await selectionScope.getSelectedText().toPromise()\n text = lines.join("\\n")\n } catch {\n text = ""\n }\n\n const pages: PdfEditorSelectionPage[] = formatted.map((page) => {\n const pageSize = document?.pages[page.pageIndex]?.size ?? {\n width: 1,\n height: 1,\n }\n\n return {\n pageIndex: page.pageIndex,\n pageNumber: page.pageIndex + 1,\n pageSize,\n rect: page.rect,\n rects: page.segmentRects,\n normalizedRect: toNormalizedRect(page.rect, pageSize),\n normalizedRects: page.segmentRects.map((rect) =>\n toNormalizedRect(rect, pageSize)\n ),\n }\n })\n\n return { documentId, text, pages, ...pages[0] }\n}\n\nfunction PdfEditorTextSelectionMenu({\n documentId,\n rect,\n placement,\n menuWrapperProps,\n}: SelectionSelectionMenuProps & { documentId: string }) {\n const { provides: selectionCapability } = useSelectionCapability()\n const { provides: annotationCapability } = useAnnotationCapability()\n const { provides: annotation } = useAnnotation(documentId)\n const { provides: redaction } = useRedaction(documentId)\n const editor = usePdfEditor()\n const selectionScope = React.useMemo(\n () => selectionCapability?.forDocument(documentId) ?? null,\n [documentId, selectionCapability]\n )\n const canAnnotate =\n editor.features.annotate && editor.permissions.canModifyAnnotations\n const canRedact =\n editor.features.redact && editor.permissions.canModifyContents\n\n const createMarkup = (\n toolId: string,\n subtype:\n | PdfAnnotationSubtype.HIGHLIGHT\n | PdfAnnotationSubtype.UNDERLINE\n | PdfAnnotationSubtype.STRIKEOUT,\n options: { select?: boolean; openComments?: boolean } = {}\n ) => {\n if (!selectionScope || !annotation) return\n\n const formatted = selectionScope.getFormattedSelection()\n\n if (formatted.length === 0) return\n\n const defaults = (annotationCapability?.getTool(toolId)?.defaults ??\n {}) as Record<string, unknown>\n\n const finish = (text: string[]) => {\n let firstId: { pageIndex: number; id: string } | null = null\n\n for (const page of formatted) {\n const id = uuidV4()\n\n annotation.createAnnotation(page.pageIndex, {\n ...defaults,\n id,\n type: subtype,\n pageIndex: page.pageIndex,\n rect: page.rect,\n segmentRects: page.segmentRects,\n author: editor.annotationAuthor,\n created: new Date(),\n modified: new Date(),\n flags: ["print"],\n custom: text.length ? { text: text.join("\\n") } : undefined,\n } as PdfAnnotationObject)\n\n firstId ??= { pageIndex: page.pageIndex, id }\n }\n\n selectionScope.clear()\n\n if (options.select && firstId) {\n annotation.selectAnnotation(firstId.pageIndex, firstId.id)\n }\n\n if (options.openComments) editor.setRightPanel("comments")\n }\n\n selectionScope.getSelectedText().wait(finish, () => finish([]))\n }\n\n const runCustomAction = async (action: PdfEditorSelectionAction) => {\n if (!selectionScope) return\n\n const payload = await buildSelectionPayload(\n documentId,\n editor.document,\n selectionScope\n )\n\n if (!payload) return\n\n action.onSelect?.(payload)\n editor.onSelectionAction?.(action.id, payload)\n\n if (!action.keepSelection) selectionScope.clear()\n }\n\n return (\n <SelectionMenuShell\n rect={rect}\n placement={placement}\n menuWrapperProps={menuWrapperProps}\n >\n <MenuButton\n label="Copy"\n glyph={CopyGlyph}\n onClick={() => {\n selectionScope?.copyToClipboard()\n selectionScope?.clear()\n }}\n />\n {canAnnotate ? (\n <>\n <PdfEditorToolbarSeparator />\n <MenuButton\n label="Highlight"\n glyph={HighlighterGlyph}\n onClick={() =>\n createMarkup("highlight", PdfAnnotationSubtype.HIGHLIGHT)\n }\n />\n <MenuButton\n label="Underline"\n glyph={UnderlineGlyph}\n onClick={() =>\n createMarkup("underline", PdfAnnotationSubtype.UNDERLINE)\n }\n />\n <MenuButton\n label="Strikethrough"\n glyph={StrikethroughGlyph}\n onClick={() =>\n createMarkup("strikeout", PdfAnnotationSubtype.STRIKEOUT)\n }\n />\n {editor.features.comments ? (\n <MenuButton\n label="Comment"\n glyph={CommentGlyph}\n onClick={() =>\n createMarkup("highlight", PdfAnnotationSubtype.HIGHLIGHT, {\n select: true,\n openComments: true,\n })\n }\n />\n ) : null}\n <MenuButton\n label="Add link"\n glyph={LinkGlyph}\n onClick={() =>\n editor.openDialog({ type: "link", source: "selection" })\n }\n />\n </>\n ) : null}\n {canRedact ? (\n <>\n <PdfEditorToolbarSeparator />\n <MenuButton\n label="Mark for redaction"\n glyph={EyeOffGlyph}\n onClick={() => {\n redaction?.queueCurrentSelectionAsPending().wait(\n () => {\n selectionScope?.clear()\n editor.setRightPanel("redactions")\n },\n () =>\n editor.notify("The selection could not be marked.", "error")\n )\n }}\n />\n </>\n ) : null}\n {editor.selectionActions.length > 0 ? (\n <>\n <PdfEditorToolbarSeparator />\n {editor.selectionActions.map((action) => (\n <PdfEditorTooltip key={action.id} label={action.label}>\n <Button\n type="button"\n size="xs"\n variant="ghost"\n onClick={(event) => {\n event.stopPropagation()\n void runCustomAction(action)\n }}\n >\n {action.icon}\n {action.label}\n </Button>\n </PdfEditorTooltip>\n ))}\n </>\n ) : null}\n </SelectionMenuShell>\n )\n}\n\nconst STAMP_SOURCE_TYPES = new Set<PdfAnnotationSubtype>([\n PdfAnnotationSubtype.INK,\n PdfAnnotationSubtype.SQUARE,\n PdfAnnotationSubtype.CIRCLE,\n PdfAnnotationSubtype.LINE,\n PdfAnnotationSubtype.POLYLINE,\n PdfAnnotationSubtype.POLYGON,\n PdfAnnotationSubtype.FREETEXT,\n PdfAnnotationSubtype.STAMP,\n PdfAnnotationSubtype.TEXT,\n])\n\nfunction PdfEditorAnnotationMenu({\n documentId,\n selected,\n context,\n rect,\n placement,\n menuWrapperProps,\n}: AnnotationSelectionMenuProps & { documentId: string }) {\n const { provides: annotation } = useAnnotation(documentId)\n const { provides: redaction } = useRedaction(documentId)\n const editor = usePdfEditor()\n\n if (!selected || !annotation) return null\n\n const object = context.annotation.object\n const { pageIndex, id } = object\n const isRedact = object.type === PdfAnnotationSubtype.REDACT\n const isWidget = object.type === PdfAnnotationSubtype.WIDGET\n const isLink = object.type === PdfAnnotationSubtype.LINK\n const isLocked = (object.flags ?? []).includes("locked")\n const canModify = editor.permissions.canModifyAnnotations\n const canDelete = canModify && !context.structurallyLocked\n\n const remove = () => annotation.deleteAnnotation(pageIndex, id)\n\n if (isRedact) {\n return (\n <SelectionMenuShell\n rect={rect}\n placement={placement}\n menuWrapperProps={menuWrapperProps}\n >\n <MenuButton\n label="Apply redaction"\n glyph={EyeOffGlyph}\n disabled={!editor.permissions.canModifyContents}\n onClick={() =>\n editor.openDialog({\n type: "confirm",\n title: "Apply this redaction?",\n description: "The marked content is removed permanently.",\n confirmLabel: "Apply",\n onConfirm: () => {\n redaction\n ?.commitPending(pageIndex, id)\n .wait(noop, () =>\n editor.notify(\n "The redaction could not be applied.",\n "error"\n )\n )\n },\n })\n }\n />\n <MenuButton\n label="Style"\n glyph={SlidersGlyph}\n onClick={() => editor.setRightPanel("properties")}\n />\n <MenuButton\n label="Remove mark"\n glyph={TrashGlyph}\n destructive\n onClick={remove}\n />\n </SelectionMenuShell>\n )\n }\n\n if (isLink) {\n const target = (object as PdfLinkAnnoObject).target\n\n return (\n <SelectionMenuShell\n rect={rect}\n placement={placement}\n menuWrapperProps={menuWrapperProps}\n >\n <MenuButton\n label="Open link"\n glyph={ExternalLinkGlyph}\n disabled={!target}\n onClick={() => {\n if (!target) return\n\n annotation.navigateTarget(target).wait((result) => {\n if (result.outcome === "uri") {\n window.open(result.uri, "_blank", "noopener")\n }\n }, noop)\n }}\n />\n <MenuButton\n label="Edit link"\n glyph={EditGlyph}\n disabled={!canModify}\n onClick={() =>\n editor.openDialog({ type: "link", source: "annotation" })\n }\n />\n <MenuButton\n label="Delete"\n glyph={TrashGlyph}\n destructive\n disabled={!canDelete}\n onClick={remove}\n />\n </SelectionMenuShell>\n )\n }\n\n return (\n <SelectionMenuShell\n rect={rect}\n placement={placement}\n menuWrapperProps={menuWrapperProps}\n >\n {!isWidget && editor.features.comments ? (\n <MenuButton\n label="Comment"\n glyph={CommentGlyph}\n onClick={() => editor.setRightPanel("comments")}\n />\n ) : null}\n <MenuButton\n label="Properties"\n glyph={SlidersGlyph}\n onClick={() => editor.setRightPanel("properties")}\n />\n {!isWidget && canModify ? (\n <MenuButton\n label="Add link"\n glyph={LinkGlyph}\n onClick={() =>\n editor.openDialog({ type: "link", source: "annotation" })\n }\n />\n ) : null}\n {!isWidget &&\n editor.features.stamps &&\n canModify &&\n STAMP_SOURCE_TYPES.has(object.type) ? (\n <MenuButton\n label="Save as stamp"\n glyph={StampGlyph}\n onClick={() => editor.setRightPanel("stamps")}\n />\n ) : null}\n {!isWidget && canModify ? (\n <MenuButton\n label={isLocked ? "Unlock" : "Lock"}\n glyph={isLocked ? UnlockGlyph : LockGlyph}\n onClick={() => {\n const flags = object.flags ?? []\n annotation.updateAnnotation(pageIndex, id, {\n flags: isLocked\n ? flags.filter((flag) => flag !== "locked")\n : [...flags, "locked"],\n })\n }}\n />\n ) : null}\n <MenuButton\n label="Delete"\n glyph={TrashGlyph}\n destructive\n disabled={!canDelete}\n onClick={remove}\n />\n </SelectionMenuShell>\n )\n}\n\nfunction PdfEditorGroupMenu({\n documentId,\n selected,\n context,\n rect,\n placement,\n menuWrapperProps,\n}: GroupSelectionMenuProps & { documentId: string }) {\n const { provides: annotation } = useAnnotation(documentId)\n const editor = usePdfEditor()\n\n if (!selected || !annotation) return null\n\n const groupingAction = annotation.getGroupingAction()\n const canModify = editor.permissions.canModifyAnnotations\n\n return (\n <SelectionMenuShell\n rect={rect}\n placement={placement}\n menuWrapperProps={menuWrapperProps}\n >\n <span className="px-1.5 text-xs text-muted-foreground">\n {context.annotations.length} selected\n </span>\n <MenuButton\n label={groupingAction === "ungroup" ? "Ungroup" : "Group"}\n glyph={groupingAction === "ungroup" ? UngroupGlyph : GroupGlyph}\n disabled={!canModify || groupingAction === "disabled"}\n onClick={() => {\n if (groupingAction === "ungroup") {\n annotation.ungroupAnnotations(context.annotations[0].object.id)\n } else {\n annotation.groupAnnotations()\n }\n }}\n />\n <MenuButton\n label="Properties"\n glyph={SlidersGlyph}\n onClick={() => editor.setRightPanel("properties")}\n />\n <MenuButton\n label="Delete all"\n glyph={TrashGlyph}\n destructive\n disabled={!canModify}\n onClick={() =>\n annotation.deleteAnnotations(\n context.annotations.map((item) => ({\n pageIndex: item.object.pageIndex,\n id: item.object.id,\n }))\n )\n }\n />\n </SelectionMenuShell>\n )\n}\n\nfunction PdfEditorRedactionMenu({\n documentId,\n selected,\n context,\n rect,\n placement,\n menuWrapperProps,\n}: RedactionSelectionMenuProps & { documentId: string }) {\n const { provides: redaction } = useRedaction(documentId)\n const editor = usePdfEditor()\n\n if (!selected || !redaction) return null\n\n const { page, id } = context.item\n\n return (\n <SelectionMenuShell\n rect={rect}\n placement={placement}\n menuWrapperProps={menuWrapperProps}\n >\n <MenuButton\n label="Apply redaction"\n glyph={EyeOffGlyph}\n disabled={!editor.permissions.canModifyContents}\n onClick={() =>\n editor.openDialog({\n type: "confirm",\n title: "Apply this redaction?",\n description: "The marked content is removed permanently.",\n confirmLabel: "Apply",\n onConfirm: () => {\n redaction\n .commitPending(page, id)\n .wait(noop, () =>\n editor.notify("The redaction could not be applied.", "error")\n )\n },\n })\n }\n />\n <MenuButton\n label="Remove mark"\n glyph={TrashGlyph}\n destructive\n onClick={() => redaction.removePending(page, id)}\n />\n </SelectionMenuShell>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Toolbar controls */\n/* -------------------------------------------------------------------------- */\n\nfunction PdfEditorPageControl({\n activePage,\n numPages,\n disabled,\n onPageChange,\n}: {\n activePage: number\n numPages: number\n disabled: boolean\n onPageChange: (pageNumber: number) => void\n}) {\n const inputRef = React.useRef<HTMLInputElement>(null)\n const displayPage = numPages ? activePage : 1\n const [isEditing, setIsEditing] = React.useState(false)\n const [draftPage, setDraftPage] = React.useState(() => String(displayPage))\n\n React.useEffect(() => {\n if (!isEditing) return\n\n inputRef.current?.focus()\n inputRef.current?.select()\n }, [isEditing])\n\n const applyPageDraft = React.useCallback(\n (value: string) => {\n const trimmedValue = value.trim()\n\n if (!trimmedValue) return\n\n const parsedPage = Number(trimmedValue)\n\n if (!Number.isInteger(parsedPage)) return\n\n onPageChange(Math.min(Math.max(parsedPage, 1), Math.max(numPages, 1)))\n },\n [numPages, onPageChange]\n )\n\n return (\n <div className="flex items-center text-sm whitespace-nowrap text-primary">\n <span>Page</span>\n {isEditing ? (\n <Input\n ref={inputRef}\n aria-label="Page number"\n inputMode="numeric"\n pattern="[0-9]*"\n size="sm"\n value={draftPage}\n className="mx-1 w-14 min-w-14 rounded-md [&_[data-slot=input]]:text-center"\n onBlur={() => setIsEditing(false)}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) => {\n const nextValue = event.target.value\n\n setDraftPage(nextValue)\n applyPageDraft(nextValue)\n }}\n onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key === "Enter" || event.key === "Escape") {\n event.currentTarget.blur()\n }\n }}\n />\n ) : (\n <Button\n type="button"\n variant="ghost"\n size="sm"\n className="font-normal"\n aria-label={`Current page ${displayPage}. Edit page number`}\n disabled={disabled || !numPages}\n onClick={() => {\n setDraftPage(String(displayPage))\n setIsEditing(true)\n }}\n >\n {displayPage}\n </Button>\n )}\n <span>of {numPages || "–"}</span>\n </div>\n )\n}\n\nfunction PdfEditorZoomControl({\n documentId,\n disabled,\n}: {\n documentId: string\n disabled: boolean\n}) {\n const { state, provides: zoom } = useZoom(documentId)\n const current = state.currentZoomLevel\n const selectValue = isZoomMode(state.zoomLevel)\n ? state.zoomLevel\n : String(Number(current.toFixed(2)))\n const presets = ZOOM_PRESETS.includes(Number(current.toFixed(2)))\n ? ZOOM_PRESETS\n : [...ZOOM_PRESETS, Number(current.toFixed(2))].sort((a, b) => a - b)\n\n return (\n <div className="flex items-center gap-0.5">\n <PdfEditorToolButton\n label="Zoom out"\n shortcut="mod+-"\n disabled={disabled || current <= MIN_ZOOM}\n onClick={() => zoom?.zoomOut()}\n >\n <ZoomOutGlyph className="size-4" />\n </PdfEditorToolButton>\n <Select\n value={selectValue}\n disabled={disabled}\n modal={false}\n onValueChange={(value) => {\n const next = String(value)\n zoom?.requestZoom(isZoomMode(next) ? next : Number(next))\n }}\n >\n <SelectTrigger\n size="sm"\n className="w-[104px] min-w-[104px]"\n aria-label="Zoom level"\n >\n <SelectValue placeholder="Zoom">\n {Math.round(current * 100)}%\n </SelectValue>\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {(Object.keys(ZOOM_MODE_LABELS) as ZoomMode[]).map((mode) => (\n <SelectItem key={mode} value={mode}>\n {ZOOM_MODE_LABELS[mode]}\n </SelectItem>\n ))}\n {presets.map((preset) => (\n <SelectItem key={preset} value={String(preset)}>\n {Math.round(preset * 100)}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <PdfEditorToolButton\n label="Zoom in"\n shortcut="mod+="\n disabled={disabled || current >= MAX_ZOOM}\n onClick={() => zoom?.zoomIn()}\n >\n <ZoomInGlyph className="size-4" />\n </PdfEditorToolButton>\n </div>\n )\n}\n\nfunction PdfEditorSearchControl({\n documentId,\n disabled,\n open,\n onOpenChange,\n}: {\n documentId: string\n disabled: boolean\n open: boolean\n onOpenChange: (open: boolean) => void\n}) {\n const { state, provides } = useSearch(documentId)\n const { provides: scroll } = useScroll(documentId)\n const [draft, setDraft] = React.useState("")\n const [query, setQuery] = React.useState("")\n const [isSearching, setIsSearching] = React.useState(false)\n const providesRef = React.useRef(provides)\n const scrollRef = React.useRef(scroll)\n const requestIdRef = React.useRef(0)\n const inputRef = React.useRef<HTMLInputElement>(null)\n\n React.useEffect(() => {\n providesRef.current = provides\n scrollRef.current = scroll\n }, [provides, scroll])\n\n React.useEffect(() => {\n if (!open) return\n\n const frame = window.requestAnimationFrame(() => inputRef.current?.focus())\n\n return () => window.cancelAnimationFrame(frame)\n }, [open])\n\n const scrollToResult = React.useCallback(\n (index: number) => {\n const result = state.results[index]\n if (!result || !scroll) return\n\n const firstRect = result.rects[0]\n\n scroll.scrollToPage({\n pageNumber: result.pageIndex + 1,\n ...(firstRect\n ? {\n pageCoordinates: { x: firstRect.origin.x, y: firstRect.origin.y },\n alignY: 30,\n }\n : {}),\n behavior: "auto",\n })\n },\n [scroll, state.results]\n )\n\n const runSearch = React.useCallback((rawQuery: string) => {\n const nextQuery = rawQuery.trim()\n const requestId = requestIdRef.current + 1\n requestIdRef.current = requestId\n setQuery(nextQuery)\n\n const searchProvider = providesRef.current\n const scrollProvider = scrollRef.current\n\n if (!searchProvider) {\n setIsSearching(false)\n return\n }\n\n if (!nextQuery) {\n searchProvider.stopSearch()\n setIsSearching(false)\n return\n }\n\n setIsSearching(true)\n searchProvider.startSearch()\n searchProvider.searchAllPages(nextQuery).wait(\n (result) => {\n if (requestIdRef.current !== requestId) return\n\n const first = result.results[0]\n\n if (first && scrollProvider) {\n searchProvider.goToResult(0)\n const firstRect = first.rects[0]\n\n scrollProvider.scrollToPage({\n pageNumber: first.pageIndex + 1,\n ...(firstRect\n ? {\n pageCoordinates: {\n x: firstRect.origin.x,\n y: firstRect.origin.y,\n },\n alignY: 30,\n }\n : {}),\n behavior: "auto",\n })\n }\n\n setIsSearching(false)\n },\n () => {\n if (requestIdRef.current === requestId) setIsSearching(false)\n }\n )\n }, [])\n\n React.useEffect(() => {\n if (!draft.trim()) return\n\n const timeout = window.setTimeout(\n () => runSearch(draft),\n SEARCH_DEBOUNCE_MS\n )\n\n return () => window.clearTimeout(timeout)\n }, [draft, runSearch])\n\n const clear = () => {\n requestIdRef.current += 1\n setDraft("")\n setQuery("")\n setIsSearching(false)\n provides?.stopSearch()\n }\n\n const navigate = (direction: 1 | -1) => {\n if (!provides || state.total === 0) return\n\n scrollToResult(\n direction === 1 ? provides.nextResult() : provides.previousResult()\n )\n }\n\n const resultLabel = isSearching\n ? "Searching…"\n : !query\n ? "Type to search"\n : state.total\n ? `${state.activeResultIndex + 1} / ${state.total}`\n : "No results"\n\n return (\n <Popover open={open} onOpenChange={onOpenChange}>\n <PdfEditorTooltip label="Search" shortcut="mod+F">\n <PopoverTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search"\n disabled={disabled}\n className={cn(query && "text-primary")}\n >\n <SearchGlyph className="size-4" />\n </Button>\n </PopoverTrigger>\n </PdfEditorTooltip>\n <PopoverContent align="end" className="w-72 p-3">\n <div className="space-y-3">\n <Input\n ref={inputRef}\n placeholder="Search text"\n value={draft}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) => {\n const next = event.target.value\n setDraft(next)\n\n if (next.trim()) {\n setIsSearching(true)\n } else {\n clear()\n }\n }}\n onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key !== "Enter") return\n\n event.preventDefault()\n\n if (state.total) {\n navigate(event.shiftKey ? -1 : 1)\n } else if (draft.trim()) {\n runSearch(draft)\n }\n }}\n />\n <div className="flex items-center justify-between gap-2">\n <div className="min-w-0 truncate text-xs text-muted-foreground">\n {resultLabel}\n </div>\n <div className="flex shrink-0 items-center gap-1">\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Previous result"\n disabled={isSearching || state.total === 0}\n onClick={() => navigate(-1)}\n >\n <ChevronLeftGlyph className="size-4" />\n </Button>\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Next result"\n disabled={isSearching || state.total === 0}\n onClick={() => navigate(1)}\n >\n <ChevronRightGlyph className="size-4" />\n </Button>\n <Button type="button" variant="outline" size="sm" onClick={clear}>\n Clear\n </Button>\n </div>\n </div>\n </div>\n </PopoverContent>\n </Popover>\n )\n}\n\nfunction PdfEditorModeSwitch({\n mode,\n features,\n compact = false,\n onModeChange,\n}: {\n mode: PdfEditorMode\n features: PdfEditorResolvedFeatures\n compact?: boolean\n onModeChange: (mode: PdfEditorMode) => void\n}) {\n const options = PDF_EDITOR_MODE_OPTIONS.filter(\n (option) => option.feature === null || features[option.feature]\n )\n\n return (\n <div\n role="group"\n aria-label="Editor mode"\n className="flex shrink-0 items-center gap-0.5 rounded-lg bg-muted p-0.5"\n >\n {options.map((option) => {\n const Glyph = option.glyph\n const active = option.id === mode\n\n return (\n <Button\n key={option.id}\n type="button"\n size={compact ? "icon-xs" : "xs"}\n variant={active ? "default" : "ghost"}\n aria-pressed={active}\n aria-label={option.label}\n className={cn("gap-1.5", !active && "text-muted-foreground")}\n onClick={() => onModeChange(option.id)}\n >\n <Glyph className="size-3.5" />\n {compact ? null : (\n <span className="hidden md:inline">{option.label}</span>\n )}\n </Button>\n )\n })}\n </div>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Side panel shells */\n/* -------------------------------------------------------------------------- */\n\nfunction PanelTabStrip<T extends string>({\n tabs,\n value,\n onChange,\n onClose,\n label,\n}: {\n tabs: Array<{ id: T; label: string; glyph: PdfEditorGlyph }>\n value: T | null\n onChange: (value: T) => void\n onClose: () => void\n label: string\n}) {\n return (\n <div className="flex shrink-0 items-center justify-between gap-1 border-b px-1.5 py-1">\n <TooltipProvider delay={TOOLTIP_DELAY_MS}>\n <div\n className="flex min-w-0 items-center gap-0.5 overflow-x-auto"\n role="tablist"\n aria-label={label}\n >\n {tabs.map((tab) => {\n const Glyph = tab.glyph\n\n return (\n <PdfEditorToolButton\n key={tab.id}\n label={tab.label}\n active={value === tab.id}\n role="tab"\n aria-selected={value === tab.id}\n onClick={() => onChange(tab.id)}\n >\n <Glyph className="size-4" />\n </PdfEditorToolButton>\n )\n })}\n </div>\n <PdfEditorToolButton\n label="Close panel"\n size="icon-xs"\n onClick={onClose}\n >\n <CloseGlyph className="size-3.5" />\n </PdfEditorToolButton>\n </TooltipProvider>\n </div>\n )\n}\n\nfunction PdfEditorRightPanelShell({\n open,\n inline,\n children,\n}: {\n open: boolean\n inline: boolean\n children: React.ReactNode\n}) {\n return (\n <aside\n data-slot="pdf-editor-right-panel"\n data-panel-open={open ? "true" : "false"}\n className={cn(\n "absolute inset-y-0 right-0 z-30 flex shrink-0 flex-col overflow-hidden border-l bg-sidebar shadow-lg transition-[translate,margin-right] duration-200 ease-out",\n RIGHT_PANEL_WIDTH_CLASS,\n inline && "relative z-auto translate-x-0 shadow-none",\n open\n ? "mr-0 translate-x-0"\n : inline\n ? "-mr-84 border-l-0"\n : "pointer-events-none translate-x-full border-l-0"\n )}\n >\n {children}\n </aside>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Signature persistence + engine warm-up utilities */\n/* -------------------------------------------------------------------------- */\n\nfunction PdfEditorSignaturePersistence({\n storageKey,\n}: {\n storageKey: string | null\n}) {\n const { provides: signatureCapability } = useSignatureCapability()\n\n React.useEffect(() => {\n if (!signatureCapability || !storageKey) return\n\n try {\n const raw = window.localStorage.getItem(storageKey)\n\n if (raw && signatureCapability.getEntries().length === 0) {\n signatureCapability.loadEntries(deserializeEntries(JSON.parse(raw)))\n }\n } catch {\n // Ignore corrupt or unavailable storage.\n }\n\n return signatureCapability.onEntriesChange((entries) => {\n try {\n window.localStorage.setItem(\n storageKey,\n JSON.stringify(serializeEntries(entries))\n )\n } catch {\n // Storage may be unavailable (private mode, quota).\n }\n })\n }, [signatureCapability, storageKey])\n\n return null\n}\n\n/* -------------------------------------------------------------------------- */\n/* Fallback shell (engine loading, document loading, errors, empty) */\n/* -------------------------------------------------------------------------- */\n\nfunction PdfEditorFallbackShell({\n className,\n fileName,\n showToolbar,\n showUpload,\n state,\n errorMessage = "The PDF could not be loaded.",\n onUploadFile,\n children,\n}: {\n className?: string\n fileName?: string\n showToolbar: boolean\n showUpload: boolean\n state: "loading" | "error" | "empty" | "password"\n errorMessage?: string\n onUploadFile?: (file: File) => void\n children?: React.ReactNode\n}) {\n const inputRef = React.useRef<HTMLInputElement>(null)\n\n return (\n <div\n data-slot="pdf-editor"\n data-state={state}\n className={cn(\n "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n {showToolbar ? (\n <div className="flex min-h-12 items-center justify-between gap-2 border-b px-3 py-2">\n <div className="flex min-w-0 items-center gap-2 text-sm">\n <FileTextGlyph className="size-4 shrink-0 text-muted-foreground" />\n <span className="truncate text-muted-foreground">\n {fileName ?? "PDF editor"}\n </span>\n </div>\n {showUpload && onUploadFile ? (\n <>\n <input\n ref={inputRef}\n type="file"\n accept="application/pdf,.pdf"\n className="sr-only"\n tabIndex={-1}\n onChange={(event) => {\n const file = event.target.files?.[0]\n if (file) onUploadFile(file)\n event.currentTarget.value = ""\n }}\n />\n <Button\n type="button"\n size="sm"\n variant="outline"\n onClick={() => inputRef.current?.click()}\n >\n <UploadGlyph className="size-4" />\n Open PDF\n </Button>\n </>\n ) : null}\n </div>\n ) : null}\n <div className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30">\n {children ? (\n children\n ) : state === "loading" ? (\n <div className="grid flex-1 place-items-center">\n <Spinner className="size-4" />\n </div>\n ) : state === "error" ? (\n <div className="grid flex-1 place-items-center p-6 text-center text-sm text-muted-foreground">\n {errorMessage}\n </div>\n ) : (\n <div className="grid flex-1 place-items-center p-6 text-center text-sm text-muted-foreground">\n <div className="max-w-sm space-y-3">\n <div className="font-medium text-foreground">\n Open a PDF to start editing\n </div>\n <div>\n Pass a URL or file with the <code>src</code> prop, or use the\n upload control.\n </div>\n </div>\n </div>\n )}\n </div>\n </div>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Editor (per loaded document) */\n/* -------------------------------------------------------------------------- */\n\ntype EditorHandleImpl = PDFEditorHandle\n\ntype PdfEditorInnerProps = {\n documentId: string\n document: PdfDocumentObject | null\n fileName: string\n className?: string\n defaultZoom: PDFEditorZoomLevel\n defaultMode: PdfEditorMode\n leftPanel: PdfEditorLeftPanel | null\n setLeftPanel: React.Dispatch<React.SetStateAction<PdfEditorLeftPanel | null>>\n formDesignMode: boolean\n setFormDesignMode: React.Dispatch<React.SetStateAction<boolean>>\n annotationAuthor: string\n features: PdfEditorResolvedFeatures\n showToolbar: boolean\n showUpload: boolean\n showDownload: boolean\n toolbarActions?: React.ReactNode\n selectionActions: PdfEditorSelectionAction[]\n signatureFontsStylesheetUrl: string | null\n renderPageOverlay?: (props: PDFEditorPageOverlayProps) => React.ReactNode\n handleRef: React.MutableRefObject<EditorHandleImpl | null>\n onReplaceDocument: (buffer: ArrayBuffer, fileName: string) => void\n onUploadFile: (file: File) => void\n onActivePageChange?: (pageNumber: number) => void\n onModeChange?: (mode: PdfEditorMode) => void\n onAnnotationEvent?: (event: AnnotationEvent) => void\n onAnnotationsChange?: (items: AnnotationTransferItem[]) => void\n onFormValuesChange?: (values: Record<string, string>) => void\n onRedactionsApplied?: () => void\n onSave?: (result: { buffer: ArrayBuffer; fileName: string }) => void\n onCapture?: (event: CaptureAreaEvent) => void\n onToast?: (toast: PDFEditorToast) => void\n onSelectionAction?: (\n actionId: string,\n payload: PdfEditorSelectionPayload\n ) => void\n}\n\nconst LEFT_PANEL_TABS: Array<{\n id: PdfEditorLeftPanel\n label: string\n glyph: PdfEditorGlyph\n feature: keyof PdfEditorFeatureFlags | null\n}> = [\n { id: "thumbnails", label: "Thumbnails", glyph: GridGlyph, feature: null },\n { id: "outline", label: "Outline", glyph: ListTreeGlyph, feature: "outline" },\n {\n id: "attachments",\n label: "Attachments",\n glyph: PaperclipGlyph,\n feature: "attachments",\n },\n {\n id: "pages",\n label: "Organize pages",\n glyph: LayersGlyph,\n feature: "pages",\n },\n]\n\nconst RIGHT_PANEL_TABS: Array<{\n id: PdfEditorRightPanel\n label: string\n glyph: PdfEditorGlyph\n feature: keyof PdfEditorFeatureFlags | null\n}> = [\n { id: "properties", label: "Properties", glyph: SlidersGlyph, feature: null },\n {\n id: "comments",\n label: "Comments",\n glyph: CommentsGlyph,\n feature: "comments",\n },\n {\n id: "redactions",\n label: "Redactions",\n glyph: EyeOffGlyph,\n feature: "redact",\n },\n { id: "stamps", label: "Stamps", glyph: StampGlyph, feature: "stamps" },\n {\n id: "signatures",\n label: "Signatures",\n glyph: SignatureGlyph,\n feature: "sign",\n },\n {\n id: "forms",\n label: "Form fields",\n glyph: TextFieldGlyph,\n feature: "forms",\n },\n]\n\nfunction PdfEditorInner({\n documentId,\n document: pdfDocument,\n fileName,\n className,\n defaultZoom,\n defaultMode,\n leftPanel,\n setLeftPanel,\n formDesignMode,\n setFormDesignMode,\n annotationAuthor,\n features,\n showToolbar,\n showUpload,\n showDownload,\n toolbarActions,\n selectionActions,\n signatureFontsStylesheetUrl,\n renderPageOverlay,\n handleRef,\n onReplaceDocument,\n onUploadFile,\n onActivePageChange,\n onModeChange,\n onAnnotationEvent,\n onAnnotationsChange,\n onFormValuesChange,\n onRedactionsApplied,\n onSave,\n onCapture,\n onToast,\n onSelectionAction,\n}: PdfEditorInnerProps) {\n const { registry } = useRegistry()\n const permissions = useDocumentPermissions(documentId)\n const { state: scrollState, provides: scroll } = useScroll(documentId)\n const { provides: scrollCapability } = useScrollCapability()\n const { state: zoomState, provides: zoom } = useZoom(documentId)\n const { provides: rotate } = useRotate(documentId)\n const { spreadMode, provides: spread } = useSpread(documentId)\n const { provides: pan, isPanning } = usePan(documentId)\n const { state: captureState, provides: capture } = useCapture(documentId)\n const { provides: fullscreen, state: fullscreenState } = useFullscreen()\n const { provides: historyCapability } = useHistoryCapability()\n const { provides: annotationCapability } = useAnnotationCapability()\n const { state: annotationState, provides: annotation } =\n useAnnotation(documentId)\n const { state: redactionState, provides: redaction } =\n useRedaction(documentId)\n const { provides: exportScope } = useExport(documentId)\n const { provides: print } = usePrint(documentId)\n const { provides: formCapability } = useFormCapability()\n const { provides: selectionCapability } = useSelectionCapability()\n\n const [mode, setModeState] = React.useState<PdfEditorMode>(defaultMode)\n const [rightPanel, setRightPanel] =\n React.useState<PdfEditorRightPanel | null>(null)\n const [dialog, setDialog] = React.useState<PdfEditorDialogRequest | null>(\n null\n )\n const [searchOpen, setSearchOpen] = React.useState(false)\n const [historyState, setHistoryState] = React.useState({\n canUndo: false,\n canRedo: false,\n })\n const [horizontalScroll, setHorizontalScroll] = React.useState(false)\n const [isDownloading, setIsDownloading] = React.useState(false)\n\n const rootRef = React.useRef<HTMLDivElement | null>(null)\n const [toastContainer, setToastContainer] =\n React.useState<HTMLDivElement | null>(null)\n const [editorToastManager] = React.useState(() =>\n ToastPrimitive.createToastManager()\n )\n const viewportElementRef = React.useRef<HTMLDivElement | null>(null)\n const uploadInputRef = React.useRef<HTMLInputElement>(null)\n const annotationImportInputRef = React.useRef<HTMLInputElement>(null)\n const [shellRef, shellWidth] = useElementWidth<HTMLDivElement>()\n const leftInline = useInlineThumbnailSidebar(shellWidth)\n const rightInline = shellWidth >= RIGHT_PANEL_INLINE_MIN_WIDTH\n const compactToolbar = shellWidth > 0 && shellWidth <= TOOLBAR_STACK_MAX_WIDTH\n\n const activePage = scrollState.currentPage\n const numPages = pdfDocument?.pageCount ?? 0\n const isLoading = !pdfDocument\n const controlsDisabled = !numPages\n const currentZoom = zoomState.currentZoomLevel\n const selectedAnnotations = React.useMemo(\n () => getSelectedAnnotations(annotationState),\n [annotationState]\n )\n const activeToolId = annotationState.activeToolId\n const activeTool = React.useMemo(\n () =>\n activeToolId && annotationCapability\n ? annotationCapability.getTool(activeToolId)\n : null,\n [activeToolId, annotationCapability]\n )\n const historyScope = React.useMemo(\n () => historyCapability?.forDocument(documentId) ?? null,\n [documentId, historyCapability]\n )\n const formScope = React.useMemo(\n () => formCapability?.forDocument(documentId) ?? null,\n [documentId, formCapability]\n )\n const selectionScope = React.useMemo(\n () => selectionCapability?.forDocument(documentId) ?? null,\n [documentId, selectionCapability]\n )\n\n /* ---- notices ---------------------------------------------------------- */\n\n const notify = React.useCallback(\n (message: string, tone: PdfEditorNoticeTone = "info") => {\n if (onToast) {\n onToast({ message, tone })\n return\n }\n\n editorToastManager.add({ title: message, type: tone })\n },\n [editorToastManager, onToast]\n )\n\n const setRootElement = React.useCallback((element: HTMLDivElement | null) => {\n rootRef.current = element\n setToastContainer(element)\n }, [])\n\n /* ---- tool helpers ----------------------------------------------------- */\n\n const deactivateTools = React.useCallback(() => {\n annotation?.setActiveTool(null)\n if (redactionState.isRedacting) redaction?.endRedact()\n if (isPanning) pan?.disablePan()\n if (captureState.isMarqueeCaptureActive) capture?.disableMarqueeCapture()\n if (zoomState.isMarqueeZoomActive) zoom?.disableMarqueeZoom()\n }, [\n annotation,\n capture,\n captureState.isMarqueeCaptureActive,\n isPanning,\n pan,\n redaction,\n redactionState.isRedacting,\n zoom,\n zoomState.isMarqueeZoomActive,\n ])\n\n const setActiveTool = React.useCallback(\n (toolId: string | null) => {\n if (!annotation) return\n\n if (isPanning) pan?.disablePan()\n if (captureState.isMarqueeCaptureActive) capture?.disableMarqueeCapture()\n if (zoomState.isMarqueeZoomActive) zoom?.disableMarqueeZoom()\n if (redactionState.isRedacting) redaction?.endRedact()\n\n annotation.setActiveTool(\n toolId !== null && annotationState.activeToolId === toolId\n ? null\n : toolId\n )\n },\n [\n annotation,\n annotationState.activeToolId,\n capture,\n captureState.isMarqueeCaptureActive,\n isPanning,\n pan,\n redaction,\n redactionState.isRedacting,\n zoom,\n zoomState.isMarqueeZoomActive,\n ]\n )\n\n const setMode = React.useCallback(\n (nextMode: PdfEditorMode) => {\n setModeState((previous) => {\n if (previous === nextMode) return previous\n\n onModeChange?.(nextMode)\n return nextMode\n })\n\n const defaultPanel: Record<PdfEditorMode, PdfEditorRightPanel | null> = {\n view: null,\n annotate: "properties",\n sign: "signatures",\n forms: "forms",\n redact: "redactions",\n }\n const panel = defaultPanel[nextMode]\n\n if (panel) setRightPanel(panel)\n else setRightPanel(null)\n },\n [onModeChange]\n )\n\n React.useEffect(() => {\n deactivateTools()\n annotation?.deselectAnnotation()\n // Only react to mode changes here; tool state is otherwise managed by the toolbar.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [mode])\n\n React.useEffect(() => {\n annotation?.setLocked(\n mode === "forms" && formDesignMode\n ? { type: LockModeType.None }\n : { type: LockModeType.Include, categories: ["form"] }\n )\n }, [annotation, formDesignMode, mode])\n\n React.useEffect(() => {\n if (mode !== "forms" && formDesignMode) setFormDesignMode(false)\n }, [formDesignMode, mode, setFormDesignMode])\n\n /* ---- history ---------------------------------------------------------- */\n\n React.useEffect(() => {\n if (!historyScope) return\n\n const sync = () => {\n const state = historyScope.getHistoryState()\n setHistoryState({\n canUndo: state.global.canUndo,\n canRedo: state.global.canRedo,\n })\n }\n\n sync()\n return historyScope.onHistoryChange(sync)\n }, [historyScope])\n\n /* ---- callbacks: page, annotations, forms, redactions ------------------ */\n\n React.useEffect(() => {\n if (activePage > 0) onActivePageChange?.(activePage)\n }, [activePage, onActivePageChange])\n\n const onAnnotationEventRef = React.useRef(onAnnotationEvent)\n const onAnnotationsChangeRef = React.useRef(onAnnotationsChange)\n const onFormValuesChangeRef = React.useRef(onFormValuesChange)\n const onRedactionsAppliedRef = React.useRef(onRedactionsApplied)\n\n React.useEffect(() => {\n onAnnotationEventRef.current = onAnnotationEvent\n onAnnotationsChangeRef.current = onAnnotationsChange\n onFormValuesChangeRef.current = onFormValuesChange\n onRedactionsAppliedRef.current = onRedactionsApplied\n })\n\n React.useEffect(() => {\n if (!annotation) return\n\n let timeout: number | null = null\n\n const unsubscribe = annotation.onAnnotationEvent((event) => {\n onAnnotationEventRef.current?.(event)\n\n if (!onAnnotationsChangeRef.current) return\n if (event.type === "loaded" || !event.committed) return\n\n if (timeout !== null) window.clearTimeout(timeout)\n\n timeout = window.setTimeout(() => {\n timeout = null\n annotation.exportAnnotations().wait((items) => {\n onAnnotationsChangeRef.current?.(items)\n }, noop)\n }, 400)\n })\n\n return () => {\n if (timeout !== null) window.clearTimeout(timeout)\n unsubscribe()\n }\n }, [annotation])\n\n React.useEffect(() => {\n if (!formScope) return\n\n return formScope.onFieldValueChange(() => {\n onFormValuesChangeRef.current?.(formScope.getFormValues())\n })\n }, [formScope])\n\n React.useEffect(() => {\n if (!redaction) return\n\n return redaction.onRedactionEvent((event) => {\n if (event.type !== "commit") return\n\n if (event.success) {\n notify(\n "Redactions applied. The content was removed from the document.",\n "success"\n )\n onRedactionsAppliedRef.current?.()\n } else {\n notify("The redactions could not be applied.", "error")\n }\n })\n }, [notify, redaction])\n\n /* ---- initial zoom (numeric defaults never lift the viewport gate) ----- */\n\n const initialZoomDocumentRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n if (!pdfDocument || !zoom) return\n if (initialZoomDocumentRef.current === documentId) return\n\n initialZoomDocumentRef.current = documentId\n zoom.requestZoom(toZoomLevel(defaultZoom))\n }, [defaultZoom, documentId, pdfDocument, zoom])\n\n /* ---- document actions ------------------------------------------------- */\n\n const scrollToPage = React.useCallback(\n (\n pageNumber: number,\n options?: { smooth?: boolean } | ScrollIntoViewOptions\n ) => {\n const smooth =\n options && "smooth" in options\n ? options.smooth\n : options && "behavior" in options\n ? options.behavior === "smooth"\n : false\n\n scroll?.scrollToPage({ pageNumber, behavior: smooth ? "smooth" : "auto" })\n },\n [scroll]\n )\n\n const scrollToAnnotation = React.useCallback(\n (target: PdfAnnotationObject) => {\n scroll?.scrollToPage({\n pageNumber: target.pageIndex + 1,\n pageCoordinates: { x: target.rect.origin.x, y: target.rect.origin.y },\n alignX: 50,\n alignY: 25,\n behavior: "smooth",\n })\n },\n [scroll]\n )\n\n const getDocumentBuffer = React.useCallback(async () => {\n if (!exportScope) throw new Error("The document is not ready.")\n\n if (annotation && annotationState.hasPendingChanges) {\n try {\n await annotation.commit().toPromise()\n } catch {\n // Continue with whatever the engine currently holds.\n }\n }\n\n return exportScope.saveAsCopy().toPromise()\n }, [annotation, annotationState.hasPendingChanges, exportScope])\n\n const downloadDocument = React.useCallback(\n async (name?: string) => {\n const targetName = getPdfFileName(name ?? fileName)\n\n setIsDownloading(true)\n\n try {\n const buffer = await getDocumentBuffer()\n downloadArrayBuffer(buffer, targetName)\n onSave?.({ buffer, fileName: targetName })\n } catch (error) {\n console.error(error)\n notify("The document could not be saved.", "error")\n } finally {\n setIsDownloading(false)\n }\n },\n [fileName, getDocumentBuffer, notify, onSave]\n )\n\n const flattenDocument = React.useCallback(() => {\n setDialog({\n type: "confirm",\n title: "Flatten annotations and form fields?",\n description:\n "Annotations and filled form fields become part of the page content and can no longer be edited.",\n confirmLabel: "Flatten",\n destructive: true,\n onConfirm: async () => {\n if (!registry || !pdfDocument) return\n\n try {\n if (annotation && annotationState.hasPendingChanges) {\n await annotation.commit().toPromise()\n }\n\n const engine = registry.getEngine()\n\n for (const page of pdfDocument.pages) {\n await engine\n .flattenPage(pdfDocument, page, {\n flag: PdfPageFlattenFlag.Display,\n })\n .toPromise()\n }\n\n const buffer = await engine.saveAsCopy(pdfDocument).toPromise()\n onReplaceDocument(buffer, fileName)\n notify("Annotations flattened into the page content.", "success")\n } catch (error) {\n console.error(error)\n notify("The document could not be flattened.", "error")\n }\n },\n })\n }, [\n annotation,\n annotationState.hasPendingChanges,\n fileName,\n notify,\n onReplaceDocument,\n pdfDocument,\n registry,\n ])\n\n const exportAnnotationsJson = React.useCallback(() => {\n if (!annotation) return\n\n annotation.exportAnnotations().wait(\n (items) => {\n downloadBlob(\n new Blob([JSON.stringify(serializeAnnotationItems(items), null, 2)], {\n type: "application/json",\n }),\n `${fileName.replace(/\\.pdf$/i, "")}-annotations.json`\n )\n notify(\n `Exported ${items.length} annotation${items.length === 1 ? "" : "s"}.`,\n "success"\n )\n },\n () => notify("The annotations could not be exported.", "error")\n )\n }, [annotation, fileName, notify])\n\n const importAnnotationsFile = React.useCallback(\n async (file: File) => {\n if (!annotation) return\n\n try {\n const items = deserializeAnnotationItems(JSON.parse(await file.text()))\n annotation.importAnnotations(items)\n notify(\n `Imported ${items.length} annotation${items.length === 1 ? "" : "s"}.`,\n "success"\n )\n } catch {\n notify("The file is not a valid annotation export.", "error")\n }\n },\n [annotation, notify]\n )\n\n const deleteSelectedAnnotations = React.useCallback(() => {\n if (!annotation || selectedAnnotations.length === 0) return\n\n const deletable = selectedAnnotations.filter(\n (item) => !annotation.isAnnotationStructurallyLocked(item.object)\n )\n\n if (deletable.length === 0) return\n\n annotation.deleteAnnotations(\n deletable.map((item) => ({\n pageIndex: item.object.pageIndex,\n id: item.object.id,\n }))\n )\n }, [annotation, selectedAnnotations])\n\n const applyAllRedactions = React.useCallback(() => {\n if (!redaction || redactionState.pendingCount === 0) return\n\n setDialog({\n type: "confirm",\n title: `Apply ${redactionState.pendingCount} redaction${redactionState.pendingCount === 1 ? "" : "s"}?`,\n description:\n "Redaction permanently removes the marked content from the document. This cannot be undone.",\n confirmLabel: "Apply redactions",\n onConfirm: () => {\n redaction.commitAllPending().wait(noop, noop)\n },\n })\n }, [redaction, redactionState.pendingCount])\n\n /* ---- imperative handle ------------------------------------------------ */\n\n React.useEffect(() => {\n handleRef.current = {\n getDocumentBuffer,\n download: downloadDocument,\n print: async (options) => {\n if (!print) throw new Error("Printing is not available.")\n await print.print(options).toPromise()\n },\n exportAnnotations: async () => {\n if (!annotation) return []\n return annotation.exportAnnotations().toPromise()\n },\n importAnnotations: (items) => annotation?.importAnnotations(items),\n getFormValues: () => formScope?.getFormValues() ?? {},\n setFormValues: async (values) => {\n if (!formScope) return\n await formScope.setFormValues(values).toPromise()\n },\n applyRedactions: async () => {\n if (!redaction) return\n await redaction.commitAllPending().toPromise()\n },\n setMode,\n setActiveTool: (toolId) => annotation?.setActiveTool(toolId),\n scrollToPage: (pageNumber, options) => scrollToPage(pageNumber, options),\n undo: () => historyScope?.undo(),\n redo: () => historyScope?.redo(),\n getViewportElement: () => viewportElementRef.current,\n }\n\n return () => {\n handleRef.current = null\n }\n }, [\n annotation,\n downloadDocument,\n formScope,\n getDocumentBuffer,\n handleRef,\n historyScope,\n print,\n redaction,\n scrollToPage,\n setMode,\n ])\n\n /* ---- keyboard shortcuts ----------------------------------------------- */\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLDivElement>) => {\n const key = event.key\n const mod = event.metaKey || event.ctrlKey\n\n if (isTypingTarget(event.target)) {\n if (key === "Escape") (event.target as HTMLElement).blur()\n return\n }\n\n if (key === "Escape") {\n deactivateTools()\n annotation?.deselectAnnotation()\n selectionScope?.clear()\n setSearchOpen(false)\n event.preventDefault()\n return\n }\n\n if (\n (key === "Delete" || key === "Backspace") &&\n selectedAnnotations.length > 0\n ) {\n deleteSelectedAnnotations()\n event.preventDefault()\n return\n }\n\n if (mod && key.toLowerCase() === "z") {\n if (event.shiftKey) historyScope?.redo()\n else historyScope?.undo()\n event.preventDefault()\n return\n }\n\n if (mod && key.toLowerCase() === "y") {\n historyScope?.redo()\n event.preventDefault()\n return\n }\n\n if (mod && (key === "=" || key === "+")) {\n zoom?.zoomIn()\n event.preventDefault()\n return\n }\n\n if (mod && key === "-") {\n zoom?.zoomOut()\n event.preventDefault()\n return\n }\n\n if (mod && key === "0") {\n zoom?.requestZoom(ZoomMode.FitPage)\n event.preventDefault()\n return\n }\n\n if (mod && key.toLowerCase() === "p" && features.print) {\n setDialog({ type: "print" })\n event.preventDefault()\n return\n }\n\n if (mod && key.toLowerCase() === "s" && showDownload) {\n void downloadDocument()\n event.preventDefault()\n return\n }\n\n if (mod && key.toLowerCase() === "f") {\n setSearchOpen(true)\n event.preventDefault()\n return\n }\n\n if (mod && key.toLowerCase() === "a" && annotation && mode !== "view") {\n const ids = annotationState.pages[Math.max(0, activePage - 1)] ?? []\n\n if (ids.length > 0) {\n annotation.setSelection(ids)\n event.preventDefault()\n }\n return\n }\n\n if (!mod && !event.altKey && key.toLowerCase() === "h") {\n pan?.togglePan()\n event.preventDefault()\n return\n }\n\n if (!mod && !event.altKey && key.toLowerCase() === "v") {\n deactivateTools()\n event.preventDefault()\n }\n },\n [\n activePage,\n annotation,\n annotationState.pages,\n deactivateTools,\n deleteSelectedAnnotations,\n downloadDocument,\n features.print,\n historyScope,\n mode,\n pan,\n selectedAnnotations.length,\n selectionScope,\n showDownload,\n zoom,\n ]\n )\n\n const handlePointerDownCapture = React.useCallback(\n (event: React.PointerEvent<HTMLDivElement>) => {\n const root = rootRef.current\n if (!root) return\n\n const active = window.document.activeElement\n\n if (active && root.contains(active) && active !== root) return\n if (!(event.target instanceof Node) || !root.contains(event.target))\n return\n if (isTypingTarget(event.target)) return\n\n root.focus({ preventScroll: true })\n },\n []\n )\n\n /* ---- context ---------------------------------------------------------- */\n\n const openDialog = React.useCallback(\n (request: PdfEditorDialogRequest) => setDialog(request),\n []\n )\n const toggleLeftPanel = React.useCallback(\n (panel: PdfEditorLeftPanel) =>\n setLeftPanel((previous) => (previous === panel ? null : panel)),\n [setLeftPanel]\n )\n const toggleRightPanel = React.useCallback(\n (panel: PdfEditorRightPanel) =>\n setRightPanel((previous) => (previous === panel ? null : panel)),\n []\n )\n\n const contextValue = React.useMemo<PdfEditorContextValue>(\n () => ({\n documentId,\n document: pdfDocument,\n fileName,\n mode,\n setMode,\n leftPanel,\n setLeftPanel,\n toggleLeftPanel,\n rightPanel,\n setRightPanel,\n toggleRightPanel,\n openDialog,\n notify,\n features,\n permissions,\n annotationAuthor,\n selectionActions,\n formDesignMode,\n setFormDesignMode,\n replaceDocument: (buffer, name) =>\n onReplaceDocument(buffer, name ?? fileName),\n downloadDocument,\n getDocumentBuffer,\n scrollToPage,\n scrollToAnnotation,\n onCapture,\n onSelectionAction,\n signatureFontsStylesheetUrl,\n }),\n [\n annotationAuthor,\n documentId,\n downloadDocument,\n features,\n fileName,\n formDesignMode,\n getDocumentBuffer,\n leftPanel,\n mode,\n notify,\n onCapture,\n onReplaceDocument,\n onSelectionAction,\n openDialog,\n pdfDocument,\n permissions,\n rightPanel,\n scrollToAnnotation,\n scrollToPage,\n selectionActions,\n setFormDesignMode,\n setLeftPanel,\n setMode,\n signatureFontsStylesheetUrl,\n toggleLeftPanel,\n toggleRightPanel,\n ]\n )\n\n /* ---- page renderer ---------------------------------------------------- */\n\n const renderPage = React.useCallback(\n (page: PageLayout) => (\n <Rotate documentId={documentId} pageIndex={page.pageIndex}>\n <PagePointerProvider\n documentId={documentId}\n pageIndex={page.pageIndex}\n data-pdf-editor-page={page.pageNumber}\n className="relative border border-transparent bg-transparent shadow-xs select-none selection:bg-transparent selection:text-inherit"\n style={{ backgroundColor: "transparent" }}\n >\n <div\n aria-hidden="true"\n className="pointer-events-none absolute inset-0 bg-white"\n />\n <RenderLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n scale={Math.min(currentZoom, PAGE_BASE_RENDER_MAX_SCALE)}\n dpr={PAGE_BASE_RENDER_DPR}\n className="pointer-events-none absolute inset-0 h-full w-full object-fill opacity-100 blur-[0.35px] transition-none"\n />\n <TilingLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n className="pointer-events-none opacity-100 transition-none [&_img]:opacity-100 [&_img]:transition-none"\n />\n <SearchLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n className="pointer-events-none"\n highlightColor="rgba(253, 224, 71, 0.45)"\n activeHighlightColor="rgba(249, 115, 22, 0.55)"\n />\n <MarqueeZoom documentId={documentId} pageIndex={page.pageIndex} />\n <MarqueeCapture documentId={documentId} pageIndex={page.pageIndex} />\n <SelectionLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n textStyle={{ background: "rgba(59, 130, 246, 0.3)" }}\n selectionMenu={(props) => (\n <PdfEditorTextSelectionMenu {...props} documentId={documentId} />\n )}\n />\n <AnnotationLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n selectionOutline={{\n color: PDF_EDITOR_SELECTION_COLOR,\n style: "solid",\n width: 1,\n offset: 2,\n }}\n groupSelectionOutline={{\n color: PDF_EDITOR_SELECTION_COLOR,\n style: "dashed",\n width: 1,\n offset: 3,\n }}\n resizeUI={{ size: 10, color: PDF_EDITOR_SELECTION_COLOR }}\n vertexUI={{ size: 10, color: PDF_EDITOR_SELECTION_COLOR }}\n rotationUI={{\n size: 18,\n color: "#ffffff",\n iconColor: PDF_EDITOR_SELECTION_COLOR,\n connectorColor: PDF_EDITOR_SELECTION_COLOR,\n showConnector: true,\n }}\n selectionMenu={(props) => (\n <PdfEditorAnnotationMenu {...props} documentId={documentId} />\n )}\n groupSelectionMenu={(props) => (\n <PdfEditorGroupMenu {...props} documentId={documentId} />\n )}\n />\n <RedactionLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n selectionMenu={(props) => (\n <PdfEditorRedactionMenu {...props} documentId={documentId} />\n )}\n />\n {renderPageOverlay?.({\n pageNumber: page.pageNumber,\n pageWidth: page.width,\n pageHeight: page.height,\n scale: currentZoom,\n rotation: 0,\n })}\n </PagePointerProvider>\n </Rotate>\n ),\n [currentZoom, documentId, renderPageOverlay]\n )\n\n /* ---- toolbar pieces --------------------------------------------------- */\n\n const activeToolColorKey = React.useMemo(() => {\n if (!activeTool) return null\n\n const defaults = activeTool.defaults as Record<string, unknown>\n\n if ("fontColor" in defaults) return "fontColor"\n if ("strokeColor" in defaults) return "strokeColor"\n if ("color" in defaults) return "color"\n return null\n }, [activeTool])\n const activeToolColor = activeToolColorKey\n ? String(\n (activeTool?.defaults as Record<string, unknown>)[activeToolColorKey] ??\n "#111827"\n )\n : null\n\n const visibleLeftTabs = LEFT_PANEL_TABS.filter(\n (tab) => tab.feature === null || features[tab.feature]\n )\n const visibleRightTabs = RIGHT_PANEL_TABS.filter(\n (tab) => tab.feature === null || features[tab.feature]\n )\n\n const canAnnotate = features.annotate && permissions.canModifyAnnotations\n const canRedact = features.redact && permissions.canModifyContents\n const canDesignForms = features.forms && permissions.canModifyAnnotations\n\n const selectToolButton = (\n <PdfEditorToolButton\n label="Select"\n shortcut="V"\n active={\n !activeToolId &&\n !isPanning &&\n !captureState.isMarqueeCaptureActive &&\n !zoomState.isMarqueeZoomActive &&\n !redactionState.isRedacting\n }\n onClick={deactivateTools}\n >\n <CursorGlyph className="size-4" />\n </PdfEditorToolButton>\n )\n\n const renderToolButton = (\n tool: { id: string; label: string; glyph: PdfEditorGlyph; hint?: string },\n disabled: boolean\n ) => {\n const Glyph = tool.glyph\n\n return (\n <PdfEditorToolButton\n key={tool.id}\n label={tool.hint ? `${tool.label} · ${tool.hint}` : tool.label}\n active={activeToolId === tool.id}\n disabled={disabled}\n onClick={() => setActiveTool(tool.id)}\n >\n <Glyph className="size-4" />\n </PdfEditorToolButton>\n )\n }\n\n let ribbon: React.ReactNode = null\n\n if (mode === "view") {\n ribbon = (\n <>\n {selectToolButton}\n <PdfEditorToolButton\n label="Hand tool"\n shortcut="H"\n active={isPanning}\n onClick={() => pan?.togglePan()}\n >\n <HandGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Zoom to area"\n active={zoomState.isMarqueeZoomActive}\n onClick={() => zoom?.toggleMarqueeZoom()}\n >\n <MarqueeZoomGlyph className="size-4" />\n </PdfEditorToolButton>\n {features.capture ? (\n <PdfEditorToolButton\n label="Capture area as image"\n active={captureState.isMarqueeCaptureActive}\n onClick={() => capture?.toggleMarqueeCapture()}\n >\n <CameraGlyph className="size-4" />\n </PdfEditorToolButton>\n ) : null}\n <PdfEditorToolbarSeparator />\n <Select\n items={SPREAD_MODE_OPTIONS}\n value={spreadMode}\n disabled={controlsDisabled}\n modal={false}\n onValueChange={(value) =>\n spread?.setSpreadMode(String(value) as SpreadMode)\n }\n >\n <SelectTrigger\n size="sm"\n className="w-[132px]"\n aria-label="Page layout"\n >\n <BookOpenGlyph className="size-4 text-muted-foreground" />\n <SelectValue placeholder="Layout" />\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {SPREAD_MODE_OPTIONS.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <Select\n items={SCROLL_DIRECTION_OPTIONS}\n value={horizontalScroll ? "horizontal" : "vertical"}\n disabled={controlsDisabled}\n modal={false}\n onValueChange={(value) => {\n const horizontal = value === "horizontal"\n setHorizontalScroll(horizontal)\n scrollCapability?.setScrollStrategy(\n horizontal ? ScrollStrategy.Horizontal : ScrollStrategy.Vertical,\n documentId\n )\n }}\n >\n <SelectTrigger\n size="sm"\n className="w-[128px]"\n aria-label="Scroll direction"\n >\n <SelectValue placeholder="Scroll" />\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {SCROLL_DIRECTION_OPTIONS.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </>\n )\n } else if (mode === "annotate") {\n ribbon = (\n <>\n {selectToolButton}\n {PDF_EDITOR_ANNOTATION_TOOL_GROUPS.map((group) => (\n <React.Fragment key={group.id}>\n <PdfEditorToolbarSeparator />\n {group.tools.map((tool) => renderToolButton(tool, !canAnnotate))}\n </React.Fragment>\n ))}\n {features.stamps ? (\n <PdfEditorToolButton\n label="Rubber stamps"\n active={rightPanel === "stamps"}\n disabled={!canAnnotate}\n onClick={() => toggleRightPanel("stamps")}\n >\n <StampGlyph className="size-4" />\n </PdfEditorToolButton>\n ) : null}\n {activeTool && activeToolColorKey && activeToolColor ? (\n <>\n <PdfEditorToolbarSeparator />\n <ColorPicker\n label={`${activeTool.name} color`}\n icon={PaletteGlyph}\n color={activeToolColor}\n onChange={(color) =>\n annotationCapability?.setToolDefaults(activeTool.id, {\n [activeToolColorKey]: color,\n })\n }\n />\n </>\n ) : null}\n <div className="ml-auto flex items-center gap-0.5">\n <PdfEditorToolButton\n label="Delete selected"\n shortcut="Delete"\n disabled={selectedAnnotations.length === 0}\n onClick={deleteSelectedAnnotations}\n >\n <TrashGlyph className="size-4" />\n </PdfEditorToolButton>\n {features.comments ? (\n <PdfEditorToolButton\n label="Comments"\n active={rightPanel === "comments"}\n onClick={() => toggleRightPanel("comments")}\n >\n <CommentsGlyph className="size-4" />\n </PdfEditorToolButton>\n ) : null}\n <PdfEditorToolButton\n label="Properties"\n active={rightPanel === "properties"}\n onClick={() => toggleRightPanel("properties")}\n >\n <SlidersGlyph className="size-4" />\n </PdfEditorToolButton>\n </div>\n </>\n )\n } else if (mode === "sign") {\n ribbon = (\n <>\n {selectToolButton}\n <PdfEditorToolbarSeparator />\n <Button\n type="button"\n size="sm"\n variant="outline"\n disabled={!canAnnotate}\n onClick={() => setDialog({ type: "signature" })}\n >\n <PlusGlyph className="size-4" />\n Create signature\n </Button>\n <PdfEditorToolButton\n label="Saved signatures"\n active={rightPanel === "signatures"}\n onClick={() => toggleRightPanel("signatures")}\n >\n <SignatureGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolbarSeparator />\n {renderToolButton(\n {\n id: "freeText",\n label: "Text box",\n glyph: TextGlyph,\n hint: "Click to add text",\n },\n !canAnnotate\n )}\n <PdfEditorToolButton\n label="Date · Click to add today\'s date"\n disabled={!canAnnotate}\n active={\n activeToolId === "freeText" &&\n Boolean(annotationState.activeToolContext?.date)\n }\n onClick={() => {\n if (!annotation) return\n\n annotationCapability?.setToolDefaults("freeText", {\n contents: new Date().toLocaleDateString(),\n })\n annotation.setActiveTool("freeText", { date: true })\n }}\n >\n <FileTextGlyph className="size-4" />\n </PdfEditorToolButton>\n {renderToolButton(\n { id: "ink", label: "Draw", glyph: EditGlyph, hint: "Sign by hand" },\n !canAnnotate\n )}\n </>\n )\n } else if (mode === "forms") {\n ribbon = (\n <>\n {selectToolButton}\n <PdfEditorToolbarSeparator />\n <div\n role="group"\n aria-label="Form mode"\n className="flex shrink-0 items-center gap-0.5 rounded-lg bg-muted p-0.5"\n >\n <Button\n type="button"\n size="xs"\n variant={formDesignMode ? "ghost" : "default"}\n aria-pressed={!formDesignMode}\n onClick={() => setFormDesignMode(false)}\n >\n Fill\n </Button>\n <Button\n type="button"\n size="xs"\n variant={formDesignMode ? "default" : "ghost"}\n aria-pressed={formDesignMode}\n disabled={!canDesignForms}\n onClick={() => setFormDesignMode(true)}\n >\n Design\n </Button>\n </div>\n {formDesignMode ? (\n <>\n <PdfEditorToolbarSeparator />\n {PDF_EDITOR_FORM_TOOLS.map((tool) =>\n renderToolButton(tool, !canDesignForms)\n )}\n </>\n ) : null}\n <div className="ml-auto flex items-center gap-0.5">\n <PdfEditorToolButton\n label="Delete selected"\n shortcut="Delete"\n disabled={selectedAnnotations.length === 0 || !formDesignMode}\n onClick={deleteSelectedAnnotations}\n >\n <TrashGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Form fields"\n active={rightPanel === "forms"}\n onClick={() => toggleRightPanel("forms")}\n >\n <TextFieldGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Properties"\n active={rightPanel === "properties"}\n onClick={() => toggleRightPanel("properties")}\n >\n <SlidersGlyph className="size-4" />\n </PdfEditorToolButton>\n </div>\n </>\n )\n } else if (mode === "redact") {\n const activeType = redactionState.activeType\n const pendingCount = redactionState.pendingCount\n\n ribbon = (\n <>\n {selectToolButton}\n <PdfEditorToolbarSeparator />\n <PdfEditorToolButton\n label="Redact · Select text or drag an area"\n active={activeType === RedactionMode.Redact}\n disabled={!canRedact}\n onClick={() => {\n deactivateTools()\n if (activeType !== RedactionMode.Redact) redaction?.enableRedact()\n }}\n >\n <EyeOffGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Mark text"\n active={activeType === RedactionMode.RedactSelection}\n disabled={!canRedact}\n onClick={() => {\n deactivateTools()\n if (activeType !== RedactionMode.RedactSelection)\n redaction?.enableRedactSelection()\n }}\n >\n <StrikethroughGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Mark area"\n active={activeType === RedactionMode.MarqueeRedact}\n disabled={!canRedact}\n onClick={() => {\n deactivateTools()\n if (activeType !== RedactionMode.MarqueeRedact)\n redaction?.enableMarqueeRedact()\n }}\n >\n <RedactAreaGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolbarSeparator />\n <Badge\n variant={pendingCount > 0 ? "secondary" : "outline"}\n className="me-1 tabular-nums"\n >\n {pendingCount} pending\n </Badge>\n <Button\n type="button"\n size="sm"\n disabled={!canRedact || pendingCount === 0}\n onClick={applyAllRedactions}\n >\n Apply all\n </Button>\n <Button\n type="button"\n size="sm"\n variant="ghost"\n disabled={pendingCount === 0}\n onClick={() => redaction?.clearPending()}\n >\n Clear\n </Button>\n <div className="ml-auto flex items-center gap-0.5">\n <PdfEditorToolButton\n label="Redactions"\n active={rightPanel === "redactions"}\n onClick={() => toggleRightPanel("redactions")}\n >\n <EyeOffGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Properties"\n active={rightPanel === "properties"}\n onClick={() => toggleRightPanel("properties")}\n >\n <SlidersGlyph className="size-4" />\n </PdfEditorToolButton>\n </div>\n </>\n )\n }\n\n let rightPanelContent: React.ReactNode = null\n\n switch (rightPanel) {\n case "properties":\n rightPanelContent = <PdfEditorPropertiesPanel documentId={documentId} />\n break\n case "comments":\n rightPanelContent = <PdfEditorCommentsPanel documentId={documentId} />\n break\n case "redactions":\n rightPanelContent = <PdfEditorRedactionsPanel documentId={documentId} />\n break\n case "stamps":\n rightPanelContent = <PdfEditorStampsPanel documentId={documentId} />\n break\n case "signatures":\n rightPanelContent = <PdfEditorSignaturesPanel documentId={documentId} />\n break\n case "forms":\n rightPanelContent = <PdfEditorFormsPanel documentId={documentId} />\n break\n default:\n rightPanelContent = null\n }\n\n let leftPanelContent: React.ReactNode = null\n\n switch (leftPanel) {\n case "thumbnails":\n leftPanelContent = (\n <PdfEditorThumbnailsPanel\n documentId={documentId}\n activePage={activePage}\n pageCount={numPages}\n onSelectPage={(pageNumber) => scrollToPage(pageNumber)}\n />\n )\n break\n case "outline":\n leftPanelContent = <PdfEditorOutlinePanel documentId={documentId} />\n break\n case "attachments":\n leftPanelContent = <PdfEditorAttachmentsPanel documentId={documentId} />\n break\n case "pages":\n leftPanelContent = (\n <PdfEditorPagesPanel documentId={documentId} activePage={activePage} />\n )\n break\n default:\n leftPanelContent = null\n }\n\n return (\n <PdfEditorContextProvider value={contextValue}>\n <ToastProvider\n limit={3}\n timeout={NOTICE_DURATION_MS}\n toastManager={editorToastManager}\n portalProps={{ container: toastContainer }}\n viewportProps={{ className: "absolute" }}\n >\n <div\n data-slot="pdf-editor"\n data-mode={mode}\n data-fullscreen={fullscreenState.isFullscreen ? "" : undefined}\n className={cn(\n "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className,\n // The fullscreen plugin auto-mounts a wrapper around the EmbedPDF\n // tree; when that wrapper is fullscreen, fill it instead of the\n // consumer-provided height.\n fullscreenState.isFullscreen && "h-full max-h-full"\n )}\n >\n <div\n ref={setRootElement}\n tabIndex={-1}\n className="relative flex h-full min-h-0 flex-1 flex-col outline-none"\n onKeyDown={handleKeyDown}\n onPointerDownCapture={handlePointerDownCapture}\n >\n <input\n ref={uploadInputRef}\n type="file"\n accept="application/pdf,.pdf"\n className="sr-only"\n tabIndex={-1}\n onChange={(event) => {\n const file = event.target.files?.[0]\n if (file) onUploadFile(file)\n event.currentTarget.value = ""\n }}\n />\n <input\n ref={annotationImportInputRef}\n type="file"\n accept="application/json,.json"\n className="sr-only"\n tabIndex={-1}\n onChange={(event) => {\n const file = event.target.files?.[0]\n if (file) void importAnnotationsFile(file)\n event.currentTarget.value = ""\n }}\n />\n\n {showToolbar ? (\n <TooltipProvider delay={TOOLTIP_DELAY_MS}>\n <div\n data-slot="pdf-editor-toolbar"\n className={cn(\n "flex min-h-12 flex-wrap items-center justify-between gap-2 border-b bg-background px-3 py-2",\n compactToolbar && "gap-0 px-0 py-0"\n )}\n >\n <div\n className={cn(\n "flex min-w-0 items-center gap-2",\n compactToolbar && "w-full px-3 py-2"\n )}\n >\n <PdfEditorToolButton\n label="Pages sidebar"\n active={leftPanel !== null}\n disabled={controlsDisabled}\n onClick={() => toggleLeftPanel("thumbnails")}\n >\n <PanelLeftGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorPageControl\n activePage={activePage}\n numPages={numPages}\n disabled={controlsDisabled}\n onPageChange={(pageNumber) => scrollToPage(pageNumber)}\n />\n </div>\n <ScrollArea\n orientation="horizontal"\n scrollFade\n scrollbarOverflowOnly\n className={cn(\n "min-w-0 flex-1",\n compactToolbar && "h-12 w-full flex-none border-t"\n )}\n viewportClassName={cn(compactToolbar && "px-3 py-2")}\n >\n <div\n className={cn(\n "flex w-max min-w-full items-center gap-1",\n compactToolbar ? "justify-start" : "justify-end"\n )}\n >\n <div className="flex items-center gap-0.5">\n <PdfEditorToolButton\n label="Undo"\n shortcut="mod+Z"\n disabled={!historyState.canUndo}\n onClick={() => historyScope?.undo()}\n >\n <UndoGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Redo"\n shortcut="mod+shift+Z"\n disabled={!historyState.canRedo}\n onClick={() => historyScope?.redo()}\n >\n <RedoGlyph className="size-4" />\n </PdfEditorToolButton>\n </div>\n <PdfEditorToolbarSeparator />\n <PdfEditorZoomControl\n documentId={documentId}\n disabled={controlsDisabled}\n />\n <PdfEditorToolbarSeparator />\n <div className="flex items-center gap-0.5">\n <PdfEditorToolButton\n label="Rotate counterclockwise"\n disabled={controlsDisabled}\n onClick={() => rotate?.rotateBackward()}\n >\n <RotateGlyph className="size-4 -scale-x-100" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Rotate clockwise"\n disabled={controlsDisabled}\n onClick={() => rotate?.rotateForward()}\n >\n <RotateGlyph className="size-4" />\n </PdfEditorToolButton>\n </div>\n <PdfEditorToolbarSeparator />\n <PdfEditorSearchControl\n documentId={documentId}\n disabled={controlsDisabled}\n open={searchOpen}\n onOpenChange={setSearchOpen}\n />\n <PdfEditorToolButton\n label="Details panel"\n active={rightPanel !== null}\n disabled={controlsDisabled}\n onClick={() => toggleRightPanel("properties")}\n >\n <PanelRightGlyph className="size-4" />\n </PdfEditorToolButton>\n {toolbarActions ? (\n <>\n <PdfEditorToolbarSeparator />\n {toolbarActions}\n </>\n ) : null}\n <PdfEditorToolbarSeparator />\n {showDownload ? (\n <PdfEditorToolButton\n label="Download"\n shortcut="mod+S"\n disabled={controlsDisabled || isDownloading}\n onClick={() => void downloadDocument()}\n >\n {isDownloading ? (\n <Spinner className="size-4" />\n ) : (\n <DownloadGlyph className="size-4" />\n )}\n </PdfEditorToolButton>\n ) : null}\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="More actions"\n >\n <MoreGlyph className="size-4" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="w-60">\n <DropdownMenuGroup>\n <DropdownMenuLabel className="truncate">\n {fileName}\n </DropdownMenuLabel>\n {showUpload ? (\n <DropdownMenuItem\n onClick={() => uploadInputRef.current?.click()}\n >\n <UploadGlyph className="size-4" />\n Open PDF…\n </DropdownMenuItem>\n ) : null}\n {showDownload ? (\n <DropdownMenuItem\n disabled={controlsDisabled}\n onClick={() => void downloadDocument()}\n >\n <DownloadGlyph className="size-4" />\n Download\n <DropdownMenuShortcut>⌘S</DropdownMenuShortcut>\n </DropdownMenuItem>\n ) : null}\n {features.print ? (\n <DropdownMenuItem\n disabled={\n controlsDisabled || !permissions.canPrint\n }\n onClick={() => setDialog({ type: "print" })}\n >\n <PrintGlyph className="size-4" />\n Print…\n <DropdownMenuShortcut>⌘P</DropdownMenuShortcut>\n </DropdownMenuItem>\n ) : null}\n {features.capture ? (\n <DropdownMenuItem\n disabled={controlsDisabled}\n onClick={() => capture?.toggleMarqueeCapture()}\n >\n <CameraGlyph className="size-4" />\n Capture area as image\n </DropdownMenuItem>\n ) : null}\n {features.fullscreen ? (\n <DropdownMenuItem\n onClick={() => fullscreen?.toggleFullscreen()}\n >\n {fullscreenState.isFullscreen ? (\n <ExitFullscreenGlyph className="size-4" />\n ) : (\n <FullscreenGlyph className="size-4" />\n )}\n {fullscreenState.isFullscreen\n ? "Exit full screen"\n : "Full screen"}\n </DropdownMenuItem>\n ) : null}\n </DropdownMenuGroup>\n <DropdownMenuSeparator />\n <DropdownMenuGroup>\n <DropdownMenuItem\n disabled={controlsDisabled}\n onClick={() => setDialog({ type: "properties" })}\n >\n <InfoGlyph className="size-4" />\n Document properties…\n </DropdownMenuItem>\n {features.security ? (\n <DropdownMenuItem\n disabled={controlsDisabled}\n onClick={() => setDialog({ type: "security" })}\n >\n <ShieldGlyph className="size-4" />\n Security…\n </DropdownMenuItem>\n ) : null}\n <DropdownMenuItem\n disabled={\n controlsDisabled ||\n !permissions.canModifyContents\n }\n onClick={flattenDocument}\n >\n <LayersGlyph className="size-4" />\n Flatten annotations…\n </DropdownMenuItem>\n </DropdownMenuGroup>\n <DropdownMenuSeparator />\n <DropdownMenuGroup>\n <DropdownMenuItem\n disabled={controlsDisabled}\n onClick={exportAnnotationsJson}\n >\n <DownloadGlyph className="size-4" />\n Export annotations (JSON)\n </DropdownMenuItem>\n <DropdownMenuItem\n disabled={\n controlsDisabled ||\n !permissions.canModifyAnnotations\n }\n onClick={() =>\n annotationImportInputRef.current?.click()\n }\n >\n <UploadGlyph className="size-4" />\n Import annotations (JSON)…\n </DropdownMenuItem>\n </DropdownMenuGroup>\n <DropdownMenuSeparator />\n <DropdownMenuGroup>\n <DropdownMenuLabel>Page layout</DropdownMenuLabel>\n <DropdownMenuRadioGroup\n value={spreadMode}\n onValueChange={(value) =>\n spread?.setSpreadMode(\n String(value) as SpreadMode\n )\n }\n >\n <DropdownMenuRadioItem value={SpreadMode.None}>\n Single page\n </DropdownMenuRadioItem>\n <DropdownMenuRadioItem value={SpreadMode.Odd}>\n Two pages\n </DropdownMenuRadioItem>\n <DropdownMenuRadioItem value={SpreadMode.Even}>\n Two pages, cover first\n </DropdownMenuRadioItem>\n </DropdownMenuRadioGroup>\n </DropdownMenuGroup>\n <DropdownMenuSeparator />\n <DropdownMenuItem\n onClick={() => setDialog({ type: "shortcuts" })}\n >\n <KeyboardGlyph className="size-4" />\n Keyboard shortcuts\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n </div>\n </ScrollArea>\n </div>\n <div\n data-slot="pdf-editor-ribbon"\n className="flex min-h-10 items-center gap-1 border-b bg-muted/30 px-3 py-1.5"\n >\n <PdfEditorModeSwitch\n mode={mode}\n features={features}\n compact={compactToolbar}\n onModeChange={setMode}\n />\n <PdfEditorToolbarSeparator className="mx-1.5" />\n <ScrollArea\n orientation="horizontal"\n scrollFade\n scrollbarOverflowOnly\n className="min-w-0 flex-1 self-stretch"\n >\n <div className="flex w-max min-w-full items-center gap-0.5 py-0.5">\n {ribbon}\n </div>\n </ScrollArea>\n </div>\n </TooltipProvider>\n ) : null}\n\n <div\n ref={shellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {isLoading ? (\n <div className="absolute inset-0 z-20 flex bg-muted/30">\n {leftPanel ? (\n <DocumentViewerSidebarSkeleton\n className={LEFT_SIDEBAR_WIDTH_CLASS}\n inline={leftInline}\n />\n ) : null}\n <div className="grid min-w-0 flex-1 place-items-center">\n <Spinner className="size-4" />\n </div>\n </div>\n ) : null}\n <div className="flex h-full max-h-full min-h-0 w-full flex-1 overflow-hidden">\n <DocumentViewerThumbnailSidebar\n closedInlineClassName={LEFT_SIDEBAR_CLOSED_CLASS}\n inline={leftInline}\n open={leftPanel !== null && !isLoading}\n widthClassName={LEFT_SIDEBAR_WIDTH_CLASS}\n >\n {leftPanel !== null && !isLoading ? (\n <div className="flex h-full flex-col">\n <PanelTabStrip\n tabs={visibleLeftTabs}\n value={leftPanel}\n onChange={setLeftPanel}\n onClose={() => setLeftPanel(null)}\n label="Sidebar panels"\n />\n <div className="min-h-0 flex-1">{leftPanelContent}</div>\n </div>\n ) : null}\n </DocumentViewerThumbnailSidebar>\n\n <PdfEditorViewport\n documentId={documentId}\n className="relative h-full max-h-full min-h-0 min-w-0 flex-1"\n >\n <PdfEditorViewportBridge\n viewportElementRef={viewportElementRef}\n />\n <GlobalPointerProvider documentId={documentId}>\n <Scroller documentId={documentId} renderPage={renderPage} />\n </GlobalPointerProvider>\n <CopyToClipboard />\n </PdfEditorViewport>\n\n <PdfEditorRightPanelShell\n open={rightPanel !== null && !isLoading}\n inline={rightInline}\n >\n {rightPanel !== null && !isLoading ? (\n <div className="flex h-full flex-col">\n <PanelTabStrip\n tabs={visibleRightTabs}\n value={rightPanel}\n onChange={setRightPanel}\n onClose={() => setRightPanel(null)}\n label="Detail panels"\n />\n <div className="min-h-0 flex-1 overflow-hidden">\n {rightPanel === "properties" ? (\n <PdfEditorScrollArea\n className="h-full w-full"\n scrollbarGutter={false}\n >\n {rightPanelContent}\n </PdfEditorScrollArea>\n ) : (\n rightPanelContent\n )}\n </div>\n </div>\n ) : null}\n </PdfEditorRightPanelShell>\n </div>\n </div>\n\n <PdfEditorSignaturePersistence storageKey={null} />\n {features.capture ? (\n <PdfEditorCaptureDialog documentId={documentId} />\n ) : null}\n <PdfEditorPrintDialog\n documentId={documentId}\n open={dialog?.type === "print"}\n onOpenChange={(open) => {\n if (!open) setDialog(null)\n }}\n />\n <PdfEditorSecurityDialog\n documentId={documentId}\n open={dialog?.type === "security"}\n onOpenChange={(open) => {\n if (!open) setDialog(null)\n }}\n />\n <PdfEditorPropertiesDialog\n documentId={documentId}\n open={dialog?.type === "properties"}\n onOpenChange={(open) => {\n if (!open) setDialog(null)\n }}\n />\n <PdfEditorShortcutsDialog\n open={dialog?.type === "shortcuts"}\n onOpenChange={(open) => {\n if (!open) setDialog(null)\n }}\n />\n <PdfEditorSignatureDialog\n open={dialog?.type === "signature"}\n onOpenChange={(open) => {\n if (!open) setDialog(null)\n }}\n />\n <PdfEditorLinkDialog\n documentId={documentId}\n open={dialog?.type === "link"}\n source={dialog?.type === "link" ? dialog.source : "selection"}\n onOpenChange={(open) => {\n if (!open) setDialog(null)\n }}\n />\n <PdfEditorConfirmDialog\n open={dialog?.type === "confirm"}\n title={dialog?.type === "confirm" ? dialog.title : ""}\n description={\n dialog?.type === "confirm" ? dialog.description : undefined\n }\n confirmLabel={\n dialog?.type === "confirm" ? dialog.confirmLabel : undefined\n }\n destructive={\n dialog?.type === "confirm" ? dialog.destructive : false\n }\n onConfirm={() => {\n if (dialog?.type === "confirm") dialog.onConfirm()\n }}\n onOpenChange={(open) => {\n if (!open) setDialog(null)\n }}\n />\n </div>\n </div>\n </ToastProvider>\n </PdfEditorContextProvider>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Document loader */\n/* -------------------------------------------------------------------------- */\n\ntype PdfEditorDocumentLoaderProps = Omit<\n PdfEditorInnerProps,\n | "documentId"\n | "document"\n | "fileName"\n | "leftPanel"\n | "setLeftPanel"\n | "formDesignMode"\n | "setFormDesignMode"\n> & {\n source: EditorSource | null\n sourceLoading: boolean\n fileNameOverride?: string\n signatureStorageKey: string | null\n onDocumentLoadSuccess?: PDFEditorProps["onDocumentLoadSuccess"]\n onDocumentLoadError?: PDFEditorProps["onDocumentLoadError"]\n}\n\nfunction PdfEditorDocumentLoader({\n source,\n sourceLoading,\n fileNameOverride,\n signatureStorageKey,\n onDocumentLoadSuccess,\n onDocumentLoadError,\n ...innerProps\n}: PdfEditorDocumentLoaderProps) {\n const { provides: documentManager } = useDocumentManagerCapability()\n const { activeDocumentId, activeDocument } = useActiveDocument()\n const [loadError, setLoadError] = React.useState<string | null>(null)\n const [leftPanel, setLeftPanel] = React.useState<PdfEditorLeftPanel | null>(\n null\n )\n const [formDesignMode, setFormDesignMode] = React.useState(false)\n const openedSourceRef = React.useRef<string | null>(null)\n const successRef = React.useRef(onDocumentLoadSuccess)\n const errorRef = React.useRef(onDocumentLoadError)\n\n React.useEffect(() => {\n successRef.current = onDocumentLoadSuccess\n errorRef.current = onDocumentLoadError\n })\n\n React.useEffect(() => {\n if (!documentManager || !source) return\n if (openedSourceRef.current === source.key) return\n\n openedSourceRef.current = source.key\n setLoadError(null)\n\n const previousIds = documentManager\n .getOpenDocuments()\n .map((item) => item.id)\n const fail = (message: string) => {\n if (openedSourceRef.current !== source.key) return\n\n setLoadError(message)\n errorRef.current?.(message)\n }\n\n const task =\n source.kind === "url"\n ? documentManager.openDocumentUrl({\n url: source.url,\n name: source.name,\n mode: source.url.startsWith("blob:") ? "full-fetch" : "auto",\n autoActivate: previousIds.length === 0,\n })\n : documentManager.openDocumentBuffer({\n buffer: source.buffer.slice(0),\n name: source.name,\n autoActivate: previousIds.length === 0,\n })\n\n task.wait(\n (response) => {\n response.task.wait(\n (openedDocument) => {\n documentManager.setActiveDocument(response.documentId)\n successRef.current?.({\n numPages: openedDocument.pageCount,\n documentId: response.documentId,\n fileName: source.name,\n })\n previousIds.forEach((id) => {\n if (id !== response.documentId) {\n documentManager.closeDocument(id).wait(noop, noop)\n }\n })\n },\n (failure) => {\n // Password prompts are handled through the document state.\n if (failure?.reason?.code === PdfErrorCode.Password) return\n fail(failure?.reason?.message ?? "The PDF could not be loaded.")\n }\n )\n },\n (failure) =>\n fail(failure?.reason?.message ?? "The PDF could not be loaded.")\n )\n }, [documentManager, source])\n\n const fileName = source?.name ?? getPdfFileName(fileNameOverride)\n const passwordRequired =\n activeDocument?.status === "error" &&\n activeDocument.errorCode === PdfErrorCode.Password\n const documentFailed =\n loadError !== null ||\n (activeDocument?.status === "error" && !passwordRequired)\n\n if (\n !source ||\n sourceLoading ||\n !activeDocumentId ||\n documentFailed ||\n passwordRequired\n ) {\n return (\n <PdfEditorFallbackShell\n className={innerProps.className}\n fileName={source?.name}\n showToolbar={innerProps.showToolbar}\n showUpload={innerProps.showUpload}\n state={\n !source && !sourceLoading\n ? "empty"\n : passwordRequired\n ? "password"\n : documentFailed\n ? "error"\n : "loading"\n }\n errorMessage={loadError ?? activeDocument?.error ?? undefined}\n onUploadFile={innerProps.onUploadFile}\n >\n {passwordRequired && activeDocument ? (\n <div className="flex-1">\n <PdfEditorPasswordPrompt documentState={activeDocument} />\n </div>\n ) : null}\n </PdfEditorFallbackShell>\n )\n }\n\n const document =\n activeDocument?.status === "loaded" ? activeDocument.document : null\n\n return (\n <>\n <PdfEditorSignaturePersistence storageKey={signatureStorageKey} />\n <PdfEditorInner\n key={activeDocumentId}\n {...innerProps}\n documentId={activeDocumentId}\n document={document}\n fileName={fileName}\n leftPanel={leftPanel}\n setLeftPanel={setLeftPanel}\n formDesignMode={formDesignMode}\n setFormDesignMode={setFormDesignMode}\n />\n </>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Root */\n/* -------------------------------------------------------------------------- */\n\nexport const PDFEditor = React.forwardRef<PDFEditorHandle, PDFEditorProps>(\n function PDFEditor(\n {\n className,\n src,\n fileName,\n defaultZoom = "fit-width",\n defaultMode = "view",\n annotationAuthor = DEFAULT_ANNOTATION_AUTHOR,\n colorPresets = PDF_EDITOR_DEFAULT_COLOR_PRESETS,\n features,\n showToolbar = true,\n showUpload = true,\n showDownload = true,\n toolbarActions,\n selectionActions,\n persistSignatures = true,\n stampManifests,\n signatureFontsStylesheetUrl = PDF_EDITOR_DEFAULT_SIGNATURE_FONTS_URL,\n resolveScrollAreaViewport,\n renderPageOverlay,\n onDocumentLoadSuccess,\n onDocumentLoadError,\n onActivePageChange,\n onModeChange,\n onAnnotationEvent,\n onAnnotationsChange,\n onFormValuesChange,\n onRedactionsApplied,\n onSave,\n onCapture,\n onPdfUpload,\n onToast,\n onSelectionAction,\n },\n ref\n ) {\n const { engine, error: engineError } = useSharedPdfEngine()\n const {\n source,\n loading: sourceLoading,\n replace,\n } = useEditorSource(src, fileName)\n const handleRef = React.useRef<EditorHandleImpl | null>(null)\n const resolvedFeatures = React.useMemo<PdfEditorResolvedFeatures>(\n () => ({ ...PDF_EDITOR_DEFAULT_FEATURES, ...features }),\n [features]\n )\n const resolvedSelectionActions = React.useMemo(\n () => selectionActions ?? [],\n [selectionActions]\n )\n const signatureStorageKey =\n persistSignatures === false\n ? null\n : typeof persistSignatures === "string"\n ? persistSignatures\n : DEFAULT_SIGNATURE_STORAGE_KEY\n\n const handleUploadFile = React.useCallback(\n (file: File) => {\n file.arrayBuffer().then((buffer) => {\n replace(buffer, getPdfFileName(file.name))\n onPdfUpload?.(file)\n })\n },\n [onPdfUpload, replace]\n )\n\n // Plugin registrations are created once per editor instance.\n const [plugins] = React.useState(() => [\n createPluginRegistration(DocumentManagerPluginPackage),\n createPluginRegistration(ViewportPluginPackage, {\n viewportGap: PAGE_GAP,\n }),\n createPluginRegistration(ScrollPluginPackage, {\n defaultPageGap: PAGE_GAP,\n defaultBufferSize: 2,\n }),\n createPluginRegistration(RenderPluginPackage),\n createPluginRegistration(TilingPluginPackage, {\n tileSize: 768,\n overlapPx: 2.5,\n extraRings: 0,\n }),\n createPluginRegistration(InteractionManagerPluginPackage),\n createPluginRegistration(SelectionPluginPackage, {\n menuHeight: SELECTION_MENU_HEIGHT,\n }),\n createPluginRegistration(SearchPluginPackage, { showAllResults: true }),\n createPluginRegistration(ThumbnailPluginPackage, {\n width: THUMBNAIL_WIDTH,\n gap: THUMBNAIL_GAP,\n imagePadding: THUMBNAIL_IMAGE_PADDING,\n labelHeight: THUMBNAIL_LABEL_HEIGHT,\n paddingY: THUMBNAIL_PANE_PADDING_Y,\n buffer: 3,\n autoScroll: true,\n scrollBehavior: "auto",\n }),\n createPluginRegistration(ZoomPluginPackage, {\n defaultZoomLevel: toZoomLevel(defaultZoom),\n minZoom: MIN_ZOOM,\n maxZoom: MAX_ZOOM,\n }),\n createPluginRegistration(RotatePluginPackage),\n createPluginRegistration(SpreadPluginPackage, {\n defaultSpreadMode: SpreadMode.None,\n }),\n createPluginRegistration(PanPluginPackage, { defaultMode: "never" }),\n createPluginRegistration(HistoryPluginPackage),\n createPluginRegistration(AnnotationPluginPackage, {\n annotationAuthor,\n colorPresets,\n autoCommit: true,\n selectAfterCreate: true,\n deactivateToolAfterCreate: false,\n locked: { type: LockModeType.Include, categories: ["form"] },\n }),\n createPluginRegistration(FormPluginPackage),\n createPluginRegistration(RedactionPluginPackage, {\n drawBlackBoxes: true,\n useAnnotationMode: true,\n }),\n createPluginRegistration(StampPluginPackage, {\n defaultLibrary: {\n id: "custom",\n name: "Custom stamps",\n categories: ["custom", "sidebar"],\n },\n ...(stampManifests && stampManifests.length > 0\n ? {\n manifests: [\n {\n url: PDF_EDITOR_DEFAULT_STAMP_MANIFEST_URL,\n fallbackLocale: "en",\n },\n ...stampManifests.map((url) => ({ url })),\n ],\n }\n : {}),\n }),\n createPluginRegistration(SignaturePluginPackage, {\n mode: SignatureMode.SignatureAndInitials,\n defaultSize: { width: 160, height: 56 },\n }),\n createPluginRegistration(ExportPluginPackage, {\n defaultFileName: "document.pdf",\n }),\n createPluginRegistration(PrintPluginPackage),\n createPluginRegistration(CapturePluginPackage, {\n scale: 2,\n imageType: "image/png",\n withAnnotations: true,\n }),\n createPluginRegistration(FullscreenPluginPackage),\n createPluginRegistration(BookmarkPluginPackage),\n createPluginRegistration(AttachmentPluginPackage),\n ])\n\n React.useImperativeHandle(\n ref,\n () => ({\n getDocumentBuffer: () =>\n handleRef.current?.getDocumentBuffer() ??\n Promise.reject(new Error("The document is not ready.")),\n download: (name) =>\n handleRef.current?.download(name) ?? Promise.resolve(),\n print: (options) =>\n handleRef.current?.print(options) ?? Promise.resolve(),\n exportAnnotations: () =>\n handleRef.current?.exportAnnotations() ?? Promise.resolve([]),\n importAnnotations: (items) =>\n handleRef.current?.importAnnotations(items),\n getFormValues: () => handleRef.current?.getFormValues() ?? {},\n setFormValues: (values) =>\n handleRef.current?.setFormValues(values) ?? Promise.resolve(),\n applyRedactions: () =>\n handleRef.current?.applyRedactions() ?? Promise.resolve(),\n setMode: (mode) => handleRef.current?.setMode(mode),\n setActiveTool: (toolId) => handleRef.current?.setActiveTool(toolId),\n scrollToPage: (pageNumber, options) =>\n handleRef.current?.scrollToPage(pageNumber, options),\n undo: () => handleRef.current?.undo(),\n redo: () => handleRef.current?.redo(),\n getViewportElement: () =>\n handleRef.current?.getViewportElement() ?? null,\n }),\n []\n )\n\n if (engineError) {\n return (\n <PdfEditorFallbackShell\n className={className}\n fileName={source?.name}\n showToolbar={showToolbar}\n showUpload={showUpload}\n state="error"\n errorMessage="The PDF engine could not be loaded."\n onUploadFile={handleUploadFile}\n />\n )\n }\n\n if (!engine) {\n return (\n <PdfEditorFallbackShell\n className={className}\n fileName={source?.name}\n showToolbar={showToolbar}\n showUpload={showUpload}\n state="loading"\n onUploadFile={handleUploadFile}\n />\n )\n }\n\n return (\n <PdfEditorScrollAreaResolverContext.Provider\n value={resolveScrollAreaViewport ?? resolveDefaultScrollAreaViewport}\n >\n <EmbedPDF engine={engine} plugins={plugins}>\n <PdfEditorDocumentLoader\n source={source}\n sourceLoading={sourceLoading}\n fileNameOverride={fileName}\n signatureStorageKey={signatureStorageKey}\n className={className}\n defaultZoom={defaultZoom}\n defaultMode={defaultMode}\n annotationAuthor={annotationAuthor}\n features={resolvedFeatures}\n showToolbar={showToolbar}\n showUpload={showUpload}\n showDownload={showDownload}\n toolbarActions={toolbarActions}\n selectionActions={resolvedSelectionActions}\n signatureFontsStylesheetUrl={signatureFontsStylesheetUrl}\n renderPageOverlay={renderPageOverlay}\n handleRef={handleRef}\n onReplaceDocument={replace}\n onUploadFile={handleUploadFile}\n onDocumentLoadSuccess={onDocumentLoadSuccess}\n onDocumentLoadError={onDocumentLoadError}\n onActivePageChange={onActivePageChange}\n onModeChange={onModeChange}\n onAnnotationEvent={onAnnotationEvent}\n onAnnotationsChange={onAnnotationsChange}\n onFormValuesChange={onFormValuesChange}\n onRedactionsApplied={onRedactionsApplied}\n onSave={onSave}\n onCapture={onCapture}\n onToast={onToast}\n onSelectionAction={onSelectionAction}\n />\n </EmbedPDF>\n </PdfEditorScrollAreaResolverContext.Provider>\n )\n }\n)\n',
},
{
fileName: "components/extend/pdf-editor-shared.tsx",