TypeScript
Polish PDF editor controls and sidebar interactions
Andrew Luoc10ad84686d0
diff --git a/apps/v4/components/extend/pdf-editor-dialogs.tsx b/apps/v4/components/extend/pdf-editor-dialogs.tsxnew file mode 100644index 0000000..6fd39f5--- /dev/null+++ b/apps/v4/components/extend/pdf-editor-dialogs.tsx@@ -0,0 +1,1981 @@+"use client"++import * as React from "react"+import type { DocumentState } from "@embedpdf/core"+import {+ useDocumentPermissions,+ useDocumentState,+ useRegistry,+} from "@embedpdf/core/react"+import {+ ignore,+ PdfActionType,+ PdfAnnotationBorderStyle,+ PdfAnnotationReplyType,+ PdfAnnotationSubtype,+ PdfBlendMode,+ PdfErrorCode,+ PdfPermissionFlag,+ PdfZoomMode,+ uuidV4,+ type PdfLinkAnnoObject,+ type PdfLinkTarget,+ type PdfMetadataObject,+ type PdfPrintOptions,+} from "@embedpdf/models"+import { useAnnotationCapability } from "@embedpdf/plugin-annotation/react"+import { useCapture } from "@embedpdf/plugin-capture/react"+import { useDocumentManagerCapability } from "@embedpdf/plugin-document-manager/react"+import { usePrint } from "@embedpdf/plugin-print/react"+import { useScroll } from "@embedpdf/plugin-scroll/react"+import { useSelectionCapability } from "@embedpdf/plugin-selection/react"+import {+ SignatureDrawPad,+ SignatureMode,+ SignatureTypePad,+ useSignatureCapability,+ useSignatureUpload,+ type SignatureDrawPadHandle,+ type SignatureFieldDefinition,+ type SignatureTypePadHandle,+} from "@embedpdf/plugin-signature/react"++import { cn } from "@/lib/utils"+import { Badge } from "@/components/ui/badge"+import { Button } from "@/components/ui/button"+import { ColorPicker } from "@/components/ui/color-picker"+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogPanel,+ DialogTitle,+} from "@/components/ui/dialog"+import { Input } from "@/components/ui/input"+import { Kbd } from "@/components/ui/kbd"+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select"+import { Spinner } from "@/components/ui/spinner"+import {+ CloseGlyph,+ CopyGlyph,+ downloadBlob,+ DownloadGlyph,+ formatBytes,+ formatDateTime,+ formatShortcut,+ KeyGlyph,+ LockGlyph,+ PDF_EDITOR_SIGNATURE_FONTS,+ PdfEditorCheckbox,+ PdfEditorFieldLabel,+ PdfEditorSection,+ PdfEditorSwatch,+ PdfEditorToolButton,+ ShieldGlyph,+ UnlockGlyph,+ usePdfEditor,+} from "@/components/extend/pdf-editor-shared"++/* -------------------------------------------------------------------------- */+/* Confirm */+/* -------------------------------------------------------------------------- */++export function PdfEditorConfirmDialog({+ open,+ onOpenChange,+ title,+ description,+ confirmLabel = "Confirm",+ destructive = false,+ onConfirm,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+ title: string+ description?: string+ confirmLabel?: string+ destructive?: boolean+ onConfirm: () => void+}) {+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle>{title}</DialogTitle>+ {description ? (+ <DialogDescription>{description}</DialogDescription>+ ) : null}+ </DialogHeader>+ <DialogFooter variant="bare">+ <Button+ type="button"+ variant="outline"+ onClick={() => onOpenChange(false)}+ >+ Cancel+ </Button>+ <Button+ type="button"+ variant={destructive ? "destructive" : "default"}+ onClick={() => {+ onConfirm()+ onOpenChange(false)+ }}+ >+ {confirmLabel}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++/* -------------------------------------------------------------------------- */+/* Print */+/* -------------------------------------------------------------------------- */++type PrintPageSelection = "all" | "current" | "custom"++export function PdfEditorPrintDialog({+ documentId,+ open,+ onOpenChange,+}: {+ documentId: string+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { provides: print } = usePrint(documentId)+ const { state: scrollState } = useScroll(documentId)+ const { notify } = usePdfEditor()+ const [selection, setSelection] = React.useState<PrintPageSelection>("all")+ const [customPages, setCustomPages] = React.useState("")+ const [includeAnnotations, setIncludeAnnotations] = React.useState(true)+ const [isPrinting, setIsPrinting] = React.useState(false)+ const [error, setError] = React.useState<string | null>(null)++ React.useEffect(() => {+ if (open) return++ setSelection("all")+ setCustomPages("")+ setIncludeAnnotations(true)+ setIsPrinting(false)+ setError(null)+ }, [open])++ const canSubmit =+ !isPrinting && (selection !== "custom" || customPages.trim().length > 0)++ const handlePrint = () => {+ if (!print || !canSubmit) return++ const options: PdfPrintOptions = {+ includeAnnotations,+ pageRange:+ selection === "current"+ ? String(scrollState.currentPage)+ : selection === "custom"+ ? customPages.trim()+ : undefined,+ }++ setIsPrinting(true)+ setError(null)++ print.print(options).wait(+ () => {+ setIsPrinting(false)+ onOpenChange(false)+ },+ (failure) => {+ setIsPrinting(false)+ const message =+ failure?.reason?.message ?? "The document could not be printed."+ setError(message)+ notify(message, "error")+ }+ )+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle>Print</DialogTitle>+ <DialogDescription>+ Prepares a print-ready copy and opens the browser print dialog.+ </DialogDescription>+ </DialogHeader>+ <DialogPanel className="space-y-5">+ <PdfEditorSection title="Pages">+ <div className="space-y-1">+ <PdfEditorCheckbox+ checked={selection === "all"}+ onCheckedChange={() => setSelection("all")}+ label="All pages"+ />+ <PdfEditorCheckbox+ checked={selection === "current"}+ onCheckedChange={() => setSelection("current")}+ label={`Current page (${scrollState.currentPage || 1})`}+ />+ <PdfEditorCheckbox+ checked={selection === "custom"}+ onCheckedChange={() => setSelection("custom")}+ label="Page range"+ />+ </div>+ <Input+ placeholder="e.g. 1-3, 5, 8-10"+ value={customPages}+ disabled={selection !== "custom"}+ onChange={(event: React.ChangeEvent<HTMLInputElement>) =>+ setCustomPages(event.target.value)+ }+ onFocus={() => setSelection("custom")}+ />+ <div className="text-xs text-muted-foreground">+ {scrollState.totalPages} pages in this document.+ </div>+ </PdfEditorSection>+ <PdfEditorSection title="Options">+ <PdfEditorCheckbox+ checked={includeAnnotations}+ onCheckedChange={setIncludeAnnotations}+ label="Include annotations and form values"+ />+ </PdfEditorSection>+ {error ? (+ <div className="text-xs text-destructive">{error}</div>+ ) : null}+ </DialogPanel>+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ disabled={isPrinting}+ onClick={() => onOpenChange(false)}+ >+ Cancel+ </Button>+ <Button+ type="button"+ loading={isPrinting}+ disabled={!canSubmit || !print}+ onClick={handlePrint}+ >+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++/* -------------------------------------------------------------------------- */+/* Capture */+/* -------------------------------------------------------------------------- */++type CaptureResult = {+ pageIndex: number+ blob: Blob+ imageType: string+ url: string+}++export function PdfEditorCaptureDialog({ documentId }: { documentId: string }) {+ const { provides: capture } = useCapture(documentId)+ const { fileName, notify, onCapture } = usePdfEditor()+ const [result, setResult] = React.useState<CaptureResult | null>(null)+ const onCaptureRef = React.useRef(onCapture)++ React.useEffect(() => {+ onCaptureRef.current = onCapture+ })++ React.useEffect(() => {+ if (!capture) return++ return capture.onCaptureArea((event) => {+ onCaptureRef.current?.(event)+ setResult((previous) => {+ if (previous) URL.revokeObjectURL(previous.url)++ return {+ pageIndex: event.pageIndex,+ blob: event.blob,+ imageType: event.imageType,+ url: URL.createObjectURL(event.blob),+ }+ })+ })+ }, [capture])++ React.useEffect(+ () => () => {+ if (result) URL.revokeObjectURL(result.url)+ },+ [result]+ )++ const close = () => setResult(null)+ const extension = result?.imageType.split("/")[1] ?? "png"+ const captureFileName = `${fileName.replace(/\.pdf$/i, "")}-page-${(result?.pageIndex ?? 0) + 1}.${extension}`+ const canCopy =+ typeof navigator !== "undefined" &&+ typeof window !== "undefined" &&+ "ClipboardItem" in window &&+ Boolean(navigator.clipboard?.write)++ return (+ <Dialog+ open={result !== null}+ onOpenChange={(open) => {+ if (!open) close()+ }}+ >+ <DialogContent className="max-w-2xl">+ <DialogHeader>+ <DialogTitle>Captured area</DialogTitle>+ <DialogDescription>+ Page {(result?.pageIndex ?? 0) + 1} ·{" "}+ {formatBytes(result?.blob.size)}+ </DialogDescription>+ </DialogHeader>+ <DialogPanel>+ <div className="grid place-items-center rounded-lg border bg-muted/40 p-3">+ {result ? (+ <img+ src={result.url}+ alt={`Captured area from page ${result.pageIndex + 1}`}+ className="max-h-[52vh] max-w-full rounded-md shadow-sm"+ />+ ) : null}+ </div>+ </DialogPanel>+ <DialogFooter>+ {canCopy ? (+ <Button+ type="button"+ variant="outline"+ onClick={async () => {+ if (!result) return++ try {+ await navigator.clipboard.write([+ new ClipboardItem({ [result.imageType]: result.blob }),+ ])+ notify("Image copied to the clipboard.", "success")+ } catch {+ notify("The image could not be copied.", "error")+ }+ }}+ >+ <CopyGlyph className="size-4" />+ Copy image+ </Button>+ ) : null}+ <Button+ type="button"+ onClick={() => {+ if (!result) return++ downloadBlob(result.blob, captureFileName)+ close()+ }}+ >+ <DownloadGlyph className="size-4" />+ Download+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++/* -------------------------------------------------------------------------- */+/* Security */+/* -------------------------------------------------------------------------- */++const PERMISSION_OPTIONS: Array<{+ flag: PdfPermissionFlag+ label: string+ description: string+}> = [+ {+ flag: PdfPermissionFlag.Print,+ label: "Print",+ description: "Allow printing, possibly at reduced quality.",+ },+ {+ flag: PdfPermissionFlag.PrintHighQuality,+ label: "Print in high quality",+ description: "Allow full-resolution printing.",+ },+ {+ flag: PdfPermissionFlag.ModifyContents,+ label: "Modify contents",+ description: "Allow editing the page content.",+ },+ {+ flag: PdfPermissionFlag.CopyContents,+ label: "Copy text and images",+ description: "Allow copying and extracting content.",+ },+ {+ flag: PdfPermissionFlag.ModifyAnnotations,+ label: "Annotate",+ description: "Allow adding and changing annotations.",+ },+ {+ flag: PdfPermissionFlag.FillForms,+ label: "Fill forms",+ description: "Allow filling in existing form fields.",+ },+ {+ flag: PdfPermissionFlag.ExtractForAccessibility,+ label: "Extract for accessibility",+ description: "Allow assistive technologies to read the content.",+ },+ {+ flag: PdfPermissionFlag.AssembleDocument,+ label: "Assemble pages",+ description: "Allow inserting, rotating, and deleting pages.",+ },+]++function PasswordInput({+ id,+ value,+ onChange,+ placeholder,+ autoFocus,+ onEnter,+}: {+ id?: string+ value: string+ onChange: (value: string) => void+ placeholder?: string+ autoFocus?: boolean+ onEnter?: () => void+}) {+ return (+ <Input+ id={id}+ type="password"+ autoComplete="off"+ value={value}+ placeholder={placeholder}+ autoFocus={autoFocus}+ onChange={(event: React.ChangeEvent<HTMLInputElement>) =>+ onChange(event.target.value)+ }+ onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {+ if (event.key === "Enter") onEnter?.()+ }}+ />+ )+}++export function PdfEditorSecurityDialog({+ documentId,+ open,+ onOpenChange,+}: {+ documentId: string+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { provides: documentManager } = useDocumentManagerCapability()+ const documentState = useDocumentState(documentId)+ const permissions = useDocumentPermissions(documentId)+ const { notify } = usePdfEditor()+ const document = documentState?.document ?? null+ const isEncrypted = document?.isEncrypted ?? false+ const isOwnerUnlocked = document?.isOwnerUnlocked ?? false+ const needsOwnerUnlock = isEncrypted && !isOwnerUnlocked++ const [unlockPassword, setUnlockPassword] = React.useState("")+ const [isUnlocking, setIsUnlocking] = React.useState(false)+ const [requireOpenPassword, setRequireOpenPassword] = React.useState(false)+ const [openPassword, setOpenPassword] = React.useState("")+ const [confirmOpenPassword, setConfirmOpenPassword] = React.useState("")+ const [restrictPermissions, setRestrictPermissions] = React.useState(false)+ const [ownerPassword, setOwnerPassword] = React.useState("")+ const [confirmOwnerPassword, setConfirmOwnerPassword] = React.useState("")+ const [allowedFlags, setAllowedFlags] = React.useState<+ Set<PdfPermissionFlag>+ >(() => new Set(PERMISSION_OPTIONS.map((option) => option.flag)))+ const [isApplying, setIsApplying] = React.useState(false)+ const [error, setError] = React.useState<string | null>(null)++ React.useEffect(() => {+ if (!open) return++ setUnlockPassword("")+ setIsUnlocking(false)+ setRequireOpenPassword(false)+ setOpenPassword("")+ setConfirmOpenPassword("")+ setRestrictPermissions(false)+ setOwnerPassword("")+ setConfirmOwnerPassword("")+ setAllowedFlags(new Set(PERMISSION_OPTIONS.map((option) => option.flag)))+ setIsApplying(false)+ setError(null)+ }, [open])++ const openPasswordValid =+ !requireOpenPassword ||+ (openPassword.length > 0 && openPassword === confirmOpenPassword)+ const ownerPasswordValid =+ !restrictPermissions ||+ (ownerPassword.length > 0 && ownerPassword === confirmOwnerPassword)+ const canApply =+ !isApplying &&+ (requireOpenPassword || restrictPermissions) &&+ openPasswordValid &&+ ownerPasswordValid++ const handleUnlock = () => {+ if (!documentManager || !unlockPassword.trim()) return++ setIsUnlocking(true)+ setError(null)+ documentManager.unlockOwnerPermissions(documentId, unlockPassword).wait(+ (success) => {+ setIsUnlocking(false)++ if (success) {+ setUnlockPassword("")+ notify("Owner permissions unlocked.", "success")+ } else {+ setError("The owner password is incorrect.")+ }+ },+ (failure) => {+ setIsUnlocking(false)+ setError(+ failure?.reason?.message ?? "The document could not be unlocked."+ )+ }+ )+ }++ const handleApply = () => {+ if (!documentManager || !canApply) return++ let flags = PdfPermissionFlag.AllowAll as number++ if (restrictPermissions) {+ flags = 0+ for (const flag of allowedFlags) flags |= flag+ }++ const userPassword = requireOpenPassword ? openPassword : ""+ const resolvedOwnerPassword = restrictPermissions+ ? ownerPassword+ : requireOpenPassword+ ? openPassword+ : ""++ setIsApplying(true)+ setError(null)+ documentManager+ .setDocumentEncryption(documentId, {+ userPassword,+ ownerPassword: resolvedOwnerPassword,+ allowedFlags: flags,+ })+ .wait(+ (success) => {+ setIsApplying(false)++ if (success) {+ notify(+ "Protection is applied the next time you download the document.",+ "success"+ )+ onOpenChange(false)+ } else {+ setError("The protection settings could not be applied.")+ }+ },+ (failure) => {+ setIsApplying(false)+ setError(+ failure?.reason?.message ??+ "The protection settings could not be applied."+ )+ }+ )+ }++ const handleRemove = () => {+ if (!documentManager) return++ setIsApplying(true)+ setError(null)+ documentManager.removeEncryption(documentId).wait(+ (success) => {+ setIsApplying(false)++ if (success) {+ notify(+ "Protection is removed the next time you download the document.",+ "success"+ )+ onOpenChange(false)+ } else {+ setError("The protection could not be removed.")+ }+ },+ (failure) => {+ setIsApplying(false)+ setError(+ failure?.reason?.message ?? "The protection could not be removed."+ )+ }+ )+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-lg">+ <DialogHeader>+ <DialogTitle>Security</DialogTitle>+ <DialogDescription>+ Passwords and permissions are written into the PDF when you download+ it.+ </DialogDescription>+ </DialogHeader>+ <DialogPanel className="space-y-5">+ <PdfEditorSection title="Current status">+ <div className="flex flex-wrap items-center gap-2 text-sm">+ {isEncrypted ? (+ <Badge variant="secondary">+ <LockGlyph className="size-3" />+ Encrypted+ </Badge>+ ) : (+ <Badge variant="outline">+ <UnlockGlyph className="size-3" />+ Not encrypted+ </Badge>+ )}+ {isEncrypted ? (+ <Badge variant={isOwnerUnlocked ? "secondary" : "outline"}>+ <KeyGlyph className="size-3" />+ {isOwnerUnlocked ? "Owner unlocked" : "Owner locked"}+ </Badge>+ ) : null}+ </div>+ <div className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs text-muted-foreground">+ {PERMISSION_OPTIONS.map((option) => {+ const allowed = permissions.hasPermission(option.flag)++ return (+ <div key={option.flag} className="flex items-center gap-1.5">+ <span+ aria-hidden="true"+ className={cn(+ "size-1.5 rounded-full",+ allowed ? "bg-emerald-500" : "bg-destructive"+ )}+ />+ <span className={cn(!allowed && "line-through")}>+ {option.label}+ </span>+ </div>+ )+ })}+ </div>+ </PdfEditorSection>++ {needsOwnerUnlock ? (+ <PdfEditorSection title="Unlock owner permissions">+ <div className="text-xs text-muted-foreground">+ Enter the owner password to change protection settings.+ </div>+ <div className="flex gap-2">+ <PasswordInput+ value={unlockPassword}+ placeholder="Owner password"+ onChange={setUnlockPassword}+ onEnter={handleUnlock}+ />+ <Button+ type="button"+ variant="outline"+ loading={isUnlocking}+ disabled={!unlockPassword.trim()}+ onClick={handleUnlock}+ >+ Unlock+ </Button>+ </div>+ </PdfEditorSection>+ ) : null}++ <PdfEditorSection title="Open password">+ <PdfEditorCheckbox+ checked={requireOpenPassword}+ disabled={needsOwnerUnlock}+ onCheckedChange={setRequireOpenPassword}+ label="Require a password to open the document"+ />+ {requireOpenPassword ? (+ <div className="grid gap-2 sm:grid-cols-2">+ <PasswordInput+ value={openPassword}+ placeholder="Password"+ onChange={setOpenPassword}+ />+ <PasswordInput+ value={confirmOpenPassword}+ placeholder="Confirm password"+ onChange={setConfirmOpenPassword}+ />+ {!openPasswordValid && confirmOpenPassword ? (+ <div className="text-xs text-destructive sm:col-span-2">+ The passwords do not match.+ </div>+ ) : null}+ </div>+ ) : null}+ </PdfEditorSection>++ <PdfEditorSection title="Permissions">+ <PdfEditorCheckbox+ checked={restrictPermissions}+ disabled={needsOwnerUnlock}+ onCheckedChange={setRestrictPermissions}+ label="Restrict what readers can do"+ description="Requires an owner password to lift the restrictions later."+ />+ {restrictPermissions ? (+ <div className="space-y-3">+ <div className="grid gap-2 sm:grid-cols-2">+ <PasswordInput+ value={ownerPassword}+ placeholder="Owner password"+ onChange={setOwnerPassword}+ />+ <PasswordInput+ value={confirmOwnerPassword}+ placeholder="Confirm owner password"+ onChange={setConfirmOwnerPassword}+ />+ {!ownerPasswordValid && confirmOwnerPassword ? (+ <div className="text-xs text-destructive sm:col-span-2">+ The passwords do not match.+ </div>+ ) : null}+ </div>+ <div className="grid gap-1 sm:grid-cols-2">+ {PERMISSION_OPTIONS.map((option) => (+ <PdfEditorCheckbox+ key={option.flag}+ checked={allowedFlags.has(option.flag)}+ onCheckedChange={(checked) =>+ setAllowedFlags((previous) => {+ const next = new Set(previous)++ if (checked) {+ next.add(option.flag)+ } else {+ next.delete(option.flag)+ }++ return next+ })+ }+ label={option.label}+ description={option.description}+ />+ ))}+ </div>+ </div>+ ) : null}+ </PdfEditorSection>++ {error ? (+ <div className="text-xs text-destructive">{error}</div>+ ) : null}+ </DialogPanel>+ <DialogFooter>+ {isEncrypted && !needsOwnerUnlock ? (+ <Button+ type="button"+ variant="destructive-outline"+ disabled={isApplying}+ onClick={handleRemove}+ className="sm:mr-auto"+ >+ Remove protection+ </Button>+ ) : null}+ <Button+ type="button"+ variant="outline"+ disabled={isApplying}+ onClick={() => onOpenChange(false)}+ >+ Cancel+ </Button>+ <Button+ type="button"+ loading={isApplying}+ disabled={!canApply || needsOwnerUnlock}+ onClick={handleApply}+ >+ <ShieldGlyph className="size-4" />+ Apply protection+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++/* -------------------------------------------------------------------------- */+/* Document properties (metadata) */+/* -------------------------------------------------------------------------- */++type EditableMetadata = {+ title: string+ author: string+ subject: string+ keywords: string+ creator: string+ producer: string+}++const EMPTY_METADATA: EditableMetadata = {+ title: "",+ author: "",+ subject: "",+ keywords: "",+ creator: "",+ producer: "",+}++export function PdfEditorPropertiesDialog({+ documentId,+ open,+ onOpenChange,+}: {+ documentId: string+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { registry } = useRegistry()+ const documentState = useDocumentState(documentId)+ const permissions = useDocumentPermissions(documentId)+ const { fileName, notify } = usePdfEditor()+ const document = documentState?.document ?? null+ const [metadata, setMetadata] =+ React.useState<EditableMetadata>(EMPTY_METADATA)+ const [dates, setDates] = React.useState<{+ creationDate: Date | null+ modificationDate: Date | null+ }>({ creationDate: null, modificationDate: null })+ const [isLoading, setIsLoading] = React.useState(false)+ const [isSaving, setIsSaving] = React.useState(false)+ const [error, setError] = React.useState<string | null>(null)++ React.useEffect(() => {+ if (!open || !registry || !document) return++ let cancelled = false+ setIsLoading(true)+ setError(null)++ registry+ .getEngine()+ .getMetadata(document)+ .wait(+ (result: PdfMetadataObject) => {+ if (cancelled) return++ setMetadata({+ title: result.title ?? "",+ author: result.author ?? "",+ subject: result.subject ?? "",+ keywords: result.keywords ?? "",+ creator: result.creator ?? "",+ producer: result.producer ?? "",+ })+ setDates({+ creationDate: result.creationDate ?? null,+ modificationDate: result.modificationDate ?? null,+ })+ setIsLoading(false)+ },+ (failure) => {+ if (cancelled) return++ setError(+ failure?.reason?.message ??+ "The document metadata could not be read."+ )+ setIsLoading(false)+ }+ )++ return () => {+ cancelled = true+ }+ }, [document, open, registry])++ const updateField = (key: keyof EditableMetadata, value: string) =>+ setMetadata((previous) => ({ ...previous, [key]: value }))++ const handleSave = () => {+ if (!registry || !document) return++ setIsSaving(true)+ setError(null)+ registry+ .getEngine()+ .setMetadata(document, {+ title: metadata.title,+ author: metadata.author,+ subject: metadata.subject,+ keywords: metadata.keywords,+ creator: metadata.creator,+ producer: metadata.producer,+ modificationDate: new Date(),+ })+ .wait(+ () => {+ setIsSaving(false)+ notify("Document properties saved.", "success")+ onOpenChange(false)+ },+ (failure) => {+ setIsSaving(false)+ setError(+ failure?.reason?.message ??+ "The document metadata could not be saved."+ )+ }+ )+ }++ const firstPage = document?.pages[0]++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-lg">+ <DialogHeader>+ <DialogTitle>Document properties</DialogTitle>+ <DialogDescription>{fileName}</DialogDescription>+ </DialogHeader>+ <DialogPanel className="space-y-5">+ {isLoading ? (+ <div className="grid place-items-center py-8">+ <Spinner className="size-4" />+ </div>+ ) : (+ <>+ <PdfEditorSection title="Description">+ <div className="grid gap-3">+ {(+ [+ ["title", "Title"],+ ["author", "Author"],+ ["subject", "Subject"],+ ["keywords", "Keywords"],+ ["creator", "Creator"],+ ["producer", "Producer"],+ ] as Array<[keyof EditableMetadata, string]>+ ).map(([key, label]) => (+ <div key={key} className="grid gap-1">+ <PdfEditorFieldLabel htmlFor={`pdf-editor-meta-${key}`}>+ {label}+ </PdfEditorFieldLabel>+ <Input+ id={`pdf-editor-meta-${key}`}+ size="sm"+ value={metadata[key]}+ disabled={!permissions.canModifyContents}+ onChange={(+ event: React.ChangeEvent<HTMLInputElement>+ ) => updateField(key, event.target.value)}+ />+ </div>+ ))}+ </div>+ </PdfEditorSection>+ <PdfEditorSection title="Details">+ <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5 text-xs">+ <dt className="text-muted-foreground">Pages</dt>+ <dd>{document?.pageCount ?? "—"}</dd>+ <dt className="text-muted-foreground">Page size</dt>+ <dd>+ {firstPage+ ? `${Math.round(firstPage.size.width)} × ${Math.round(firstPage.size.height)} pt`+ : "—"}+ </dd>+ <dt className="text-muted-foreground">Created</dt>+ <dd>{formatDateTime(dates.creationDate)}</dd>+ <dt className="text-muted-foreground">Modified</dt>+ <dd>{formatDateTime(dates.modificationDate)}</dd>+ <dt className="text-muted-foreground">Security</dt>+ <dd>+ {document?.isEncrypted+ ? "Password protected"+ : "No protection"}+ </dd>+ </dl>+ </PdfEditorSection>+ {error ? (+ <div className="text-xs text-destructive">{error}</div>+ ) : null}+ </>+ )}+ </DialogPanel>+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ disabled={isSaving}+ onClick={() => onOpenChange(false)}+ >+ Cancel+ </Button>+ <Button+ type="button"+ loading={isSaving}+ disabled={isLoading || !permissions.canModifyContents}+ onClick={handleSave}+ >+ Save+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++/* -------------------------------------------------------------------------- */+/* Signature creation */+/* -------------------------------------------------------------------------- */++type SignatureCreationTab = "draw" | "type" | "upload"+type SignatureTarget = "signature" | "initials"++const SIGNATURE_COLORS = [+ { name: "Black", value: "#111827" },+ { name: "Blue", value: "#1d4ed8" },+ { name: "Red", value: "#dc2626" },+]++function useSignatureFontsStylesheet(url: string | null, enabled: boolean) {+ React.useEffect(() => {+ if (!enabled || !url || typeof document === "undefined") return++ const existing = document.querySelector<HTMLLinkElement>(+ `link[data-pdf-editor-signature-fonts="${CSS.escape(url)}"]`+ )++ if (existing) return++ const link = document.createElement("link")+ link.rel = "stylesheet"+ link.href = url+ link.dataset.pdfEditorSignatureFonts = url+ document.head.append(link)+ }, [enabled, url])+}++type SignatureUploadZoneProps = {+ inputRef: ReturnType<typeof useSignatureUpload>["inputRef"]+ accept: string+ isDragging: boolean+ previewUrl: string | null+ placeholder: string+ onOpen: () => void+ onFileInputChange: (event: Event) => void+ onDrop: (event: DragEvent) => void+ onDragOver: (event: DragEvent) => void+ onDragLeave: () => void+}++function SignatureUploadZone({+ inputRef,+ accept,+ isDragging,+ previewUrl,+ placeholder,+ onOpen,+ onFileInputChange,+ onDrop,+ onDragOver,+ onDragLeave,+}: SignatureUploadZoneProps) {+ return (+ <>+ <input+ ref={inputRef}+ type="file"+ accept={accept}+ className="sr-only"+ tabIndex={-1}+ onChange={(event) => onFileInputChange(event.nativeEvent)}+ />+ <button+ type="button"+ onClick={onOpen}+ onDrop={(event) => {+ event.preventDefault()+ onDrop(event.nativeEvent)+ }}+ onDragOver={(event) => {+ event.preventDefault()+ onDragOver(event.nativeEvent)+ }}+ onDragLeave={() => onDragLeave()}+ className={cn(+ "flex h-full w-full items-center justify-center rounded-md border-2 border-dashed transition-colors",+ isDragging+ ? "border-primary bg-primary/5"+ : "border-input hover:border-muted-foreground/60"+ )}+ >+ {previewUrl ? (+ <img+ src={previewUrl}+ alt="Uploaded signature"+ className="max-h-[90%] max-w-[90%] object-contain"+ />+ ) : (+ <span className="px-4 text-center text-xs text-muted-foreground">+ {placeholder}+ </span>+ )}+ </button>+ </>+ )+}++function SignaturePad({+ tab,+ color,+ fontFamily,+ placeholder,+ uploadPlaceholder,+ drawRef,+ typeRef,+ upload,+ onResult,+}: {+ tab: SignatureCreationTab+ color: string+ fontFamily: string+ placeholder: string+ uploadPlaceholder: string+ drawRef: React.MutableRefObject<SignatureDrawPadHandle | null>+ typeRef: React.MutableRefObject<SignatureTypePadHandle | null>+ upload: ReturnType<typeof useSignatureUpload>+ onResult: (result: SignatureFieldDefinition | null) => void+}) {+ return (+ <div className="h-full w-full">+ {tab === "draw" ? (+ <SignatureDrawPad+ onResult={onResult}+ padRef={(handle) => {+ drawRef.current = handle+ }}+ strokeColor={color}+ strokeWidth={3}+ className="h-full w-full rounded-md border border-input bg-white"+ />+ ) : null}+ {tab === "type" ? (+ <SignatureTypePad+ onResult={onResult}+ padRef={(handle) => {+ typeRef.current = handle+ }}+ fontFamily={fontFamily}+ fontSize={40}+ color={color}+ placeholder={placeholder}+ className="h-full w-full rounded-md border border-input bg-white px-3 py-2 text-3xl text-slate-950 outline-none dark:bg-white dark:text-slate-950"+ />+ ) : null}+ {tab === "upload" ? (+ <SignatureUploadZone+ inputRef={upload.inputRef}+ accept={upload.accept}+ isDragging={upload.isDragging}+ previewUrl={upload.previewUrl}+ placeholder={uploadPlaceholder}+ onOpen={upload.openFilePicker}+ onFileInputChange={upload.handleFileInputChange}+ onDrop={upload.handleDrop}+ onDragOver={upload.handleDragOver}+ onDragLeave={upload.handleDragLeave}+ />+ ) : null}+ </div>+ )+}++export function PdfEditorSignatureDialog({+ open,+ onOpenChange,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { provides: signatureCapability } = useSignatureCapability()+ const { notify, signatureFontsStylesheetUrl } = usePdfEditor()+ const supportsInitials =+ (signatureCapability?.mode ?? SignatureMode.SignatureOnly) ===+ SignatureMode.SignatureAndInitials+ const [tab, setTab] = React.useState<SignatureCreationTab>("draw")+ const [color, setColor] = React.useState(SIGNATURE_COLORS[0].value)+ const [fontFamily, setFontFamily] = React.useState(+ PDF_EDITOR_SIGNATURE_FONTS[0].family+ )+ const [signature, setSignature] =+ React.useState<SignatureFieldDefinition | null>(null)+ const [initials, setInitials] =+ React.useState<SignatureFieldDefinition | null>(null)+ const [activeTarget, setActiveTarget] =+ React.useState<SignatureTarget>("signature")+ const signatureDrawRef = React.useRef<SignatureDrawPadHandle | null>(null)+ const initialsDrawRef = React.useRef<SignatureDrawPadHandle | null>(null)+ const signatureTypeRef = React.useRef<SignatureTypePadHandle | null>(null)+ const initialsTypeRef = React.useRef<SignatureTypePadHandle | null>(null)++ useSignatureFontsStylesheet(signatureFontsStylesheetUrl, open)++ const signatureUpload = useSignatureUpload({ onResult: setSignature })+ const initialsUpload = useSignatureUpload({ onResult: setInitials })+ const clearSignatureUpload = signatureUpload.clear+ const clearInitialsUpload = initialsUpload.clear++ const clearAll = React.useCallback(() => {+ signatureDrawRef.current?.clear()+ initialsDrawRef.current?.clear()+ signatureTypeRef.current?.clear()+ initialsTypeRef.current?.clear()+ clearSignatureUpload()+ clearInitialsUpload()+ setSignature(null)+ setInitials(null)+ }, [clearInitialsUpload, clearSignatureUpload])++ React.useEffect(() => {+ if (open) return++ setTab("draw")+ setColor(SIGNATURE_COLORS[0].value)+ setFontFamily(PDF_EDITOR_SIGNATURE_FONTS[0].family)+ setActiveTarget("signature")+ setSignature(null)+ setInitials(null)+ }, [open])++ const handleTabChange = (nextTab: SignatureCreationTab) => {+ clearAll()+ setTab(nextTab)+ }++ const canSave = Boolean(signature || initials)++ const handleSave = () => {+ const entrySignature = signature ?? initials+ if (!entrySignature || !signatureCapability) return++ signatureCapability.addEntry({+ signature: entrySignature,+ ...(initials ? { initials } : {}),+ })+ notify(signature ? "Signature saved." : "Initials saved.", "success")+ onOpenChange(false)+ }++ const tabs: Array<{ id: SignatureCreationTab; label: string }> = [+ { id: "draw", label: "Draw" },+ { id: "type", label: "Type" },+ { id: "upload", label: "Upload" },+ ]+ const fontOptions = PDF_EDITOR_SIGNATURE_FONTS.map((font) => ({+ label: font.name,+ value: font.family,+ }))++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-2xl">+ <DialogHeader>+ <DialogTitle>Create signature</DialogTitle>+ <DialogDescription>+ Saved signatures can be placed anywhere in the document.+ </DialogDescription>+ </DialogHeader>+ <DialogPanel className="space-y-4">+ <div className="flex items-center gap-1 rounded-lg bg-muted p-0.5">+ {tabs.map((item) => (+ <button+ key={item.id}+ type="button"+ onClick={() => handleTabChange(item.id)}+ className={cn(+ "flex-1 rounded-md px-3 py-1.5 text-sm font-medium transition-colors",+ tab === item.id+ ? "bg-background text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground"+ )}+ >+ {item.label}+ </button>+ ))}+ </div>++ <div className="space-y-2">+ <div className="flex items-center justify-between gap-3">+ {supportsInitials ? (+ <div className="flex items-center gap-1 rounded-lg bg-muted p-0.5">+ {(["signature", "initials"] as const).map((target) => (+ <button+ key={target}+ type="button"+ aria-pressed={activeTarget === target}+ onClick={() => setActiveTarget(target)}+ className={cn(+ "rounded-md px-3 py-1 text-xs font-medium transition-colors",+ activeTarget === target+ ? "bg-background text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground"+ )}+ >+ {target === "signature" ? "Signature" : "Initials"}+ </button>+ ))}+ </div>+ ) : (+ <PdfEditorFieldLabel>Signature</PdfEditorFieldLabel>+ )}+ <Button+ type="button"+ variant="ghost"+ size="xs"+ onClick={() => {+ if (activeTarget === "signature") {+ if (tab === "draw") signatureDrawRef.current?.clear()+ else if (tab === "type") signatureTypeRef.current?.clear()+ else clearSignatureUpload()+ setSignature(null)+ } else {+ if (tab === "draw") initialsDrawRef.current?.clear()+ else if (tab === "type") initialsTypeRef.current?.clear()+ else clearInitialsUpload()+ setInitials(null)+ }+ }}+ >+ Clear+ </Button>+ </div>+ <div+ className={cn(+ "h-36 w-full",+ activeTarget !== "signature" && "hidden"+ )}+ >+ <SignaturePad+ tab={tab}+ color={color}+ fontFamily={fontFamily}+ placeholder="Type your name"+ uploadPlaceholder="Click or drop an image of your signature"+ drawRef={signatureDrawRef}+ typeRef={signatureTypeRef}+ upload={signatureUpload}+ onResult={setSignature}+ />+ </div>+ {supportsInitials ? (+ <div+ className={cn(+ "w-full",+ activeTarget !== "initials" && "hidden"+ )}+ >+ <div className="aspect-[20/7] h-36 max-w-full">+ <SignaturePad+ tab={tab}+ color={color}+ fontFamily={fontFamily}+ placeholder="Initials"+ uploadPlaceholder="Click or drop an image"+ drawRef={initialsDrawRef}+ typeRef={initialsTypeRef}+ upload={initialsUpload}+ onResult={setInitials}+ />+ </div>+ </div>+ ) : null}+ </div>++ <div className="flex flex-wrap items-center gap-4">+ {tab !== "upload" ? (+ <div className="flex items-center gap-2">+ <span className="text-xs text-muted-foreground">Color</span>+ <div className="flex items-center gap-1.5">+ {SIGNATURE_COLORS.map((option) => (+ <PdfEditorSwatch+ key={option.value}+ color={option.value}+ label={option.name}+ active={color === option.value}+ onClick={() => setColor(option.value)}+ />+ ))}+ <ColorPicker+ label="Custom signature color"+ rainbowTrigger+ color={color}+ onChange={setColor}+ />+ </div>+ </div>+ ) : null}+ {tab === "type" ? (+ <div className="flex items-center gap-2">+ <span className="text-xs text-muted-foreground">Font</span>+ <Select+ items={fontOptions}+ value={fontFamily}+ onValueChange={(value) => setFontFamily(String(value))}+ >+ <SelectTrigger size="sm" className="w-40">+ <SelectValue placeholder="Font" />+ </SelectTrigger>+ <SelectContent alignItemWithTrigger={false}>+ {fontOptions.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ <span style={{ fontFamily: option.value }}>+ {option.label}+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ ) : null}+ </div>+ </DialogPanel>+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ onClick={() => onOpenChange(false)}+ >+ Cancel+ </Button>+ <Button type="button" disabled={!canSave} onClick={handleSave}>+ Save+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++/* -------------------------------------------------------------------------- */+/* Links */+/* -------------------------------------------------------------------------- */++type LinkTab = "url" | "page"++function readLinkTarget(target: PdfLinkTarget | undefined): {+ tab: LinkTab+ url: string+ pageNumber: number | null+} {+ if (!target) return { tab: "url", url: "", pageNumber: null }++ if (target.type === "action") {+ if (target.action.type === PdfActionType.URI) {+ return { tab: "url", url: target.action.uri, pageNumber: null }+ }++ if (+ target.action.type === PdfActionType.Goto ||+ target.action.type === PdfActionType.RemoteGoto+ ) {+ return {+ tab: "page",+ url: "",+ pageNumber: target.action.destination.pageIndex + 1,+ }+ }++ return { tab: "url", url: "", pageNumber: null }+ }++ return {+ tab: "page",+ url: "",+ pageNumber: target.destination.pageIndex + 1,+ }+}++export function PdfEditorLinkDialog({+ documentId,+ open,+ onOpenChange,+ source,+}: {+ documentId: string+ open: boolean+ onOpenChange: (open: boolean) => void+ source: "annotation" | "selection"+}) {+ const { provides: annotationCapability } = useAnnotationCapability()+ const { provides: selectionCapability } = useSelectionCapability()+ const { state: scrollState } = useScroll(documentId)+ const { notify } = usePdfEditor()+ const [tab, setTab] = React.useState<LinkTab>("url")+ const [url, setUrl] = React.useState("")+ const [pageNumber, setPageNumber] = React.useState(1)+ const totalPages = Math.max(scrollState.totalPages, 1)++ const annotationScope = React.useMemo(+ () => annotationCapability?.forDocument(documentId) ?? null,+ [annotationCapability, documentId]+ )+ const selectionScope = React.useMemo(+ () => selectionCapability?.forDocument(documentId) ?? null,+ [documentId, selectionCapability]+ )++ React.useEffect(() => {+ if (!open) return++ const selected =+ source === "annotation" ? annotationScope?.getSelectedAnnotation() : null++ if (selected && selected.object.type === PdfAnnotationSubtype.LINK) {+ const existing = readLinkTarget(+ (selected.object as PdfLinkAnnoObject).target+ )+ setTab(existing.tab)+ setUrl(existing.url)+ setPageNumber(existing.pageNumber ?? 1)+ return+ }++ setTab("url")+ setUrl("")+ setPageNumber(1)+ }, [annotationScope, open, source])++ const buildTarget = (): PdfLinkTarget | null => {+ if (tab === "url") {+ const trimmed = url.trim()++ if (!trimmed) return null++ const normalized = /^[a-z][a-z0-9+.-]*:/i.test(trimmed)+ ? trimmed+ : `https://${trimmed}`++ return {+ type: "action",+ action: { type: PdfActionType.URI, uri: normalized },+ }+ }++ return {+ type: "destination",+ destination: {+ pageIndex: Math.min(Math.max(pageNumber, 1), totalPages) - 1,+ zoom: { mode: PdfZoomMode.FitPage },+ view: [],+ },+ }+ }++ const handleSubmit = () => {+ const target = buildTarget()++ if (!target || !annotationScope) return++ const selected =+ source === "annotation" ? annotationScope.getSelectedAnnotation() : null++ if (selected && selected.object.type === PdfAnnotationSubtype.LINK) {+ annotationScope.updateAnnotation(+ selected.object.pageIndex,+ selected.object.id,+ {+ target,+ } as Partial<PdfLinkAnnoObject>+ )+ notify("Link updated.", "success")+ onOpenChange(false)+ return+ }++ if (selected) {+ const rects =+ "segmentRects" in selected.object &&+ Array.isArray(selected.object.segmentRects) &&+ selected.object.segmentRects.length > 0+ ? selected.object.segmentRects+ : [selected.object.rect]++ for (const rect of rects) {+ annotationScope.createAnnotation<PdfLinkAnnoObject>(+ selected.object.pageIndex,+ {+ id: uuidV4(),+ type: PdfAnnotationSubtype.LINK,+ pageIndex: selected.object.pageIndex,+ rect,+ inReplyToId: selected.object.id,+ replyType: PdfAnnotationReplyType.Group,+ target,+ strokeStyle: PdfAnnotationBorderStyle.UNDERLINE,+ strokeColor: "#2563eb",+ strokeWidth: 2,+ created: new Date(),+ }+ )+ }++ notify("Link added.", "success")+ onOpenChange(false)+ return+ }++ const formattedSelection = selectionScope?.getFormattedSelection() ?? []++ if (formattedSelection.length === 0) {+ notify("Select text or an annotation first.", "error")+ return+ }++ const applyLinks = (text: string[]) => {+ for (const page of formattedSelection) {+ const highlightId = uuidV4()++ annotationScope.createAnnotation(page.pageIndex, {+ id: highlightId,+ created: new Date(),+ flags: ["print"],+ type: PdfAnnotationSubtype.HIGHLIGHT,+ blendMode: PdfBlendMode.Multiply,+ pageIndex: page.pageIndex,+ rect: page.rect,+ segmentRects: page.segmentRects,+ strokeColor: "#ffffff",+ opacity: 0,+ custom: { text: text.join("\n") },+ })++ for (const rect of page.segmentRects) {+ annotationScope.createAnnotation<PdfLinkAnnoObject>(page.pageIndex, {+ id: uuidV4(),+ type: PdfAnnotationSubtype.LINK,+ pageIndex: page.pageIndex,+ rect,+ inReplyToId: highlightId,+ replyType: PdfAnnotationReplyType.Group,+ target,+ strokeStyle: PdfAnnotationBorderStyle.UNDERLINE,+ strokeColor: "#2563eb",+ strokeWidth: 2,+ created: new Date(),+ })+ }+ }++ selectionScope?.clear()+ notify("Link added.", "success")+ onOpenChange(false)+ }++ const textTask = selectionScope?.getSelectedText()++ if (textTask) {+ textTask.wait(applyLinks, () => applyLinks([]))+ } else {+ applyLinks([])+ }+ }++ const canSubmit = tab === "url" ? url.trim().length > 0 : pageNumber >= 1++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle>Add link</DialogTitle>+ <DialogDescription>+ {source === "selection"+ ? "The selected text becomes a clickable link."+ : "The selected annotation becomes a clickable link."}+ </DialogDescription>+ </DialogHeader>+ <DialogPanel className="space-y-4">+ <div className="flex items-center gap-1 rounded-lg bg-muted p-0.5">+ {(+ [+ ["url", "Web address"],+ ["page", "Page in document"],+ ] as Array<[LinkTab, string]>+ ).map(([id, label]) => (+ <button+ key={id}+ type="button"+ onClick={() => setTab(id)}+ className={cn(+ "flex-1 rounded-md px-3 py-1.5 text-sm font-medium transition-colors",+ tab === id+ ? "bg-background text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground"+ )}+ >+ {label}+ </button>+ ))}+ </div>+ {tab === "url" ? (+ <div className="grid gap-1">+ <PdfEditorFieldLabel htmlFor="pdf-editor-link-url">+ URL+ </PdfEditorFieldLabel>+ <Input+ id="pdf-editor-link-url"+ autoFocus+ placeholder="https://example.com"+ value={url}+ onChange={(event: React.ChangeEvent<HTMLInputElement>) =>+ setUrl(event.target.value)+ }+ onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {+ if (event.key === "Enter" && canSubmit) handleSubmit()+ }}+ />+ </div>+ ) : (+ <div className="grid gap-1">+ <PdfEditorFieldLabel htmlFor="pdf-editor-link-page">+ Page number (1–{totalPages})+ </PdfEditorFieldLabel>+ <Input+ id="pdf-editor-link-page"+ type="number"+ min={1}+ max={totalPages}+ value={pageNumber}+ onChange={(event: React.ChangeEvent<HTMLInputElement>) =>+ setPageNumber(Number(event.target.value) || 1)+ }+ />+ </div>+ )}+ </DialogPanel>+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ onClick={() => onOpenChange(false)}+ >+ Cancel+ </Button>+ <Button type="button" disabled={!canSubmit} onClick={handleSubmit}>+ Save link+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++/* -------------------------------------------------------------------------- */+/* Keyboard shortcuts */+/* -------------------------------------------------------------------------- */++export const PDF_EDITOR_SHORTCUTS: Array<{+ group: string+ items: Array<{ keys: string[]; label: string }>+}> = [+ {+ group: "Document",+ items: [+ { keys: ["mod+S"], label: "Download" },+ { keys: ["mod+P"], label: "Print" },+ { keys: ["mod+F"], label: "Search" },+ { keys: ["mod+Z"], label: "Undo" },+ { keys: ["mod+shift+Z"], label: "Redo" },+ ],+ },+ {+ group: "View",+ items: [+ { keys: ["mod+="], label: "Zoom in" },+ { keys: ["mod+-"], label: "Zoom out" },+ { keys: ["mod+0"], label: "Fit page" },+ { keys: ["H"], label: "Hand tool" },+ { keys: ["V"], label: "Select tool" },+ ],+ },+ {+ group: "Editing",+ items: [+ { keys: ["Esc"], label: "Cancel tool / clear selection" },+ { keys: ["Delete"], label: "Delete selected annotations" },+ { keys: ["mod+A"], label: "Select all annotations on the page" },+ ],+ },+]++export function PdfEditorShortcutsDialog({+ open,+ onOpenChange,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle>Keyboard shortcuts</DialogTitle>+ </DialogHeader>+ <DialogPanel className="space-y-4">+ {PDF_EDITOR_SHORTCUTS.map((group) => (+ <PdfEditorSection key={group.group} title={group.group}>+ <div className="divide-y rounded-lg border">+ {group.items.map((item) => (+ <div+ key={item.label}+ className="flex items-center justify-between gap-3 px-3 py-1.5 text-sm"+ >+ <span>{item.label}</span>+ <span className="flex items-center gap-1">+ {item.keys.map((key) => (+ <Kbd key={key}>{formatShortcut(key)}</Kbd>+ ))}+ </span>+ </div>+ ))}+ </div>+ </PdfEditorSection>+ ))}+ </DialogPanel>+ <DialogFooter variant="bare">+ <Button type="button" onClick={() => onOpenChange(false)}>+ Done+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++/* -------------------------------------------------------------------------- */+/* Password prompt (inline) */+/* -------------------------------------------------------------------------- */++export function PdfEditorPasswordPrompt({+ documentState,+}: {+ documentState: DocumentState+}) {+ const { provides: documentManager } = useDocumentManagerCapability()+ const [password, setPassword] = React.useState("")+ const [isRetrying, setIsRetrying] = React.useState(false)+ const isPasswordError = documentState.errorCode === PdfErrorCode.Password+ const isIncorrect = isPasswordError && documentState.passwordProvided++ const handleRetry = () => {+ if (!documentManager || !password.trim()) return++ setIsRetrying(true)+ documentManager.retryDocument(documentState.id, { password }).wait(+ () => {+ setPassword("")+ setIsRetrying(false)+ },+ () => setIsRetrying(false)+ )+ }++ if (!isPasswordError) {+ return (+ <div className="grid h-full place-items-center p-6">+ <div className="max-w-sm space-y-2 text-center">+ <div className="text-sm font-medium text-foreground">+ The document could not be opened+ </div>+ <div className="text-sm text-muted-foreground">+ {documentState.error ?? "An unknown error occurred."}+ </div>+ </div>+ </div>+ )+ }++ return (+ <div className="grid h-full place-items-center p-6">+ <div className="w-full max-w-sm space-y-4 rounded-xl border bg-background p-5 shadow-sm">+ <div className="flex items-start gap-3">+ <div className="grid size-9 shrink-0 place-items-center rounded-full bg-muted text-muted-foreground">+ <LockGlyph className="size-4" />+ </div>+ <div className="space-y-1">+ <div className="text-sm font-medium text-foreground">+ Password required+ </div>+ <div className="text-xs text-muted-foreground">+ {isIncorrect+ ? "The password was incorrect. Try again."+ : "This document is protected. Enter the password to open it."}+ </div>+ </div>+ </div>+ <PasswordInput+ value={password}+ autoFocus+ placeholder="Document password"+ onChange={setPassword}+ onEnter={handleRetry}+ />+ <div className="flex justify-end">+ <Button+ type="button"+ loading={isRetrying}+ disabled={!password.trim()}+ onClick={handleRetry}+ >+ Open document+ </Button>+ </div>+ </div>+ </div>+ )+}++export { ignore as ignorePdfTask }diff --git a/apps/v4/components/extend/pdf-editor-panels.tsx b/apps/v4/components/extend/pdf-editor-panels.tsxnew file mode 100644index 0000000..fc3e767--- /dev/null+++ b/apps/v4/components/extend/pdf-editor-panels.tsx@@ -0,0 +1,2309 @@+"use client"++import * as React from "react"+import { useDocumentState, useRegistry } from "@embedpdf/core/react"+import {+ PDF_FORM_FIELD_TYPE,+ PdfActionType,+ PdfAnnotationName,+ PdfAnnotationSubtype,+ PdfZoomMode,+ uuidV4,+ type PdfAttachmentObject,+ type PdfBookmarkObject,+ type PdfDestinationObject,+ type PdfWidgetAnnoObject,+} from "@embedpdf/models"+import {+ getGroupLeaderId,+ getSelectedAnnotations,+ getSidebarAnnotationsWithRepliesGroupedByPage,+ useAnnotation,+ type SidebarAnnotationEntry,+ type TrackedAnnotation,+} from "@embedpdf/plugin-annotation/react"+import { useAttachmentCapability } from "@embedpdf/plugin-attachment/react"+import { useBookmarkCapability } from "@embedpdf/plugin-bookmark/react"+import {+ useFormCapability,+ type FormFieldInfo,+} from "@embedpdf/plugin-form/react"+import {+ useRedaction,+ type RedactionItem,+} from "@embedpdf/plugin-redaction/react"+import { useScrollCapability } from "@embedpdf/plugin-scroll/react"+import {+ SignatureFieldKind,+ useActivePlacement,+ useSignatureEntries,+} from "@embedpdf/plugin-signature/react"+import {+ StampImg,+ useActiveStamp,+ useStampCapability,+ useStampLibraries,+ useStampsByLibrary,+ type StampDefinition,+} from "@embedpdf/plugin-stamp/react"+import {+ ThumbImg,+ useThumbnailPlugin,+ type ThumbMeta,+ type WindowState,+} from "@embedpdf/plugin-thumbnail/react"+import type { degrees, ParseSpeeds, PDFDocument } from "pdf-lib"++import { cn } from "@/lib/utils"+import { Badge } from "@/components/ui/badge"+import { Button } from "@/components/ui/button"+import { Input } from "@/components/ui/input"+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select"+import { Spinner } from "@/components/ui/spinner"+import { Switch } from "@/components/ui/switch"+import { getFormFieldTypeLabel } from "@/components/extend/pdf-editor-properties"+import {+ ArrowDownGlyph,+ ArrowUpGlyph,+ CheckGlyph,+ ChevronDownGlyph,+ ChevronRightGlyph,+ CommentsGlyph,+ downloadArrayBuffer,+ downloadBlob,+ DownloadGlyph,+ EditGlyph,+ EyeOffGlyph,+ FilePlusGlyph,+ formatBytes,+ formatRelativeDate,+ getAnnotationMeta,+ GridGlyph,+ ListTreeGlyph,+ MergeGlyph,+ PaperclipGlyph,+ PdfEditorEmptyState,+ PdfEditorScrollArea,+ PdfEditorSection,+ PdfEditorToolbarSeparator,+ PdfEditorToolButton,+ PlusGlyph,+ RedactAreaGlyph,+ RotateGlyph,+ ScissorsGlyph,+ SignatureGlyph,+ StampGlyph,+ TextFieldGlyph,+ toArrayBuffer,+ TrashGlyph,+ UploadGlyph,+ usePdfEditor,+ withFileNameSuffix,+} from "@/components/extend/pdf-editor-shared"++/* -------------------------------------------------------------------------- */+/* Thumbnails */+/* -------------------------------------------------------------------------- */++const THUMBNAIL_FOCUS_RING_CLASS =+ "group-focus-visible/pdf-editor-thumbnails:ring-2 group-focus-visible/pdf-editor-thumbnails:ring-ring group-focus-visible/pdf-editor-thumbnails:ring-offset-1 group-focus-visible/pdf-editor-thumbnails:ring-offset-background"++export function PdfEditorThumbnailsPanel({+ documentId,+ activePage,+ pageCount,+ onSelectPage,+}: {+ documentId: string+ activePage: number+ pageCount: number+ onSelectPage: (pageNumber: number) => void+}) {+ const { plugin: thumbnailPlugin } = useThumbnailPlugin()+ const listboxId = React.useId()+ const viewportRef = React.useRef<HTMLDivElement | null>(null)+ const scope = React.useMemo(+ () => thumbnailPlugin?.provides().forDocument(documentId) ?? null,+ [documentId, thumbnailPlugin]+ )+ const windowState = React.useSyncExternalStore<WindowState | null>(+ React.useCallback(+ (onStoreChange) => {+ if (!scope) return () => undefined++ return scope.onWindow(() => onStoreChange())+ },+ [scope]+ ),+ React.useCallback(() => scope?.getWindow() ?? null, [scope]),+ () => null+ )+ const paddingY = thumbnailPlugin?.cfg.paddingY ?? 0++ React.useEffect(() => {+ const viewport = viewportRef.current+ if (!viewport || !scope) return++ const updateWindow = () => {+ scope.updateWindow(viewport.scrollTop, viewport.clientHeight)+ }++ updateWindow()+ viewport.addEventListener("scroll", updateWindow, { passive: true })+ const resizeObserver = new ResizeObserver(updateWindow)+ resizeObserver.observe(viewport)++ return () => {+ viewport.removeEventListener("scroll", updateWindow)+ resizeObserver.disconnect()+ }+ }, [scope])++ React.useEffect(() => {+ const viewport = viewportRef.current+ if (!viewport || !scope) return++ return scope.onScrollTo(({ top, behavior }) => {+ viewport.scrollTo({ top, behavior })+ })+ }, [scope])++ const handleKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLDivElement>) => {+ if (pageCount < 1) return++ const currentPage = activePage > 0 ? activePage : 1+ let nextPage: number | null = null++ if (event.key === "ArrowDown")+ nextPage = Math.min(pageCount, currentPage + 1)+ else if (event.key === "ArrowUp") nextPage = Math.max(1, currentPage - 1)+ else if (event.key === "Home") nextPage = 1+ else if (event.key === "End") nextPage = pageCount++ if (nextPage === null) return++ event.preventDefault()+ onSelectPage(nextPage)+ },+ [activePage, onSelectPage, pageCount]+ )++ return (+ <PdfEditorScrollArea+ className="h-full w-full"+ viewportClassName="group/pdf-editor-thumbnails px-4 focus-visible:ring-0 focus-visible:ring-offset-0"+ viewportProps={{+ "aria-activedescendant":+ activePage > 0 ? `${listboxId}-page-${activePage}` : undefined,+ "aria-label": "Pages",+ onKeyDown: handleKeyDown,+ onMouseDown: (event) => {+ event.currentTarget.focus({ preventScroll: true })+ },+ role: "listbox",+ style: { paddingBottom: paddingY, paddingTop: paddingY },+ tabIndex: 0,+ }}+ viewportRef={viewportRef}+ >+ <div+ className="relative"+ style={{ height: windowState?.totalHeight ?? 0 }}+ >+ {windowState?.items.map((meta: ThumbMeta) => {+ const pageNumber = meta.pageIndex + 1+ const isActive = pageNumber === activePage+ const imagePadding = meta.padding ?? 0++ return (+ <div+ key={meta.pageIndex}+ className={cn(+ "absolute right-0 left-0 flex justify-center",+ isActive && "z-10"+ )}+ style={{ top: meta.top, height: meta.wrapperHeight }}+ >+ <div+ id={`${listboxId}-page-${pageNumber}`}+ role="option"+ aria-selected={isActive}+ aria-current={isActive ? "page" : undefined}+ aria-label={`Page ${pageNumber}`}+ className={cn(+ "flex h-full w-full cursor-default flex-col items-center justify-between rounded-md px-2 text-xs transition-shadow outline-none select-none hover:bg-sidebar-accent",+ isActive+ ? cn(+ "bg-sidebar-accent text-foreground",+ THUMBNAIL_FOCUS_RING_CLASS+ )+ : "text-muted-foreground"+ )}+ onClick={() => onSelectPage(pageNumber)}+ >+ <span+ className="flex items-center justify-center overflow-hidden rounded-md"+ style={{+ width: meta.width + imagePadding * 2,+ height: meta.height + imagePadding * 2,+ padding: imagePadding,+ }}+ >+ <ThumbImg+ documentId={documentId}+ meta={meta}+ className="block rounded-sm object-contain shadow-xs"+ style={{ width: meta.width, height: meta.height }}+ />+ </span>+ <span+ className="flex items-center justify-center tabular-nums"+ style={{ height: meta.labelHeight }}+ >+ {pageNumber}+ </span>+ </div>+ </div>+ )+ })}+ </div>+ </PdfEditorScrollArea>+ )+}++/* -------------------------------------------------------------------------- */+/* Outline */+/* -------------------------------------------------------------------------- */++function resolveBookmarkDestination(bookmark: PdfBookmarkObject): {+ destination: PdfDestinationObject | null+ uri: string | null+} {+ const target = bookmark.target++ if (!target) return { destination: null, uri: null }++ if (target.type === "destination") {+ return { destination: target.destination, uri: null }+ }++ const action = target.action++ if (+ action.type === PdfActionType.Goto ||+ action.type === PdfActionType.RemoteGoto+ ) {+ return { destination: action.destination, uri: null }+ }++ if (action.type === PdfActionType.URI) {+ return { destination: null, uri: action.uri }+ }++ return { destination: null, uri: null }+}++export function PdfEditorOutlinePanel({ documentId }: { documentId: string }) {+ const { provides: bookmark } = useBookmarkCapability()+ const { provides: scroll } = useScrollCapability()+ const documentState = useDocumentState(documentId)+ const document = documentState?.document ?? null+ const [bookmarks, setBookmarks] = React.useState<PdfBookmarkObject[] | null>(+ null+ )+ const [expanded, setExpanded] = React.useState<Set<string>>(() => new Set())++ React.useEffect(() => {+ if (!bookmark || !document) return++ let cancelled = false+ const task = bookmark.forDocument(documentId).getBookmarks()++ task.wait(+ (result) => {+ if (cancelled) return++ setBookmarks(result.bookmarks)+ setExpanded(+ new Set(result.bookmarks.map((_, index) => `bookmark-${index}`))+ )+ },+ () => {+ if (!cancelled) setBookmarks([])+ }+ )++ return () => {+ cancelled = true+ }+ }, [bookmark, document, documentId])++ const navigate = React.useCallback(+ (item: PdfBookmarkObject) => {+ const { destination, uri } = resolveBookmarkDestination(item)++ if (uri) {+ window.open(uri, "_blank", "noopener")+ return+ }++ if (!destination || !scroll) return++ const scope = scroll.forDocument(documentId)+ const page = document?.pages[destination.pageIndex]++ if (destination.zoom.mode === PdfZoomMode.XYZ && page) {+ scope.scrollToPage({+ pageNumber: destination.pageIndex + 1,+ pageCoordinates: {+ x: destination.zoom.params.x,+ y: page.size.height - destination.zoom.params.y,+ },+ behavior: "smooth",+ })+ return+ }++ scope.scrollToPage({+ pageNumber: destination.pageIndex + 1,+ behavior: "smooth",+ })+ },+ [document, documentId, scroll]+ )++ if (bookmarks === null) {+ return (+ <div className="grid h-full place-items-center">+ <Spinner className="size-4" />+ </div>+ )+ }++ if (bookmarks.length === 0) {+ return (+ <PdfEditorEmptyState+ glyph={ListTreeGlyph}+ title="No outline"+ description="This document does not include bookmarks."+ />+ )+ }++ const renderBookmark = (+ item: PdfBookmarkObject,+ id: string,+ level: number+ ): React.ReactNode => {+ const hasChildren = Boolean(item.children && item.children.length > 0)+ const isExpanded = expanded.has(id)++ return (+ <div key={id}>+ <div+ className="group flex cursor-default items-center gap-1 rounded-md py-1 pr-2 text-sm hover:bg-sidebar-accent"+ style={{ paddingLeft: level * 12 + 4 }}+ >+ {hasChildren ? (+ <button+ type="button"+ aria-label={isExpanded ? "Collapse" : "Expand"}+ className="grid size-5 shrink-0 place-items-center rounded text-muted-foreground hover:text-foreground"+ onClick={(event) => {+ event.stopPropagation()+ setExpanded((previous) => {+ const next = new Set(previous)+ if (next.has(id)) next.delete(id)+ else next.add(id)+ return next+ })+ }}+ >+ {isExpanded ? (+ <ChevronDownGlyph className="size-3.5" />+ ) : (+ <ChevronRightGlyph className="size-3.5" />+ )}+ </button>+ ) : (+ <span className="size-5 shrink-0" />+ )}+ <button+ type="button"+ className="min-w-0 flex-1 truncate text-left text-foreground/90 outline-none"+ onClick={() => navigate(item)}+ >+ {item.title || "Untitled"}+ </button>+ </div>+ {hasChildren && isExpanded+ ? item.children?.map((child, index) =>+ renderBookmark(child, `${id}-${index}`, level + 1)+ )+ : null}+ </div>+ )+ }++ return (+ <PdfEditorScrollArea className="h-full w-full" viewportClassName="p-2">+ {bookmarks.map((item, index) =>+ renderBookmark(item, `bookmark-${index}`, 0)+ )}+ </PdfEditorScrollArea>+ )+}++/* -------------------------------------------------------------------------- */+/* Attachments */+/* -------------------------------------------------------------------------- */++export function PdfEditorAttachmentsPanel({+ documentId,+}: {+ documentId: string+}) {+ const { provides: attachment } = useAttachmentCapability()+ const { registry } = useRegistry()+ const documentState = useDocumentState(documentId)+ const { notify, permissions } = usePdfEditor()+ const document = documentState?.document ?? null+ const [attachments, setAttachments] = React.useState<+ PdfAttachmentObject[] | null+ >(null)+ const [version, setVersion] = React.useState(0)+ const [busy, setBusy] = React.useState(false)+ const inputRef = React.useRef<HTMLInputElement>(null)++ React.useEffect(() => {+ if (!attachment || !document) return++ let cancelled = false++ attachment+ .forDocument(documentId)+ .getAttachments()+ .wait(+ (result) => {+ if (!cancelled) setAttachments(result)+ },+ () => {+ if (!cancelled) setAttachments([])+ }+ )++ return () => {+ cancelled = true+ }+ }, [attachment, document, documentId, version])++ const refresh = () => setVersion((value) => value + 1)++ const handleDownload = (item: PdfAttachmentObject) => {+ attachment+ ?.forDocument(documentId)+ .downloadAttachment(item)+ .wait(+ (buffer) =>+ downloadArrayBuffer(+ buffer,+ item.name,+ item.mimeType || "application/octet-stream"+ ),+ () => notify("The attachment could not be downloaded.", "error")+ )+ }++ const handleRemove = (item: PdfAttachmentObject) => {+ if (!registry || !document) return++ setBusy(true)+ registry+ .getEngine()+ .removeAttachment(document, item)+ .wait(+ () => {+ setBusy(false)+ refresh()+ notify("Attachment removed.", "success")+ },+ () => {+ setBusy(false)+ notify("The attachment could not be removed.", "error")+ }+ )+ }++ const handleAdd = async (file: File) => {+ if (!registry || !document) return++ setBusy(true)++ try {+ const data = await file.arrayBuffer()++ registry+ .getEngine()+ .addAttachment(document, {+ name: file.name,+ description: "",+ mimeType: file.type || "application/octet-stream",+ data,+ })+ .wait(+ () => {+ setBusy(false)+ refresh()+ notify("Attachment added.", "success")+ },+ () => {+ setBusy(false)+ notify("The attachment could not be added.", "error")+ }+ )+ } catch {+ setBusy(false)+ notify("The file could not be read.", "error")+ }+ }++ const canModify = permissions.canModifyContents && !busy++ return (+ <div className="flex h-full flex-col">+ <div className="flex shrink-0 items-center gap-2 border-b px-3 py-2">+ <input+ ref={inputRef}+ type="file"+ className="sr-only"+ tabIndex={-1}+ onChange={(event) => {+ const file = event.target.files?.[0]+ if (file) void handleAdd(file)+ event.currentTarget.value = ""+ }}+ />+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={!canModify}+ onClick={() => inputRef.current?.click()}+ >+ <PlusGlyph className="size-4" />+ Attach file+ </Button>+ {busy ? <Spinner className="size-4" /> : null}+ </div>+ {attachments === null ? (+ <div className="grid flex-1 place-items-center">+ <Spinner className="size-4" />+ </div>+ ) : attachments.length === 0 ? (+ <PdfEditorEmptyState+ glyph={PaperclipGlyph}+ title="No attachments"+ description="Files embedded in the PDF appear here."+ />+ ) : (+ <PdfEditorScrollArea className="min-h-0 flex-1" viewportClassName="p-2">+ <div className="space-y-1">+ {attachments.map((item) => (+ <div+ key={`${item.index}-${item.name}`}+ className="flex items-center gap-2 rounded-lg border px-2.5 py-2"+ >+ <div className="grid size-8 shrink-0 place-items-center rounded-md bg-muted text-muted-foreground">+ <PaperclipGlyph className="size-4" />+ </div>+ <div className="min-w-0 flex-1">+ <div className="truncate text-sm font-medium">+ {item.name}+ </div>+ <div className="truncate text-xs text-muted-foreground">+ {[item.mimeType, formatBytes(item.size), item.description]+ .filter(Boolean)+ .join(" · ")}+ </div>+ </div>+ <PdfEditorToolButton+ label="Download"+ size="icon-xs"+ onClick={() => handleDownload(item)}+ >+ <DownloadGlyph className="size-3.5" />+ </PdfEditorToolButton>+ <PdfEditorToolButton+ label="Remove"+ size="icon-xs"+ disabled={!canModify}+ onClick={() => handleRemove(item)}+ >+ <TrashGlyph className="size-3.5" />+ </PdfEditorToolButton>+ </div>+ ))}+ </div>+ </PdfEditorScrollArea>+ )}+ </div>+ )+}++/* -------------------------------------------------------------------------- */+/* Pages (organizer) */+/* -------------------------------------------------------------------------- */++const PAGE_TILE_WIDTH = 76++type PdfLibModule = {+ PDFDocument: typeof PDFDocument+ ParseSpeeds: typeof ParseSpeeds+ degrees: typeof degrees+}++let pdfLibPromise: Promise<PdfLibModule> | null = null++function loadPdfLib() {+ pdfLibPromise ??= import("pdf-lib")+ return pdfLibPromise+}++export function PdfEditorPagesPanel({+ documentId,+ activePage,+}: {+ documentId: string+ activePage: number+}) {+ const { registry } = useRegistry()+ const documentState = useDocumentState(documentId)+ const { state: annotationState, provides: annotation } =+ useAnnotation(documentId)+ const {+ fileName,+ getDocumentBuffer,+ notify,+ openDialog,+ permissions,+ replaceDocument,+ scrollToPage,+ } = usePdfEditor()+ const document = documentState?.document ?? null+ const pages = React.useMemo(() => document?.pages ?? [], [document])+ const [selected, setSelected] = React.useState<Set<number>>(() => new Set())+ const [busy, setBusy] = React.useState<string | null>(null)+ const anchorRef = React.useRef<number | null>(null)+ const appendInputRef = React.useRef<HTMLInputElement>(null)++ React.useEffect(() => {+ void loadPdfLib()+ }, [])++ const metas = React.useMemo<ThumbMeta[]>(+ () =>+ pages.map((page) => {+ const height = Math.max(+ 1,+ Math.round(PAGE_TILE_WIDTH * (page.size.height / page.size.width))+ )++ return {+ pageIndex: page.index,+ width: PAGE_TILE_WIDTH,+ height,+ wrapperHeight: height,+ top: 0,+ labelHeight: 0,+ padding: 0,+ }+ }),+ [pages]+ )++ const selectedIndices = React.useMemo(+ () => [...selected].sort((a, b) => a - b),+ [selected]+ )+ const isEncrypted = document?.isEncrypted ?? false+ const canAssemble =+ permissions.canAssembleDocument && !isEncrypted && busy === null+ const hasSelection = selectedIndices.length > 0+ const isContiguous =+ hasSelection &&+ selectedIndices[selectedIndices.length - 1] - selectedIndices[0] ===+ selectedIndices.length - 1++ const select = (pageIndex: number, mode: "replace" | "toggle" | "range") => {+ setSelected((previous) => {+ if (mode === "range" && anchorRef.current !== null) {+ const start = Math.min(anchorRef.current, pageIndex)+ const end = Math.max(anchorRef.current, pageIndex)+ const next = new Set<number>()+ for (let index = start; index <= end; index += 1) next.add(index)+ return next+ }++ if (mode === "toggle") {+ const next = new Set(previous)+ if (next.has(pageIndex)) next.delete(pageIndex)+ else next.add(pageIndex)+ anchorRef.current = pageIndex+ return next+ }++ anchorRef.current = pageIndex+ return new Set([pageIndex])+ })+ }++ const runOperation = async (+ label: string,+ mutate: (doc: PDFDocument, lib: PdfLibModule) => Promise<void> | void,+ options: { replace?: boolean } = { replace: true }+ ) => {+ setBusy(label)++ try {+ const [buffer, lib] = await Promise.all([+ getDocumentBuffer(),+ loadPdfLib(),+ ])+ const doc = await lib.PDFDocument.load(buffer, {+ ignoreEncryption: true,+ parseSpeed: lib.ParseSpeeds.Fastest,+ updateMetadata: false,+ })++ await mutate(doc, lib)++ if (options.replace !== false) {+ const bytes = await doc.save({ objectsPerTick: 500 })+ replaceDocument(toArrayBuffer(bytes), fileName)+ notify(`${label} applied.`, "success")+ }+ } catch (error) {+ console.error(error)+ notify(`${label} failed.`, "error")+ } finally {+ setBusy(null)+ }+ }++ const rotateSelected = (delta: 90 | -90) =>+ runOperation("Rotate pages", (doc, lib) => {+ for (const index of selectedIndices) {+ const page = doc.getPage(index)+ page.setRotation(+ lib.degrees((page.getRotation().angle + delta + 360) % 360)+ )+ }+ })++ const deleteSelected = () => {+ if (selectedIndices.length >= pages.length) {+ notify("A document needs at least one page.", "error")+ return+ }++ openDialog({+ type: "confirm",+ title: `Delete ${selectedIndices.length === 1 ? "this page" : `${selectedIndices.length} pages`}?`,+ description:+ "Content and annotations on the deleted pages are removed permanently.",+ confirmLabel: "Delete",+ destructive: true,+ onConfirm: async () => {+ setBusy("Delete pages")++ try {+ if (!registry || !document) {+ throw new Error("The document is not ready.")+ }++ if (annotation && annotationState.hasPendingChanges) {+ await annotation.commit().toPromise()+ }++ const engine = registry.getEngine()++ for (const index of [...selectedIndices].reverse()) {+ await engine.deletePage(document, index).toPromise()+ }++ const buffer = await engine.saveAsCopy(document).toPromise()+ replaceDocument(buffer, fileName)+ notify("Delete pages applied.", "success")+ } catch (error) {+ console.error(error)+ notify("Delete pages failed.", "error")+ } finally {+ setBusy(null)+ }+ },+ })+ }++ const moveSelected = (direction: -1 | 1) => {+ const first = selectedIndices[0]+ const last = selectedIndices[selectedIndices.length - 1]++ if (direction === -1 && first === 0) return+ if (direction === 1 && last === pages.length - 1) return++ void runOperation("Move pages", (doc) => {+ // pdf-lib has no move API: detach the neighbouring page from the page+ // tree and re-insert it on the other side of the selected block.+ if (direction === -1) {+ const page = doc.getPage(first - 1)+ doc.removePage(first - 1)+ doc.insertPage(last, page)+ } else {+ const page = doc.getPage(last + 1)+ doc.removePage(last + 1)+ doc.insertPage(first, page)+ }+ })+ }++ const insertBlankAfter = () => {+ const referenceIndex = hasSelection+ ? selectedIndices[selectedIndices.length - 1]+ : Math.max(0, activePage - 1)++ void runOperation("Insert page", (doc) => {+ const reference = doc.getPage(referenceIndex)+ const { width, height } = reference.getSize()+ doc.insertPage(referenceIndex + 1, [width, height])+ })+ }++ const extractSelected = () =>+ runOperation(+ "Extract pages",+ async (doc, lib) => {+ const output = await lib.PDFDocument.create()+ const copied = await output.copyPages(doc, selectedIndices)+ copied.forEach((page) => output.addPage(page))+ const bytes = await output.save()+ downloadArrayBuffer(bytes, withFileNameSuffix(fileName, "-pages"))+ notify(+ `Extracted ${selectedIndices.length} page${selectedIndices.length === 1 ? "" : "s"}.`,+ "success"+ )+ },+ { replace: false }+ )++ const appendFile = (file: File) =>+ runOperation("Append PDF", async (doc, lib) => {+ const source = await lib.PDFDocument.load(await file.arrayBuffer(), {+ ignoreEncryption: true,+ parseSpeed: lib.ParseSpeeds.Fastest,+ updateMetadata: false,+ })+ const copied = await doc.copyPages(source, source.getPageIndices())+ copied.forEach((page) => doc.addPage(page))+ })++ return (+ <div className="flex h-full flex-col">+ <div className="flex shrink-0 flex-wrap items-center gap-0.5 border-b px-2 py-1.5">+ <PdfEditorToolButton+ label="Rotate left"+ disabled={!canAssemble || !hasSelection}+ onClick={() => rotateSelected(-90)}+ >+ <RotateGlyph className="size-4 -scale-x-100" />+ </PdfEditorToolButton>+ <PdfEditorToolButton+ label="Rotate right"+ disabled={!canAssemble || !hasSelection}+ onClick={() => rotateSelected(90)}+ >+ <RotateGlyph className="size-4" />+ </PdfEditorToolButton>+ <PdfEditorToolbarSeparator />+ <PdfEditorToolButton+ label="Move up"+ disabled={!canAssemble || !isContiguous || selectedIndices[0] === 0}+ onClick={() => moveSelected(-1)}+ >+ <ArrowUpGlyph className="size-4" />+ </PdfEditorToolButton>+ <PdfEditorToolButton+ label="Move down"+ disabled={+ !canAssemble ||+ !isContiguous ||+ selectedIndices[selectedIndices.length - 1] === pages.length - 1+ }+ onClick={() => moveSelected(1)}+ >+ <ArrowDownGlyph className="size-4" />+ </PdfEditorToolButton>+ <PdfEditorToolbarSeparator />+ <PdfEditorToolButton+ label="Insert blank page after"+ disabled={!canAssemble}+ onClick={insertBlankAfter}+ >+ <FilePlusGlyph className="size-4" />+ </PdfEditorToolButton>+ <PdfEditorToolButton+ label="Append PDF"+ disabled={!canAssemble}+ onClick={() => appendInputRef.current?.click()}+ >+ <MergeGlyph className="size-4" />+ </PdfEditorToolButton>+ <PdfEditorToolButton+ label="Extract selected pages"+ disabled={busy !== null || !hasSelection}+ onClick={() => void extractSelected()}+ >+ <ScissorsGlyph className="size-4" />+ </PdfEditorToolButton>+ <PdfEditorToolButton+ label="Delete pages"+ disabled={!canAssemble || !hasSelection}+ onClick={deleteSelected}+ >+ <TrashGlyph className="size-4" />+ </PdfEditorToolButton>+ <input+ ref={appendInputRef}+ type="file"+ accept="application/pdf,.pdf"+ className="sr-only"+ tabIndex={-1}+ onChange={(event) => {+ const file = event.target.files?.[0]+ if (file) void appendFile(file)+ event.currentTarget.value = ""+ }}+ />+ </div>+ <div className="flex shrink-0 items-center justify-between gap-2 border-b px-3 py-1.5 text-xs text-muted-foreground">+ <span>+ {hasSelection+ ? `${selectedIndices.length} of ${pages.length} selected`+ : `${pages.length} page${pages.length === 1 ? "" : "s"}`}+ </span>+ {busy ? (+ <span className="flex items-center gap-1.5">+ <Spinner className="size-3" />+ {busy}…+ </span>+ ) : isEncrypted ? (+ <span>Remove protection to edit pages.</span>+ ) : hasSelection ? (+ <button+ type="button"+ className="underline-offset-2 hover:underline"+ onClick={() => setSelected(new Set())}+ >+ Clear+ </button>+ ) : null}+ </div>+ <PdfEditorScrollArea+ className="min-h-0 flex-1"+ viewportClassName="px-2.5 py-3"+ >+ <div className="grid grid-cols-2 gap-2">+ {metas.map((meta) => {+ const pageNumber = meta.pageIndex + 1+ const isSelected = selected.has(meta.pageIndex)+ const isActive = pageNumber === activePage++ return (+ <button+ key={meta.pageIndex}+ type="button"+ aria-pressed={isSelected}+ className={cn(+ "group flex min-w-0 flex-col items-center gap-1.5 rounded-lg border p-1.5 text-xs transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",+ isSelected+ ? "border-primary bg-primary/5 ring-1 ring-primary/20"+ : "border-transparent hover:bg-sidebar-accent",+ isActive && !isSelected && "border-border"+ )}+ onClick={(event) => {+ select(+ meta.pageIndex,+ event.shiftKey+ ? "range"+ : event.metaKey || event.ctrlKey+ ? "toggle"+ : "replace"+ )+ }}+ onDoubleClick={() => scrollToPage(pageNumber)}+ >+ <span+ className={cn(+ "grid place-items-center rounded-md border p-1 transition-colors",+ isSelected+ ? "border-primary/40 bg-primary/5"+ : "border-border/60 bg-muted/30"+ )}+ >+ <span+ className="grid place-items-center overflow-hidden rounded-sm bg-white shadow-xs"+ style={{ width: meta.width, height: meta.height }}+ >+ <ThumbImg+ documentId={documentId}+ meta={meta}+ className="block object-contain"+ style={{ width: meta.width, height: meta.height }}+ />+ </span>+ </span>+ <span+ className={cn(+ "tabular-nums",+ isSelected ? "text-foreground" : "text-muted-foreground"+ )}+ >+ {pageNumber}+ </span>+ </button>+ )+ })}+ </div>+ </PdfEditorScrollArea>+ </div>+ )+}++/* -------------------------------------------------------------------------- */+/* Comments */+/* -------------------------------------------------------------------------- */++function CommentComposer({+ placeholder,+ initialValue = "",+ autoFocus,+ submitLabel = "Save",+ onSubmit,+ onCancel,+}: {+ placeholder: string+ initialValue?: string+ autoFocus?: boolean+ submitLabel?: string+ onSubmit: (value: string) => void+ onCancel?: () => void+}) {+ const [value, setValue] = React.useState(initialValue)++ return (+ <div className="space-y-1.5">+ <textarea+ value={value}+ autoFocus={autoFocus}+ rows={2}+ placeholder={placeholder}+ onChange={(event) => setValue(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {+ event.preventDefault()+ if (value.trim()) onSubmit(value.trim())+ }++ if (event.key === "Escape") onCancel?.()+ }}+ className="w-full resize-none rounded-md border border-input bg-background px-2 py-1.5 text-sm outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring"+ />+ <div className="flex justify-end gap-1">+ {onCancel ? (+ <Button type="button" size="xs" variant="ghost" onClick={onCancel}>+ Cancel+ </Button>+ ) : null}+ <Button+ type="button"+ size="xs"+ disabled={!value.trim()}+ onClick={() => onSubmit(value.trim())}+ >+ {submitLabel}+ </Button>+ </div>+ </div>+ )+}++function CommentCard({+ entry,+ isSelected,+ readOnly,+ onSelect,+ onUpdate,+ onDelete,+ onReply,+}: {+ entry: SidebarAnnotationEntry+ isSelected: boolean+ readOnly: boolean+ onSelect: () => void+ onUpdate: (annotation: TrackedAnnotation, contents: string) => void+ onDelete: (annotation: TrackedAnnotation) => void+ onReply: (annotation: TrackedAnnotation, contents: string) => void+}) {+ const { annotation, replies } = entry+ const [isEditing, setIsEditing] = React.useState(false)+ const [isReplying, setIsReplying] = React.useState(false)+ const meta = getAnnotationMeta(annotation.object)+ const contents =+ typeof annotation.object.contents === "string"+ ? annotation.object.contents+ : ""+ const quotedText =+ annotation.object.custom &&+ typeof annotation.object.custom === "object" &&+ typeof (annotation.object.custom as { text?: unknown }).text === "string"+ ? ((annotation.object.custom as { text: string }).text as string)+ : null+ const Glyph = meta.glyph++ return (+ <div+ role="button"+ tabIndex={0}+ onClick={onSelect}+ onKeyDown={(event) => {+ if (event.key === "Enter") onSelect()+ }}+ className={cn(+ "rounded-lg border bg-background p-3 text-left shadow-xs transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring",+ isSelected+ ? "border-primary ring-1 ring-primary/40"+ : "hover:bg-accent/40"+ )}+ >+ <div className="flex items-start gap-2">+ <span+ className="grid size-7 shrink-0 place-items-center rounded-full bg-muted"+ style={meta.color ? { color: meta.color } : undefined}+ >+ <Glyph className="size-3.5" />+ </span>+ <div className="min-w-0 flex-1">+ <div className="flex items-center justify-between gap-2">+ <div className="min-w-0">+ <div className="truncate text-sm font-medium">+ {annotation.object.author || "Guest"}+ </div>+ <div className="text-[11px] text-muted-foreground">+ {meta.label} · page {annotation.object.pageIndex + 1}+ {annotation.object.modified || annotation.object.created+ ? ` · ${formatRelativeDate(annotation.object.modified ?? annotation.object.created)}`+ : ""}+ </div>+ </div>+ {!readOnly ? (+ <div className="flex shrink-0 items-center gap-0.5">+ <PdfEditorToolButton+ label={contents ? "Edit comment" : "Add comment"}+ size="icon-xs"+ onClick={(event) => {+ event.stopPropagation()+ setIsEditing(true)+ }}+ >+ <EditGlyph className="size-3.5" />+ </PdfEditorToolButton>+ <PdfEditorToolButton+ label="Delete"+ size="icon-xs"+ onClick={(event) => {+ event.stopPropagation()+ onDelete(annotation)+ }}+ >+ <TrashGlyph className="size-3.5" />+ </PdfEditorToolButton>+ </div>+ ) : null}+ </div>+ {quotedText ? (+ <blockquote className="mt-1.5 line-clamp-3 border-l-2 pl-2 text-xs text-muted-foreground italic">+ {quotedText}+ </blockquote>+ ) : null}+ {isEditing ? (+ <div className="mt-2" onClick={(event) => event.stopPropagation()}>+ <CommentComposer+ placeholder="Write a comment…"+ initialValue={contents}+ autoFocus+ onSubmit={(value) => {+ onUpdate(annotation, value)+ setIsEditing(false)+ }}+ onCancel={() => setIsEditing(false)}+ />+ </div>+ ) : contents ? (+ <p className="mt-1.5 text-sm whitespace-pre-wrap">{contents}</p>+ ) : (+ <p className="mt-1.5 text-xs text-muted-foreground">+ No comment yet.+ </p>+ )}+ </div>+ </div>+ {replies.length > 0 ? (+ <div className="mt-2 space-y-2 border-l pl-3">+ {replies.map((reply) => (+ <div key={reply.object.id} className="text-sm">+ <div className="flex items-center justify-between gap-2">+ <span className="text-xs font-medium">+ {reply.object.author || "Guest"}+ <span className="ml-1.5 font-normal text-muted-foreground">+ {formatRelativeDate(+ reply.object.modified ?? reply.object.created+ )}+ </span>+ </span>+ {!readOnly ? (+ <PdfEditorToolButton+ label="Delete reply"+ size="icon-xs"+ onClick={(event) => {+ event.stopPropagation()+ onDelete(reply)+ }}+ >+ <TrashGlyph className="size-3" />+ </PdfEditorToolButton>+ ) : null}+ </div>+ <p className="whitespace-pre-wrap">{reply.object.contents}</p>+ </div>+ ))}+ </div>+ ) : null}+ {!readOnly ? (+ <div className="mt-2" onClick={(event) => event.stopPropagation()}>+ {isReplying ? (+ <CommentComposer+ placeholder="Reply…"+ autoFocus+ submitLabel="Reply"+ onSubmit={(value) => {+ onReply(annotation, value)+ setIsReplying(false)+ }}+ onCancel={() => setIsReplying(false)}+ />+ ) : (+ <Button+ type="button"+ size="xs"+ variant="ghost"+ className="text-muted-foreground"+ onClick={() => setIsReplying(true)}+ >+ Reply+ </Button>+ )}+ </div>+ ) : null}+ </div>+ )+}++export function PdfEditorCommentsPanel({ documentId }: { documentId: string }) {+ const { provides: annotation, state } = useAnnotation(documentId)+ const { annotationAuthor, permissions, scrollToAnnotation } = usePdfEditor()+ const grouped = React.useMemo(+ () => getSidebarAnnotationsWithRepliesGroupedByPage(state),+ [state]+ )+ const selectedLeaderIds = React.useMemo(() => {+ const ids = new Set<string>()++ for (const item of getSelectedAnnotations(state)) {+ ids.add(getGroupLeaderId(state, item.object.id) ?? item.object.id)+ }++ return ids+ }, [state])+ const pageNumbers = React.useMemo(+ () =>+ Object.keys(grouped)+ .map(Number)+ .sort((a, b) => a - b),+ [grouped]+ )+ const readOnly = !permissions.canModifyAnnotations+ const cardRefs = React.useRef<Map<string, HTMLDivElement>>(new Map())+ const firstSelectedId = selectedLeaderIds.values().next().value++ React.useEffect(() => {+ if (!firstSelectedId) return++ const element = cardRefs.current.get(firstSelectedId)+ element?.scrollIntoView({ block: "nearest", behavior: "smooth" })+ }, [firstSelectedId])++ if (pageNumbers.length === 0) {+ return (+ <PdfEditorEmptyState+ glyph={CommentsGlyph}+ title="No comments yet"+ description="Annotations and notes you add to the document show up here."+ />+ )+ }++ return (+ <PdfEditorScrollArea className="h-full w-full" viewportClassName="p-3">+ <div className="space-y-5">+ {pageNumbers.map((pageIndex) => (+ <div key={pageIndex} className="space-y-2">+ <div className="text-xs font-medium text-muted-foreground">+ Page {pageIndex + 1}+ </div>+ <div className="space-y-2">+ {grouped[pageIndex].map((entry) => (+ <div+ key={entry.annotation.object.id}+ ref={(element) => {+ if (element) {+ cardRefs.current.set(entry.annotation.object.id, element)+ } else {+ cardRefs.current.delete(entry.annotation.object.id)+ }+ }}+ >+ <CommentCard+ entry={entry}+ isSelected={selectedLeaderIds.has(+ entry.annotation.object.id+ )}+ readOnly={readOnly}+ onSelect={() => {+ annotation?.selectAnnotation(+ entry.annotation.object.pageIndex,+ entry.annotation.object.id+ )+ scrollToAnnotation(entry.annotation.object)+ }}+ onUpdate={(item, contents) =>+ annotation?.updateAnnotation(+ item.object.pageIndex,+ item.object.id,+ {+ contents,+ modified: new Date(),+ }+ )+ }+ onDelete={(item) =>+ annotation?.deleteAnnotation(+ item.object.pageIndex,+ item.object.id+ )+ }+ onReply={(parent, contents) =>+ annotation?.createAnnotation(parent.object.pageIndex, {+ id: uuidV4(),+ type: PdfAnnotationSubtype.TEXT,+ pageIndex: parent.object.pageIndex,+ rect: {+ origin: {+ x: parent.object.rect.origin.x,+ y: parent.object.rect.origin.y,+ },+ size: { width: 24, height: 24 },+ },+ contents,+ inReplyToId: parent.object.id,+ flags: ["noRotate", "noZoom", "print"],+ name: PdfAnnotationName.Comment,+ author: annotationAuthor,+ created: new Date(),+ modified: new Date(),+ })+ }+ />+ </div>+ ))}+ </div>+ </div>+ ))}+ </div>+ </PdfEditorScrollArea>+ )+}++/* -------------------------------------------------------------------------- */+/* Redactions */+/* -------------------------------------------------------------------------- */++export function PdfEditorRedactionsPanel({+ documentId,+}: {+ documentId: string+}) {+ const { state, provides } = useRedaction(documentId)+ const { provides: scroll } = useScrollCapability()+ const { openDialog, permissions, notify } = usePdfEditor()+ const items = React.useMemo(+ () =>+ Object.entries(state.pending)+ .flatMap(([page, pageItems]) =>+ pageItems.map((item) => ({ item, pageNumber: Number(page) + 1 }))+ )+ .sort((a, b) => a.pageNumber - b.pageNumber),+ [state.pending]+ )+ const [isApplying, setIsApplying] = React.useState(false)+ const canApply = permissions.canModifyContents && !isApplying++ const selectItem = (item: RedactionItem) => {+ provides?.selectPending(item.page, item.id)+ scroll?.forDocument(documentId).scrollToPage({+ pageNumber: item.page + 1,+ pageCoordinates: { x: item.rect.origin.x, y: item.rect.origin.y },+ alignX: 50,+ alignY: 25,+ behavior: "smooth",+ })+ }++ const applyAll = () =>+ openDialog({+ type: "confirm",+ title: `Apply ${items.length} redaction${items.length === 1 ? "" : "s"}?`,+ description:+ "Redaction permanently removes the marked content from the document. This cannot be undone.",+ confirmLabel: "Apply redactions",+ onConfirm: () => {+ if (!provides) return++ setIsApplying(true)+ provides.commitAllPending().wait(+ () => setIsApplying(false),+ () => {+ setIsApplying(false)+ notify("The redactions could not be applied.", "error")+ }+ )+ },+ })++ const applyOne = (item: RedactionItem) =>+ openDialog({+ type: "confirm",+ title: "Apply this redaction?",+ description: "The marked content is removed permanently.",+ confirmLabel: "Apply",+ onConfirm: () => {+ provides?.commitPending(item.page, item.id).wait(+ () => undefined,+ () => notify("The redaction could not be applied.", "error")+ )+ },+ })++ return (+ <div className="flex h-full flex-col">+ {items.length === 0 ? (+ <PdfEditorEmptyState+ glyph={EyeOffGlyph}+ title="No pending redactions"+ description="Use the Redact tools to mark text or areas. Marks stay editable until you apply them."+ />+ ) : (+ <PdfEditorScrollArea className="min-h-0 flex-1" viewportClassName="p-2">+ <div className="space-y-1.5">+ {items.map(({ item, pageNumber }) => {+ const isSelected = state.selected?.id === item.id+ const Glyph = item.kind === "text" ? EyeOffGlyph : RedactAreaGlyph++ return (+ <div+ key={item.id}+ role="button"+ tabIndex={0}+ onClick={() => selectItem(item)}+ onKeyDown={(event) => {+ if (event.key === "Enter") selectItem(item)+ }}+ className={cn(+ "flex items-start gap-2 rounded-lg border px-2.5 py-2 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring",+ isSelected+ ? "border-primary ring-1 ring-primary/40"+ : "hover:bg-accent/40"+ )}+ >+ <span+ className="mt-0.5 grid size-6 shrink-0 place-items-center rounded-md"+ style={{+ backgroundColor: `${item.markColor}22`,+ color: item.markColor,+ }}+ >+ <Glyph className="size-3.5" />+ </span>+ <div className="min-w-0 flex-1">+ <div className="text-sm font-medium">+ {item.kind === "text" ? "Text" : "Area"}+ <span className="ml-1.5 text-xs font-normal text-muted-foreground">+ page {pageNumber}+ </span>+ </div>+ {item.kind === "text" && item.text ? (+ <div className="truncate text-xs text-muted-foreground italic">+ “{item.text}”+ </div>+ ) : null}+ </div>+ <div className="flex shrink-0 items-center gap-0.5">+ <PdfEditorToolButton+ label="Apply"+ size="icon-xs"+ disabled={!canApply}+ onClick={(event) => {+ event.stopPropagation()+ applyOne(item)+ }}+ >+ <CheckGlyph className="size-3.5" />+ </PdfEditorToolButton>+ <PdfEditorToolButton+ label="Remove mark"+ size="icon-xs"+ onClick={(event) => {+ event.stopPropagation()+ provides?.removePending(item.page, item.id)+ }}+ >+ <TrashGlyph className="size-3.5" />+ </PdfEditorToolButton>+ </div>+ </div>+ )+ })}+ </div>+ </PdfEditorScrollArea>+ )}+ {items.length > 0 ? (+ <div className="flex shrink-0 gap-2 border-t p-2">+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="flex-1"+ disabled={isApplying}+ onClick={() => provides?.clearPending()}+ >+ Clear all+ </Button>+ <Button+ type="button"+ size="sm"+ className="flex-1"+ loading={isApplying}+ disabled={!canApply}+ onClick={applyAll}+ >+ Apply all+ </Button>+ </div>+ ) : null}+ </div>+ )+}++/* -------------------------------------------------------------------------- */+/* Stamps */+/* -------------------------------------------------------------------------- */++const CUSTOM_STAMP_LIBRARY_ID = "custom"+const STAMP_THUMB_WIDTH = 120+const UNSUPPORTED_STAMP_SOURCE_TYPES = new Set<PdfAnnotationSubtype>([+ PdfAnnotationSubtype.REDACT,+ PdfAnnotationSubtype.HIGHLIGHT,+ PdfAnnotationSubtype.SQUIGGLY,+ PdfAnnotationSubtype.UNDERLINE,+ PdfAnnotationSubtype.STRIKEOUT,+ PdfAnnotationSubtype.CARET,+ PdfAnnotationSubtype.WIDGET,+ PdfAnnotationSubtype.LINK,+])++export function PdfEditorStampsPanel({ documentId }: { documentId: string }) {+ const { libraries } = useStampLibraries()+ const { provides: stampCapability } = useStampCapability()+ const { provides: annotation, state: annotationState } =+ useAnnotation(documentId)+ const { notify, permissions } = usePdfEditor()+ const [libraryId, setLibraryId] = React.useState("all")+ const stamps = useStampsByLibrary(libraryId === "all" ? undefined : libraryId)+ const activeStamp = useActiveStamp(documentId)+ const [busy, setBusy] = React.useState(false)+ const importInputRef = React.useRef<HTMLInputElement>(null)+ const selected = React.useMemo(+ () => getSelectedAnnotations(annotationState),+ [annotationState]+ )+ const canCreateFromSelection =+ selected.length === 1 &&+ !UNSUPPORTED_STAMP_SOURCE_TYPES.has(selected[0].object.type)+ const customLibrary = libraries.find(+ (library) => library.id === CUSTOM_STAMP_LIBRARY_ID+ )+ const libraryOptions = [+ { label: "All libraries", value: "all" },+ ...libraries.map((library) => ({+ label: library.name,+ value: library.id,+ })),+ ]++ React.useEffect(() => {+ if (+ libraryId !== "all" &&+ !libraries.some((library) => library.id === libraryId)+ ) {+ setLibraryId("all")+ }+ }, [libraries, libraryId])++ const placeStamp = (targetLibraryId: string, stamp: StampDefinition) => {+ if (!stampCapability) return++ const isActive =+ activeStamp?.libraryId === targetLibraryId &&+ activeStamp.stamp.id === stamp.id++ if (isActive) {+ annotation?.setActiveTool(null)+ return+ }++ stampCapability+ .forDocument(documentId)+ .activateStampPlacement(targetLibraryId, stamp)+ .wait(+ () => undefined,+ () => notify("The stamp could not be activated.", "error")+ )+ }++ const createFromSelection = () => {+ if (!stampCapability || !canCreateFromSelection) return++ const count = customLibrary?.stamps.length ?? 0++ setBusy(true)+ stampCapability+ .forDocument(documentId)+ .createStampFromAnnotation(+ selected[0].object,+ {+ name: PdfAnnotationName.Custom,+ subject: `Custom stamp ${count + 1}`,+ categories: ["custom", "sidebar"],+ },+ CUSTOM_STAMP_LIBRARY_ID+ )+ .wait(+ () => {+ setBusy(false)+ setLibraryId(CUSTOM_STAMP_LIBRARY_ID)+ notify("Stamp saved to your custom library.", "success")+ },+ () => {+ setBusy(false)+ notify("The stamp could not be created from the selection.", "error")+ }+ )+ }++ const exportLibrary = (targetLibraryId: string) => {+ stampCapability?.exportLibrary(targetLibraryId).wait(+ (exported) => downloadArrayBuffer(exported.pdf, `${exported.name}.pdf`),+ () => notify("The library could not be exported.", "error")+ )+ }++ const importLibrary = async (file: File) => {+ if (!stampCapability) return++ setBusy(true)++ try {+ const buffer = await file.arrayBuffer()+ const lib = await import("pdf-lib")+ const pageCount = (+ await lib.PDFDocument.load(buffer, { ignoreEncryption: true })+ ).getPageCount()+ const name = file.name.replace(/\.pdf$/i, "") || "Imported stamps"++ stampCapability+ .loadLibrary({+ name,+ pdf: buffer,+ categories: ["sidebar"],+ stamps: Array.from({ length: pageCount }, (_, index) => ({+ id: `page-${index + 1}`,+ pageIndex: index,+ name: PdfAnnotationName.Custom,+ subject: `${name} ${index + 1}`,+ })),+ })+ .wait(+ (id) => {+ setBusy(false)+ setLibraryId(id)+ notify(+ `Imported ${pageCount} stamp${pageCount === 1 ? "" : "s"}.`,+ "success"+ )+ },+ () => {+ setBusy(false)+ notify("The stamp library could not be imported.", "error")+ }+ )+ } catch {+ setBusy(false)+ notify("The file could not be read as a PDF.", "error")+ }+ }++ return (+ <div className="flex h-full flex-col">+ <div className="shrink-0 space-y-2 border-b px-3 py-2">+ <div className="flex items-center gap-1.5">+ <Select+ items={libraryOptions}+ value={libraryId}+ onValueChange={(value) => setLibraryId(String(value))}+ >+ <SelectTrigger size="sm" className="min-w-0 flex-1">+ <SelectValue placeholder="Library" />+ </SelectTrigger>+ <SelectContent alignItemWithTrigger={false}>+ {libraryOptions.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <PdfEditorToolButton+ label="Import stamps from a PDF"+ disabled={busy}+ onClick={() => importInputRef.current?.click()}+ >+ <UploadGlyph className="size-4" />+ </PdfEditorToolButton>+ <PdfEditorToolButton+ label="Export library"+ disabled={+ busy ||+ (libraryId === "all"+ ? libraries.length === 0+ : !libraries.some((library) => library.id === libraryId))+ }+ onClick={() => {+ const targets =+ libraryId === "all"+ ? libraries.map((library) => library.id)+ : [libraryId]+ targets.forEach(exportLibrary)+ }}+ >+ <DownloadGlyph className="size-4" />+ </PdfEditorToolButton>+ </div>+ <Button+ type="button"+ size="sm"+ variant="outline"+ className="w-full"+ disabled={+ !canCreateFromSelection || busy || !permissions.canModifyAnnotations+ }+ onClick={createFromSelection}+ >+ <StampGlyph className="size-4" />+ Save selection as stamp+ </Button>+ <input+ ref={importInputRef}+ type="file"+ accept="application/pdf,.pdf"+ className="sr-only"+ tabIndex={-1}+ onChange={(event) => {+ const file = event.target.files?.[0]+ if (file) void importLibrary(file)+ event.currentTarget.value = ""+ }}+ />+ </div>+ {stamps.length === 0 ? (+ <PdfEditorEmptyState+ glyph={StampGlyph}+ title={libraries.length === 0 ? "Loading stamps…" : "No stamps"}+ description="Pick a library, import stamps from a PDF, or save a selected annotation as a stamp."+ />+ ) : (+ <PdfEditorScrollArea className="min-h-0 flex-1" viewportClassName="p-3">+ <div className="grid grid-cols-2 gap-2.5">+ {stamps.map(({ library, stamp }) => {+ const isActive =+ activeStamp?.libraryId === library.id &&+ activeStamp.stamp.id === stamp.id++ return (+ <div+ key={`${library.id}-${stamp.id}`}+ className="group relative"+ >+ <button+ type="button"+ aria-label={stamp.label ?? stamp.subject ?? "Rubber stamp"}+ aria-pressed={isActive}+ disabled={!permissions.canModifyAnnotations}+ className={cn(+ "flex aspect-square w-full items-center justify-center rounded-lg border p-2 transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",+ isActive+ ? "border-primary bg-primary/5 ring-1 ring-primary/40"+ : "hover:bg-accent/50"+ )}+ onClick={() => placeStamp(library.id, stamp)}+ >+ <StampImg+ libraryId={library.id}+ pageIndex={stamp.pageIndex}+ width={STAMP_THUMB_WIDTH}+ style={{+ maxWidth: "85%",+ maxHeight: "85%",+ objectFit: "contain",+ }}+ />+ </button>+ {!library.readonly ? (+ <button+ type="button"+ aria-label="Remove stamp"+ className="absolute top-1 right-1 grid size-5 place-items-center rounded-full border bg-background text-muted-foreground opacity-0 shadow-sm transition-opacity group-hover:opacity-100 hover:text-foreground focus-visible:opacity-100"+ onClick={() =>+ stampCapability+ ?.removeStampFromLibrary(library.id, stamp.id)+ .wait(+ () => undefined,+ () =>+ notify("The stamp could not be removed.", "error")+ )+ }+ >+ <TrashGlyph className="size-3" />+ </button>+ ) : null}+ </div>+ )+ })}+ </div>+ </PdfEditorScrollArea>+ )}+ {activeStamp ? (+ <div className="shrink-0 border-t px-3 py-2 text-xs text-muted-foreground">+ Click a page to place{" "}+ <span className="font-medium text-foreground">+ {activeStamp.stamp.subject}+ </span>+ .+ </div>+ ) : null}+ </div>+ )+}++/* -------------------------------------------------------------------------- */+/* Signatures */+/* -------------------------------------------------------------------------- */++export function PdfEditorSignaturesPanel({+ documentId,+}: {+ documentId: string+}) {+ const { entries, provides } = useSignatureEntries()+ const activePlacement = useActivePlacement(documentId)+ const { openDialog, permissions } = usePdfEditor()+ const canPlace = permissions.canModifyAnnotations++ const isActive = (entryId: string, kind: SignatureFieldKind) =>+ activePlacement?.entryId === entryId && activePlacement.kind === kind++ const togglePlacement = (entryId: string, kind: SignatureFieldKind) => {+ if (!provides) return++ const scope = provides.forDocument(documentId)++ if (isActive(entryId, kind)) {+ scope.deactivatePlacement()+ return+ }++ if (kind === SignatureFieldKind.Initials) {+ scope.activateInitialsPlacement(entryId)+ } else {+ scope.activateSignaturePlacement(entryId)+ }+ }++ return (+ <div className="flex h-full flex-col">+ <div className="shrink-0 border-b px-3 py-2">+ <Button+ type="button"+ size="sm"+ className="w-full"+ disabled={!canPlace}+ onClick={() => openDialog({ type: "signature" })}+ >+ <PlusGlyph className="size-4" />+ Create signature+ </Button>+ </div>+ {entries.length === 0 ? (+ <PdfEditorEmptyState+ glyph={SignatureGlyph}+ title="No signatures yet"+ description="Draw, type, or upload a signature, then click it to place it on the page."+ />+ ) : (+ <PdfEditorScrollArea className="min-h-0 flex-1" viewportClassName="p-3">+ <div className="space-y-3">+ {entries.map((entry) => (+ <div key={entry.id} className="space-y-2 rounded-lg border p-2.5">+ <div className="flex items-center justify-between">+ <span className="text-[11px] font-medium text-muted-foreground">+ Saved {formatRelativeDate(new Date(entry.createdAt))}+ </span>+ <PdfEditorToolButton+ label="Delete signature"+ size="icon-xs"+ onClick={() => provides?.removeEntry(entry.id)}+ >+ <TrashGlyph className="size-3.5" />+ </PdfEditorToolButton>+ </div>+ <div className="flex gap-2">+ <button+ type="button"+ disabled={!canPlace}+ aria-pressed={isActive(+ entry.id,+ SignatureFieldKind.Signature+ )}+ className={cn(+ "flex h-16 min-w-0 flex-[2] items-center justify-center rounded-md border border-dashed bg-white transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",+ isActive(entry.id, SignatureFieldKind.Signature)+ ? "border-primary ring-1 ring-primary/40"+ : "hover:border-muted-foreground/60"+ )}+ onClick={() =>+ togglePlacement(entry.id, SignatureFieldKind.Signature)+ }+ >+ <img+ src={entry.signature.previewDataUrl}+ alt="Signature"+ className="h-12 max-w-[90%] object-contain"+ />+ </button>+ {entry.initials ? (+ <button+ type="button"+ disabled={!canPlace}+ aria-pressed={isActive(+ entry.id,+ SignatureFieldKind.Initials+ )}+ className={cn(+ "flex h-16 min-w-0 flex-1 items-center justify-center rounded-md border border-dashed bg-white transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",+ isActive(entry.id, SignatureFieldKind.Initials)+ ? "border-primary ring-1 ring-primary/40"+ : "hover:border-muted-foreground/60"+ )}+ onClick={() =>+ togglePlacement(entry.id, SignatureFieldKind.Initials)+ }+ >+ <img+ src={entry.initials.previewDataUrl}+ alt="Initials"+ className="h-10 max-w-[80%] object-contain"+ />+ </button>+ ) : null}+ </div>+ </div>+ ))}+ </div>+ </PdfEditorScrollArea>+ )}+ {activePlacement ? (+ <div className="shrink-0 border-t px-3 py-2 text-xs text-muted-foreground">+ Click a page to place your{" "}+ {activePlacement.kind === SignatureFieldKind.Initials+ ? "initials"+ : "signature"}+ .+ </div>+ ) : null}+ </div>+ )+}++/* -------------------------------------------------------------------------- */+/* Forms */+/* -------------------------------------------------------------------------- */++export function PdfEditorFormsPanel({ documentId }: { documentId: string }) {+ const { provides: form } = useFormCapability()+ const { provides: annotation, state: annotationState } =+ useAnnotation(documentId)+ const {+ features,+ fileName,+ formDesignMode,+ notify,+ permissions,+ scrollToAnnotation,+ setFormDesignMode,+ } = usePdfEditor()+ const scope = React.useMemo(+ () => form?.forDocument(documentId) ?? null,+ [documentId, form]+ )+ const [fields, setFields] = React.useState<FormFieldInfo[]>([])+ const importInputRef = React.useRef<HTMLInputElement>(null)+ const designModeId = React.useId()++ React.useEffect(() => {+ if (!scope) return++ setFields(scope.getFormFields())++ const unsubscribeReady = scope.onFormReady((list) => setFields(list))+ const unsubscribeChange = scope.onFieldValueChange(() =>+ setFields(scope.getFormFields())+ )++ return () => {+ unsubscribeReady()+ unsubscribeChange()+ }+ }, [scope])++ const widgetsByName = React.useMemo(() => {+ const map = new Map<string, PdfWidgetAnnoObject>()++ for (const tracked of Object.values(annotationState.byUid)) {+ if (tracked.object.type !== PdfAnnotationSubtype.WIDGET) continue++ const widget = tracked.object as PdfWidgetAnnoObject++ if (!map.has(widget.field.name)) map.set(widget.field.name, widget)+ }++ return map+ }, [annotationState.byUid])++ const focusField = (field: FormFieldInfo) => {+ const widget = widgetsByName.get(field.name)++ if (!widget) return++ if (formDesignMode) {+ annotation?.selectAnnotation(widget.pageIndex, widget.id)+ } else {+ scope?.selectField(widget.id)+ }++ scrollToAnnotation(widget)+ }++ const exportValues = () => {+ if (!scope) return++ const values = scope.getFormValues()++ downloadBlob(+ new Blob([JSON.stringify(values, null, 2)], { type: "application/json" }),+ `${fileName.replace(/\.pdf$/i, "")}-form-values.json`+ )+ }++ const importValues = async (file: File) => {+ if (!scope) return++ try {+ const parsed = JSON.parse(await file.text()) as Record<string, unknown>+ const values = Object.fromEntries(+ Object.entries(parsed).map(([key, value]) => [key, String(value ?? "")])+ )++ scope.setFormValues(values).wait(+ () => notify("Form values imported.", "success"),+ () => notify("The form values could not be applied.", "error")+ )+ } catch {+ notify("The file is not valid JSON.", "error")+ }+ }++ const clearValues = () => {+ if (!scope || fields.length === 0) return++ const values = Object.fromEntries(+ fields.map((field) => [+ field.name,+ field.type === PDF_FORM_FIELD_TYPE.CHECKBOX ||+ field.type === PDF_FORM_FIELD_TYPE.RADIOBUTTON+ ? "Off"+ : "",+ ])+ )++ scope.setFormValues(values).wait(+ () => notify("Form cleared.", "success"),+ () => notify("The form could not be cleared.", "error")+ )+ }++ return (+ <div className="flex h-full flex-col">+ <div className="shrink-0 space-y-2 border-b px-3 py-2">+ {features.forms && permissions.canModifyAnnotations ? (+ <label+ htmlFor={designModeId}+ data-slot="label"+ className="flex cursor-pointer items-center justify-between gap-4 py-1"+ >+ <span className="flex min-w-0 flex-col gap-0.5">+ <span className="text-sm font-medium">Design mode</span>+ <span className="text-xs text-muted-foreground">+ Move, resize, and configure fields instead of filling them.+ </span>+ </span>+ <Switch+ id={designModeId}+ checked={formDesignMode}+ onCheckedChange={setFormDesignMode}+ />+ </label>+ ) : null}+ <div className="flex flex-wrap gap-1.5">+ <Button+ type="button"+ size="xs"+ variant="outline"+ disabled={fields.length === 0}+ onClick={exportValues}+ >+ <DownloadGlyph className="size-3.5" />+ Export values+ </Button>+ <Button+ type="button"+ size="xs"+ variant="outline"+ disabled={!permissions.canFillForms}+ onClick={() => importInputRef.current?.click()}+ >+ <UploadGlyph className="size-3.5" />+ Import values+ </Button>+ <Button+ type="button"+ size="xs"+ variant="outline"+ disabled={fields.length === 0 || !permissions.canFillForms}+ onClick={clearValues}+ >+ Clear+ </Button>+ </div>+ <input+ ref={importInputRef}+ type="file"+ accept="application/json,.json"+ className="sr-only"+ tabIndex={-1}+ onChange={(event) => {+ const file = event.target.files?.[0]+ if (file) void importValues(file)+ event.currentTarget.value = ""+ }}+ />+ </div>+ {fields.length === 0 ? (+ <PdfEditorEmptyState+ glyph={TextFieldGlyph}+ title="No form fields"+ description={+ features.forms+ ? "Switch to the Forms mode to add text fields, checkboxes, radio buttons, dropdowns, and list boxes."+ : "This document has no fillable fields."+ }+ />+ ) : (+ <PdfEditorScrollArea className="min-h-0 flex-1" viewportClassName="p-2">+ <div className="space-y-1">+ {fields.map((field) => (+ <button+ key={field.name}+ type="button"+ className="flex w-full items-center gap-2 rounded-lg border px-2.5 py-2 text-left outline-none hover:bg-accent/40 focus-visible:ring-2 focus-visible:ring-ring"+ onClick={() => focusField(field)}+ >+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-1.5">+ <span className="truncate text-sm font-medium">+ {field.name}+ </span>+ {field.readOnly ? (+ <Badge variant="outline" className="h-4 px-1 text-[10px]">+ Read only+ </Badge>+ ) : null}+ </div>+ <div className="truncate text-xs text-muted-foreground">+ {getFormFieldTypeLabel(field.type)}+ {field.value ? ` · ${field.value}` : ""}+ </div>+ </div>+ </button>+ ))}+ </div>+ </PdfEditorScrollArea>+ )}+ </div>+ )+}++export { GridGlyph as PdfEditorPagesGlyph }diff --git a/apps/v4/components/extend/pdf-editor-properties.tsx b/apps/v4/components/extend/pdf-editor-properties.tsxnew file mode 100644index 0000000..b8c6882--- /dev/null+++ b/apps/v4/components/extend/pdf-editor-properties.tsx@@ -0,0 +1,1977 @@+"use client"++import * as React from "react"+import {+ blendModeLabel,+ blendModeValues,+ makeStandardFont,+ PDF_FORM_FIELD_FLAG,+ PDF_FORM_FIELD_TYPE,+ PdfAnnotationBorderStyle,+ PdfAnnotationLineEnding,+ PdfAnnotationSubtype,+ PdfStandardFont,+ PdfStandardFontFamily,+ PdfTextAlignment,+ PdfVerticalAlignment,+ STANDARD_FONT_FAMILIES,+ standardFontFamily,+ standardFontIsBold,+ standardFontIsItalic,+ type LineEndings,+ type PdfAnnotationFlagName,+ type PdfAnnotationObject,+ type PdfTextWidgetAnnoField,+ type PdfWidgetAnnoField,+ type PdfWidgetAnnoObject,+ type PdfWidgetAnnoOption,+} from "@embedpdf/models"+import {+ getSelectedAnnotations,+ useAnnotation,+ useAnnotationCapability,+ type AnnotationTool,+ type TrackedAnnotation,+} from "@embedpdf/plugin-annotation/react"+import { useFormCapability } from "@embedpdf/plugin-form/react"++import { cn } from "@/lib/utils"+import { Button } from "@/components/ui/button"+import { ColorPicker } from "@/components/ui/color-picker"+import { Input } from "@/components/ui/input"+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select"+import { Switch } from "@/components/ui/switch"+import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle"+import {+ AlignBottomGlyph,+ AlignCenterGlyph,+ AlignLeftGlyph,+ AlignMiddleGlyph,+ AlignRightGlyph,+ AlignTopGlyph,+ BoldGlyph,+ formatDateTime,+ getAnnotationMeta,+ ItalicGlyph,+ PdfEditorEmptyState,+ PdfEditorFieldLabel,+ PdfEditorSection,+ PdfEditorSwatch,+ SlidersGlyph,+ TrashGlyph,+ usePdfEditor,+} from "@/components/extend/pdf-editor-shared"++/* -------------------------------------------------------------------------- */+/* Property schema */+/* -------------------------------------------------------------------------- */++type PropertyKind =+ | "color"+ | "colorWithTransparent"+ | "opacity"+ | "strokeWidth"+ | "strokeStyle"+ | "strokeStyleWithCloudy"+ | "linkStrokeStyle"+ | "lineEnding"+ | "lineEndings"+ | "fontFamily"+ | "fontSize"+ | "fontColor"+ | "textAlign"+ | "verticalAlign"+ | "blendMode"+ | "overlayText"+ | "rotation"++type PropertyConfig = {+ key: string+ kind: PropertyKind+ label: string+ /** Only shown while editing an existing annotation, never for tool defaults. */+ editOnly?: boolean+}++const PROPERTY_CONFIGS: Record<string, PropertyConfig> = {+ color: { key: "color", kind: "colorWithTransparent", label: "Fill" },+ strokeColor: {+ key: "strokeColor",+ kind: "colorWithTransparent",+ label: "Stroke",+ },+ markupColor: { key: "strokeColor", kind: "color", label: "Color" },+ opacity: { key: "opacity", kind: "opacity", label: "Opacity" },+ strokeWidth: {+ key: "strokeWidth",+ kind: "strokeWidth",+ label: "Stroke width",+ },+ strokeStyle: {+ key: "strokeStyle",+ kind: "strokeStyle",+ label: "Border style",+ },+ strokeStyleWithCloudy: {+ key: "strokeStyle",+ kind: "strokeStyleWithCloudy",+ label: "Border style",+ },+ linkStrokeStyle: {+ key: "strokeStyle",+ kind: "linkStrokeStyle",+ label: "Border style",+ },+ lineEnding: {+ key: "lineEnding",+ kind: "lineEnding",+ label: "Line ending",+ },+ lineEndings: {+ key: "lineEndings",+ kind: "lineEndings",+ label: "Line endings",+ },+ fontFamily: { key: "fontFamily", kind: "fontFamily", label: "Font" },+ fontSize: { key: "fontSize", kind: "fontSize", label: "Font size" },+ fontColor: { key: "fontColor", kind: "fontColor", label: "Text color" },+ textAlign: { key: "textAlign", kind: "textAlign", label: "Alignment" },+ verticalAlign: {+ key: "verticalAlign",+ kind: "verticalAlign",+ label: "Vertical alignment",+ },+ blendMode: { key: "blendMode", kind: "blendMode", label: "Blend mode" },+ overlayText: {+ key: "overlayText",+ kind: "overlayText",+ label: "Overlay text",+ },+ rotation: {+ key: "rotation",+ kind: "rotation",+ label: "Rotation",+ editOnly: true,+ },+}++/** Ordered property lists keyed by EmbedPDF tool id. */+const TOOL_PROPERTIES: Record<string, string[]> = {+ highlight: ["markupColor", "opacity", "blendMode"],+ underline: ["markupColor", "opacity", "blendMode"],+ strikeout: ["markupColor", "opacity", "blendMode"],+ squiggly: ["markupColor", "opacity", "blendMode"],+ ink: ["markupColor", "opacity", "strokeWidth", "rotation"],+ inkHighlighter: [+ "markupColor",+ "opacity",+ "strokeWidth",+ "blendMode",+ "rotation",+ ],+ signatureInk: ["markupColor", "opacity", "strokeWidth", "rotation"],+ circle: [+ "color",+ "opacity",+ "strokeColor",+ "strokeStyleWithCloudy",+ "strokeWidth",+ "rotation",+ ],+ square: [+ "color",+ "opacity",+ "strokeColor",+ "strokeStyleWithCloudy",+ "strokeWidth",+ "rotation",+ ],+ polygon: [+ "strokeColor",+ "opacity",+ "strokeStyleWithCloudy",+ "strokeWidth",+ "color",+ "rotation",+ ],+ line: [+ "strokeColor",+ "opacity",+ "strokeStyle",+ "strokeWidth",+ "lineEndings",+ "color",+ "rotation",+ ],+ lineArrow: [+ "strokeColor",+ "opacity",+ "strokeStyle",+ "strokeWidth",+ "lineEndings",+ "color",+ "rotation",+ ],+ polyline: [+ "strokeColor",+ "opacity",+ "strokeStyle",+ "strokeWidth",+ "lineEndings",+ "color",+ "rotation",+ ],+ textComment: ["markupColor", "opacity"],+ insertText: ["markupColor", "opacity"],+ replaceText: ["markupColor", "opacity"],+ freeText: [+ "fontFamily",+ "fontSize",+ "fontColor",+ "textAlign",+ "verticalAlign",+ "opacity",+ "color",+ "rotation",+ ],+ freeTextCallout: [+ "fontFamily",+ "fontSize",+ "fontColor",+ "textAlign",+ "verticalAlign",+ "opacity",+ "color",+ "markupColor",+ "strokeWidth",+ "lineEnding",+ ],+ stamp: ["rotation"],+ rubberStamp: ["rotation"],+ signatureStamp: ["rotation"],+ redact: ["strokeColor", "color", "opacity", "overlayText"],+ link: ["strokeColor", "strokeWidth", "linkStrokeStyle"],+ formTextField: [+ "fontSize",+ "fontColor",+ "strokeColor",+ "strokeWidth",+ "color",+ ],+ formCheckbox: ["strokeColor", "color", "strokeWidth"],+ formCombobox: [+ "fontSize",+ "fontColor",+ "strokeColor",+ "strokeWidth",+ "color",+ ],+ formListbox: [+ "fontFamily",+ "fontSize",+ "fontColor",+ "strokeColor",+ "strokeWidth",+ "color",+ ],+ formRadioButton: ["strokeColor", "color", "strokeWidth"],+}++function getSharedProperties(toolIds: string[]) {+ const unique = [...new Set(toolIds)]++ if (unique.length === 0) return []++ const first = new Set(TOOL_PROPERTIES[unique[0]] ?? [])++ for (const id of unique.slice(1)) {+ const own = new Set(TOOL_PROPERTIES[id] ?? [])+ for (const property of first) {+ if (!own.has(property)) first.delete(property)+ }+ }++ return (TOOL_PROPERTIES[unique[0]] ?? []).filter((property) =>+ first.has(property)+ )+}++const FONT_SIZE_PRESETS = [+ 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48, 72,+]++const LINE_ENDING_OPTIONS: Array<{+ value: PdfAnnotationLineEnding+ label: string+}> = [+ { value: PdfAnnotationLineEnding.None, label: "None" },+ { value: PdfAnnotationLineEnding.OpenArrow, label: "Open arrow" },+ { value: PdfAnnotationLineEnding.ClosedArrow, label: "Closed arrow" },+ { value: PdfAnnotationLineEnding.ROpenArrow, label: "Reverse open arrow" },+ {+ value: PdfAnnotationLineEnding.RClosedArrow,+ label: "Reverse closed arrow",+ },+ { value: PdfAnnotationLineEnding.Square, label: "Square" },+ { value: PdfAnnotationLineEnding.Circle, label: "Circle" },+ { value: PdfAnnotationLineEnding.Diamond, label: "Diamond" },+ { value: PdfAnnotationLineEnding.Butt, label: "Butt" },+ { value: PdfAnnotationLineEnding.Slash, label: "Slash" },+]++const FLAG_OPTIONS: Array<{+ flag: PdfAnnotationFlagName+ label: string+ description: string+}> = [+ {+ flag: "locked",+ label: "Lock position",+ description: "Prevents moving, resizing, and deleting.",+ },+ {+ flag: "lockedContents",+ label: "Lock contents",+ description: "Prevents editing the text.",+ },+ {+ flag: "print",+ label: "Print",+ description: "Include when printing.",+ },+]++/* -------------------------------------------------------------------------- */+/* Controls */+/* -------------------------------------------------------------------------- */++function useDebouncedCommit<T>(+ value: T,+ onCommit: (value: T) => void,+ delay = 150+) {+ const [draft, setDraft] = React.useState(value)+ const timeoutRef = React.useRef<number | null>(null)+ const onCommitRef = React.useRef(onCommit)++ React.useEffect(() => {+ onCommitRef.current = onCommit+ })++ React.useEffect(() => {+ setDraft(value)+ }, [value])++ React.useEffect(+ () => () => {+ if (timeoutRef.current !== null) window.clearTimeout(timeoutRef.current)+ },+ []+ )++ const update = React.useCallback(+ (next: T) => {+ setDraft(next)++ if (timeoutRef.current !== null) window.clearTimeout(timeoutRef.current)++ timeoutRef.current = window.setTimeout(() => {+ timeoutRef.current = null+ onCommitRef.current(next)+ }, delay)+ },+ [delay]+ )++ return [draft, update] as const+}++function PropertySwitch({+ checked,+ disabled,+ label,+ description,+ onCheckedChange,+}: {+ checked: boolean+ disabled?: boolean+ label: React.ReactNode+ description?: React.ReactNode+ onCheckedChange: (checked: boolean) => void+}) {+ const id = React.useId()++ return (+ <label+ htmlFor={id}+ data-slot="label"+ className={cn(+ "flex items-center justify-between gap-4 rounded-md px-1 py-1",+ disabled ? "cursor-not-allowed opacity-64" : "cursor-pointer"+ )}+ >+ <span className="min-w-0">+ <span className="block text-sm leading-4">{label}</span>+ {description ? (+ <span className="block text-xs text-muted-foreground">+ {description}+ </span>+ ) : null}+ </span>+ <Switch+ id={id}+ checked={checked}+ disabled={disabled}+ onCheckedChange={onCheckedChange}+ />+ </label>+ )+}++function ColorControl({+ label,+ value,+ presets,+ allowTransparent,+ onChange,+}: {+ label: string+ value: string | undefined+ presets: string[]+ allowTransparent: boolean+ onChange: (value: string) => void+}) {+ const current = (value ?? "").toLowerCase()+ const isTransparent = !value || current === "transparent"+ const pickerSource = isTransparent ? "#111827" : (value ?? "#111827")++ return (+ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <PdfEditorFieldLabel>{label}</PdfEditorFieldLabel>+ <span className="text-[11px] text-muted-foreground tabular-nums">+ {isTransparent ? "None" : current}+ </span>+ </div>+ <div className="flex flex-wrap items-center gap-1.5">+ {presets.map((preset) => (+ <PdfEditorSwatch+ key={preset}+ color={preset}+ active={!isTransparent && current === preset.toLowerCase()}+ onClick={() => onChange(preset)}+ />+ ))}+ {allowTransparent ? (+ <PdfEditorSwatch+ color="transparent"+ label="No fill"+ active={isTransparent}+ onClick={() => onChange("transparent")}+ />+ ) : null}+ <ColorPicker+ label={`Custom ${label.toLowerCase()}`}+ rainbowTrigger+ color={pickerSource}+ onChange={onChange}+ />+ </div>+ </div>+ )+}++function SliderControl({+ label,+ value,+ min,+ max,+ step,+ format,+ onChange,+}: {+ label: string+ value: number+ min: number+ max: number+ step: number+ format: (value: number) => string+ onChange: (value: number) => void+}) {+ const [draft, update] = useDebouncedCommit(value, onChange)++ return (+ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <PdfEditorFieldLabel>{label}</PdfEditorFieldLabel>+ <span className="text-[11px] text-muted-foreground tabular-nums">+ {format(draft)}+ </span>+ </div>+ <input+ type="range"+ min={min}+ max={max}+ step={step}+ value={draft}+ aria-label={label}+ onChange={(event) => update(Number(event.target.value))}+ className="h-1.5 w-full cursor-pointer appearance-none rounded-full bg-muted accent-primary"+ />+ </div>+ )+}++type StrokeStyleValue =+ | "solid"+ | "dotted"+ | "short-dashed"+ | "dashed"+ | "long-dashed"+ | "dash-dot"+ | "long-dash-dot"+ | "dash-dot-dot"+ | "cloudy-1"+ | "cloudy-2"+ | "underline"+ | "custom"++const STROKE_STYLE_PRESETS: Array<{+ value: Exclude<+ StrokeStyleValue,+ "cloudy-1" | "cloudy-2" | "underline" | "custom"+ >+ label: string+ dashArray?: number[]+}> = [+ { value: "solid", label: "Solid" },+ { value: "dotted", label: "Dotted", dashArray: [1, 2] },+ { value: "short-dashed", label: "Short dashed", dashArray: [2, 2] },+ { value: "dashed", label: "Dashed", dashArray: [4, 3] },+ { value: "long-dashed", label: "Long dashed", dashArray: [8, 4] },+ { value: "dash-dot", label: "Dash dot", dashArray: [6, 3, 1, 3] },+ {+ value: "long-dash-dot",+ label: "Long dash dot",+ dashArray: [10, 4, 1, 4],+ },+ {+ value: "dash-dot-dot",+ label: "Dash dot dot",+ dashArray: [6, 3, 1, 3, 1, 3],+ },+]++function getStrokeDashArray(value: StrokeStyleValue) {+ return STROKE_STYLE_PRESETS.find((preset) => preset.value === value)+ ?.dashArray+}++function StrokeStylePreview({+ value,+ dashArray,+}: {+ value: StrokeStyleValue+ dashArray?: number[]+}) {+ const path =+ value === "cloudy-2"+ ? "M1 8 Q3 2 5 8 Q7 2 9 8 Q11 2 13 8 Q15 2 17 8 Q19 2 21 8 Q23 2 25 8 Q27 2 29 8 Q31 2 33 8 Q35 2 37 8 Q39 2 41 8 Q43 2 45 8 Q47 2 49 8 Q51 2 55 8"+ : "M1 8 Q5 1 9 8 Q13 1 17 8 Q21 1 25 8 Q29 1 33 8 Q37 1 41 8 Q45 1 49 8 Q53 1 55 8"+ const resolvedDashArray = dashArray ?? getStrokeDashArray(value)++ return (+ <svg+ aria-hidden="true"+ viewBox="0 0 56 12"+ className="h-6! w-24! shrink-0 text-foreground"+ >+ <path+ d={value.startsWith("cloudy") ? path : "M1 6H55"}+ fill="none"+ stroke="currentColor"+ strokeDasharray={resolvedDashArray?.join(" ")}+ strokeLinecap="round"+ strokeWidth="2.25"+ />+ </svg>+ )+}++function SelectControl({+ label,+ value,+ options,+ onChange,+}: {+ label: string+ value: string+ options: Array<{+ value: string+ label: string+ preview?: React.ReactNode+ }>+ onChange: (value: string) => void+}) {+ const selectedOption =+ options.find((option) => option.value === value) ?? null++ return (+ <div className="space-y-1.5">+ <PdfEditorFieldLabel>{label}</PdfEditorFieldLabel>+ <Select+ items={options}+ value={value}+ onValueChange={(next) => {+ if (next) onChange(String(next))+ }}+ >+ <SelectTrigger size="sm" className="w-full">+ <SelectValue placeholder={label}>+ {selectedOption ? (+ <span className="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-3">+ <span className="truncate">{selectedOption.label}</span>+ {selectedOption.preview}+ </span>+ ) : (+ label+ )}+ </SelectValue>+ </SelectTrigger>+ <SelectContent alignItemWithTrigger={false}>+ {options.map((option) => (+ <SelectItem+ key={option.value}+ value={option.value}+ className={cn(option.preview && "py-0.5 pe-2")}+ >+ <span className="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-3">+ <span className="truncate">{option.label}</span>+ {option.preview}+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ )+}++function getStrokeStyleValue(+ strokeStyle: PdfAnnotationBorderStyle | undefined,+ cloudyBorderIntensity: number | undefined,+ strokeDashArray: number[] | undefined+): StrokeStyleValue {+ if (+ strokeStyle === PdfAnnotationBorderStyle.CLOUDY ||+ (cloudyBorderIntensity ?? 0) > 0+ ) {+ return (cloudyBorderIntensity ?? 1) >= 2 ? "cloudy-2" : "cloudy-1"+ }++ if (strokeStyle === PdfAnnotationBorderStyle.UNDERLINE) return "underline"++ if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {+ const preset = STROKE_STYLE_PRESETS.find((item) => {+ if (!item.dashArray || !strokeDashArray) return false+ if (item.dashArray.length !== strokeDashArray.length) return false++ return item.dashArray.every(+ (part, index) => part === strokeDashArray[index]+ )+ })++ return preset?.value ?? "custom"+ }++ return "solid"+}++function getStrokeStylePatch(+ value: StrokeStyleValue,+ customDashArray?: number[]+) {+ const dashArray = getStrokeDashArray(value)++ if (dashArray || value === "custom") {+ return {+ strokeStyle: PdfAnnotationBorderStyle.DASHED,+ strokeDashArray: dashArray ?? customDashArray ?? [4, 3],+ cloudyBorderIntensity: 0,+ }+ }++ switch (value) {+ case "underline":+ return {+ strokeStyle: PdfAnnotationBorderStyle.UNDERLINE,+ strokeDashArray: undefined,+ cloudyBorderIntensity: 0,+ }+ case "cloudy-1":+ return {+ strokeStyle: PdfAnnotationBorderStyle.CLOUDY,+ strokeDashArray: undefined,+ cloudyBorderIntensity: 1,+ }+ case "cloudy-2":+ return {+ strokeStyle: PdfAnnotationBorderStyle.CLOUDY,+ strokeDashArray: undefined,+ cloudyBorderIntensity: 2,+ }+ default:+ return {+ strokeStyle: PdfAnnotationBorderStyle.SOLID,+ strokeDashArray: undefined,+ cloudyBorderIntensity: 0,+ }+ }+}++function FontControl({+ value,+ onChange,+}: {+ value: PdfStandardFont | undefined+ onChange: (value: PdfStandardFont) => void+}) {+ const font = value ?? PdfStandardFont.Helvetica+ const family = standardFontFamily(font)+ const bold = standardFontIsBold(font)+ const italic = standardFontIsItalic(font)+ const supportsStyles =+ family !== PdfStandardFontFamily.Symbol &&+ family !== PdfStandardFontFamily.ZapfDingbats+ const familyOptions = STANDARD_FONT_FAMILIES.filter(+ (item) => item !== PdfStandardFontFamily.Unknown+ ).map((item) => ({ label: item, value: item }))++ const apply = (+ nextFamily: PdfStandardFontFamily,+ nextBold: boolean,+ nextItalic: boolean+ ) => {+ const next =+ makeStandardFont(nextFamily, { bold: nextBold, italic: nextItalic }) ??+ makeStandardFont(nextFamily, { bold: false, italic: false })++ if (next !== undefined && next !== PdfStandardFont.Unknown) onChange(next)+ }++ return (+ <div className="space-y-1.5">+ <PdfEditorFieldLabel>Font</PdfEditorFieldLabel>+ <div className="flex items-center gap-1.5">+ <Select+ items={familyOptions}+ value={family}+ onValueChange={(next) =>+ apply(String(next) as PdfStandardFontFamily, bold, italic)+ }+ >+ <SelectTrigger size="sm" className="min-w-0 flex-1">+ <SelectValue placeholder="Font" />+ </SelectTrigger>+ <SelectContent alignItemWithTrigger={false}>+ {familyOptions.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <ToggleGroup+ multiple+ value={[bold ? "bold" : "", italic ? "italic" : ""].filter(Boolean)}+ onValueChange={(next: string[]) =>+ apply(family, next.includes("bold"), next.includes("italic"))+ }+ spacing="none"+ className="shrink-0"+ >+ <ToggleGroupItem+ value="bold"+ size="sm"+ variant="outline"+ aria-label="Bold"+ disabled={!supportsStyles}+ >+ <BoldGlyph className="size-3.5" />+ </ToggleGroupItem>+ <ToggleGroupItem+ value="italic"+ size="sm"+ variant="outline"+ aria-label="Italic"+ disabled={!supportsStyles}+ >+ <ItalicGlyph className="size-3.5" />+ </ToggleGroupItem>+ </ToggleGroup>+ </div>+ </div>+ )+}++function FontSizeControl({+ value,+ onChange,+}: {+ value: number | undefined+ onChange: (value: number) => void+}) {+ const [draft, update] = useDebouncedCommit(value ?? 12, onChange, 250)+ const sizeOptions = (+ FONT_SIZE_PRESETS.includes(draft)+ ? FONT_SIZE_PRESETS+ : [...FONT_SIZE_PRESETS, draft].sort((a, b) => a - b)+ ).map((size) => ({ label: `${size} pt`, value: String(size) }))++ return (+ <div className="space-y-1.5">+ <PdfEditorFieldLabel>Font size</PdfEditorFieldLabel>+ <div className="flex items-center gap-1.5">+ <Input+ type="number"+ size="sm"+ min={4}+ max={200}+ value={draft}+ className="w-20"+ onChange={(event: React.ChangeEvent<HTMLInputElement>) => {+ const next = Number(event.target.value)+ if (Number.isFinite(next) && next > 0) update(next)+ }}+ />+ <Select+ items={sizeOptions}+ value={String(draft)}+ onValueChange={(next) => onChange(Number(next))}+ >+ <SelectTrigger size="sm" className="min-w-0 flex-1">+ <SelectValue placeholder="Size" />+ </SelectTrigger>+ <SelectContent alignItemWithTrigger={false}>+ {sizeOptions.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ </div>+ )+}++function AlignControl({+ label,+ value,+ onChange,+ options,+}: {+ label: string+ value: string+ onChange: (value: string) => void+ options: Array<{ value: string; label: string; glyph: React.ReactNode }>+}) {+ return (+ <div className="space-y-1.5">+ <PdfEditorFieldLabel>{label}</PdfEditorFieldLabel>+ <ToggleGroup+ value={[value]}+ onValueChange={(next: string[]) => {+ const selected = next[0]+ if (selected !== undefined) onChange(selected)+ }}+ spacing="none"+ >+ {options.map((option) => (+ <ToggleGroupItem+ key={option.value}+ value={option.value}+ size="sm"+ variant="outline"+ aria-label={option.label}+ >+ {option.glyph}+ </ToggleGroupItem>+ ))}+ </ToggleGroup>+ </div>+ )+}++function LineEndingPreview({ value }: { value: PdfAnnotationLineEnding }) {+ const isOpenArrow =+ value === PdfAnnotationLineEnding.OpenArrow ||+ value === PdfAnnotationLineEnding.ROpenArrow+ const isClosedArrow =+ value === PdfAnnotationLineEnding.ClosedArrow ||+ value === PdfAnnotationLineEnding.RClosedArrow+ const isReverse =+ value === PdfAnnotationLineEnding.ROpenArrow ||+ value === PdfAnnotationLineEnding.RClosedArrow+ const lineEndX = isReverse+ ? isClosedArrow+ ? 58+ : 56+ : isClosedArrow+ ? 68+ : 66++ return (+ <svg+ aria-hidden="true"+ viewBox="0 0 72 16"+ className="h-6! w-24! shrink-0 text-foreground"+ >+ <path+ d={`M2 8H${lineEndX}`}+ fill="none"+ stroke="currentColor"+ strokeLinecap="round"+ strokeWidth="2.5"+ />+ {isOpenArrow ? (+ <path+ d={isReverse ? "M56 8 66 2M56 8l10 6" : "M66 8 56 2M66 8l-10 6"}+ fill="none"+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="2.5"+ />+ ) : null}+ {isClosedArrow ? (+ <path+ d={isReverse ? "m58 8 10-6v12Z" : "m68 8-10-6v12Z"}+ fill="currentColor"+ />+ ) : null}+ {value === PdfAnnotationLineEnding.Square ? (+ <rect x="60" y="2" width="12" height="12" fill="currentColor" />+ ) : null}+ {value === PdfAnnotationLineEnding.Circle ? (+ <circle cx="66" cy="8" r="6" fill="currentColor" />+ ) : null}+ {value === PdfAnnotationLineEnding.Diamond ? (+ <path d="m66 2 6 6-6 6-6-6Z" fill="currentColor" />+ ) : null}+ {value === PdfAnnotationLineEnding.Butt ? (+ <path d="M66 2v12" stroke="currentColor" strokeWidth="2.5" />+ ) : null}+ {value === PdfAnnotationLineEnding.Slash ? (+ <path d="m60 14 12-12" stroke="currentColor" strokeWidth="2.5" />+ ) : null}+ </svg>+ )+}++function LineEndingsControl({+ value,+ onChange,+}: {+ value: LineEndings | undefined+ onChange: (value: LineEndings) => void+}) {+ const start = value?.start ?? PdfAnnotationLineEnding.None+ const end = value?.end ?? PdfAnnotationLineEnding.None+ const options = LINE_ENDING_OPTIONS.map((option) => ({+ value: String(option.value),+ label: option.label,+ preview: <LineEndingPreview value={option.value} />,+ }))++ return (+ <div className="space-y-2">+ <SelectControl+ label="Line start"+ value={String(start)}+ options={options}+ onChange={(next) =>+ onChange({ start: Number(next) as PdfAnnotationLineEnding, end })+ }+ />+ <SelectControl+ label="Line end"+ value={String(end)}+ options={options}+ onChange={(next) =>+ onChange({ start, end: Number(next) as PdfAnnotationLineEnding })+ }+ />+ </div>+ )+}++function LineEndingControl({+ label,+ value,+ onChange,+}: {+ label: string+ value: PdfAnnotationLineEnding | undefined+ onChange: (value: PdfAnnotationLineEnding) => void+}) {+ const options = LINE_ENDING_OPTIONS.map((option) => ({+ value: String(option.value),+ label: option.label,+ preview: <LineEndingPreview value={option.value} />,+ }))++ return (+ <SelectControl+ label={label}+ value={String(value ?? PdfAnnotationLineEnding.None)}+ options={options}+ onChange={(next) => onChange(Number(next) as PdfAnnotationLineEnding)}+ />+ )+}++function TextControl({+ label,+ value,+ placeholder,+ onChange,+}: {+ label: string+ value: string+ placeholder?: string+ onChange: (value: string) => void+}) {+ const [draft, update] = useDebouncedCommit(value, onChange, 400)++ return (+ <div className="space-y-1.5">+ <PdfEditorFieldLabel>{label}</PdfEditorFieldLabel>+ <Input+ size="sm"+ value={draft}+ placeholder={placeholder}+ onChange={(event: React.ChangeEvent<HTMLInputElement>) =>+ update(event.target.value)+ }+ />+ </div>+ )+}++function RotationControl({+ value,+ onChange,+}: {+ value: number+ onChange: (value: number) => void+}) {+ const [draft, update] = useDebouncedCommit(value, onChange, 250)++ return (+ <div className="space-y-1.5">+ <PdfEditorFieldLabel>Rotation</PdfEditorFieldLabel>+ <div className="flex items-center gap-1.5">+ <Input+ type="number"+ size="sm"+ min={0}+ max={359}+ value={Math.round(draft)}+ className="w-20"+ onChange={(event: React.ChangeEvent<HTMLInputElement>) =>+ update(((Number(event.target.value) % 360) + 360) % 360)+ }+ />+ <span className="text-xs text-muted-foreground">degrees</span>+ {[0, 90, 180, 270].map((preset) => (+ <Button+ key={preset}+ type="button"+ size="xs"+ variant={draft === preset ? "secondary" : "ghost"}+ onClick={() => {+ update(preset)+ }}+ >+ {preset}°+ </Button>+ ))}+ </div>+ </div>+ )+}++/* -------------------------------------------------------------------------- */+/* Property list */+/* -------------------------------------------------------------------------- */++function PropertyControl({+ config,+ values,+ colorPresets,+ onPatch,+ onRotate,+}: {+ config: PropertyConfig+ values: Record<string, unknown>+ colorPresets: string[]+ onPatch: (patch: Record<string, unknown>) => void+ onRotate?: (rotation: number) => void+}) {+ const value = values[config.key]++ switch (config.kind) {+ case "color":+ case "colorWithTransparent":+ case "fontColor":+ return (+ <ColorControl+ label={config.label}+ value={typeof value === "string" ? value : undefined}+ presets={colorPresets}+ allowTransparent={config.kind === "colorWithTransparent"}+ onChange={(next) => onPatch({ [config.key]: next })}+ />+ )+ case "opacity":+ return (+ <SliderControl+ label={config.label}+ value={typeof value === "number" ? value : 1}+ min={0}+ max={1}+ step={0.05}+ format={(item) => `${Math.round(item * 100)}%`}+ onChange={(next) => onPatch({ [config.key]: next })}+ />+ )+ case "strokeWidth":+ return (+ <SliderControl+ label={config.label}+ value={typeof value === "number" ? value : 1}+ min={1}+ max={30}+ step={1}+ format={(item) => `${item} pt`}+ onChange={(next) => onPatch({ [config.key]: next })}+ />+ )+ case "strokeStyle":+ case "strokeStyleWithCloudy":+ case "linkStrokeStyle": {+ const strokeDashArray = values.strokeDashArray as number[] | undefined+ const selectedValue = getStrokeStyleValue(+ value as PdfAnnotationBorderStyle | undefined,+ values.cloudyBorderIntensity as number | undefined,+ strokeDashArray+ )+ const options: Array<{+ value: string+ label: string+ preview: React.ReactNode+ }> = STROKE_STYLE_PRESETS.map((preset) => ({+ value: preset.value,+ label: preset.label,+ preview: (+ <StrokeStylePreview+ value={preset.value}+ dashArray={preset.dashArray}+ />+ ),+ }))++ if (config.kind === "linkStrokeStyle") {+ options.splice(1, 0, {+ value: "underline",+ label: "Underline",+ preview: <StrokeStylePreview value="underline" />,+ })+ }++ if (config.kind === "strokeStyleWithCloudy") {+ options.push(+ {+ value: "cloudy-1",+ label: "Cloudy",+ preview: <StrokeStylePreview value="cloudy-1" />,+ },+ {+ value: "cloudy-2",+ label: "Cloudy (dense)",+ preview: <StrokeStylePreview value="cloudy-2" />,+ }+ )+ }++ if (selectedValue === "custom") {+ options.push({+ value: "custom",+ label: "Custom dashed",+ preview: (+ <StrokeStylePreview value="custom" dashArray={strokeDashArray} />+ ),+ })+ }++ return (+ <SelectControl+ label={config.label}+ value={selectedValue}+ options={options}+ onChange={(next) =>+ onPatch(+ getStrokeStylePatch(next as StrokeStyleValue, strokeDashArray)+ )+ }+ />+ )+ }+ case "lineEnding":+ return (+ <LineEndingControl+ label={config.label}+ value={value as PdfAnnotationLineEnding | undefined}+ onChange={(next) => onPatch({ [config.key]: next })}+ />+ )+ case "lineEndings":+ return (+ <LineEndingsControl+ value={value as LineEndings | undefined}+ onChange={(next) => onPatch({ lineEndings: next })}+ />+ )+ case "fontFamily":+ return (+ <FontControl+ value={value as PdfStandardFont | undefined}+ onChange={(next) => onPatch({ fontFamily: next })}+ />+ )+ case "fontSize":+ return (+ <FontSizeControl+ value={typeof value === "number" ? value : undefined}+ onChange={(next) => onPatch({ fontSize: next })}+ />+ )+ case "textAlign":+ return (+ <AlignControl+ label={config.label}+ value={String(value ?? PdfTextAlignment.Left)}+ onChange={(next) => onPatch({ textAlign: Number(next) })}+ options={[+ {+ value: String(PdfTextAlignment.Left),+ label: "Align left",+ glyph: <AlignLeftGlyph className="size-3.5" />,+ },+ {+ value: String(PdfTextAlignment.Center),+ label: "Align center",+ glyph: <AlignCenterGlyph className="size-3.5" />,+ },+ {+ value: String(PdfTextAlignment.Right),+ label: "Align right",+ glyph: <AlignRightGlyph className="size-3.5" />,+ },+ ]}+ />+ )+ case "verticalAlign":+ return (+ <AlignControl+ label={config.label}+ value={String(value ?? PdfVerticalAlignment.Top)}+ onChange={(next) => onPatch({ verticalAlign: Number(next) })}+ options={[+ {+ value: String(PdfVerticalAlignment.Top),+ label: "Align top",+ glyph: <AlignTopGlyph className="size-3.5" />,+ },+ {+ value: String(PdfVerticalAlignment.Middle),+ label: "Align middle",+ glyph: <AlignMiddleGlyph className="size-3.5" />,+ },+ {+ value: String(PdfVerticalAlignment.Bottom),+ label: "Align bottom",+ glyph: <AlignBottomGlyph className="size-3.5" />,+ },+ ]}+ />+ )+ case "blendMode":+ return (+ <SelectControl+ label={config.label}+ value={String(value ?? 0)}+ options={blendModeValues.map((mode) => ({+ value: String(mode),+ label: blendModeLabel(mode),+ }))}+ onChange={(next) => onPatch({ blendMode: Number(next) })}+ />+ )+ case "overlayText":+ return (+ <TextControl+ label={config.label}+ value={typeof value === "string" ? value : ""}+ placeholder="e.g. REDACTED"+ onChange={(next) => onPatch({ overlayText: next })}+ />+ )+ case "rotation":+ return (+ <RotationControl+ value={typeof value === "number" ? value : 0}+ onChange={(next) =>+ onRotate ? onRotate(next) : onPatch({ rotation: next })+ }+ />+ )+ default:+ return null+ }+}++/* -------------------------------------------------------------------------- */+/* Widget (form field) properties */+/* -------------------------------------------------------------------------- */++const FIELD_TYPE_LABELS: Partial<Record<PDF_FORM_FIELD_TYPE, string>> = {+ [PDF_FORM_FIELD_TYPE.TEXTFIELD]: "Text field",+ [PDF_FORM_FIELD_TYPE.CHECKBOX]: "Checkbox",+ [PDF_FORM_FIELD_TYPE.RADIOBUTTON]: "Radio button",+ [PDF_FORM_FIELD_TYPE.COMBOBOX]: "Dropdown",+ [PDF_FORM_FIELD_TYPE.LISTBOX]: "List box",+ [PDF_FORM_FIELD_TYPE.PUSHBUTTON]: "Button",+ [PDF_FORM_FIELD_TYPE.SIGNATURE]: "Signature field",+}++export function getFormFieldTypeLabel(type: PDF_FORM_FIELD_TYPE) {+ return FIELD_TYPE_LABELS[type] ?? "Form field"+}++function WidgetProperties({+ documentId,+ widget,+}: {+ documentId: string+ widget: PdfWidgetAnnoObject+}) {+ const { provides: annotation } = useAnnotation(documentId)+ const { provides: form } = useFormCapability()+ const { openDialog, notify } = usePdfEditor()+ const [nameDraft, setNameDraft] = React.useState(widget.field.name)+ const [nameError, setNameError] = React.useState<string | null>(null)+ const field = widget.field+ const fieldLabel = getFormFieldTypeLabel(field.type)++ React.useEffect(() => {+ setNameDraft(widget.field.name)+ setNameError(null)+ }, [widget.field.name, widget.id])++ const updateField = React.useCallback(+ (patch: Partial<PdfWidgetAnnoField>) => {+ annotation?.updateAnnotations([+ {+ pageIndex: widget.pageIndex,+ id: widget.id,+ patch: { field: { ...widget.field, ...patch } as PdfWidgetAnnoField },+ },+ ])+ },+ [annotation, widget.field, widget.id, widget.pageIndex]+ )++ const toggleFlag = (flag: PDF_FORM_FIELD_FLAG, enabled: boolean) => {+ const current = field.flag ?? PDF_FORM_FIELD_FLAG.NONE+ updateField({ flag: enabled ? current | flag : current & ~flag })+ }++ const commitName = () => {+ const nextName = nameDraft.trim()++ if (!form || !nextName || nextName === field.name) {+ setNameDraft(field.name)+ return+ }++ form.renameField(widget.id, nextName, documentId).wait(+ (result) => {+ setNameError(null)++ if (result.outcome === "conflict") {+ openDialog({+ type: "confirm",+ title: "Share this field?",+ description: `A ${fieldLabel.toLowerCase()} named "${result.fieldName}" already exists. Sharing makes both widgets show the same value.`,+ confirmLabel: "Share field",+ onConfirm: () => {+ form+ .shareField(widget.id, result.targetAnnotationId, documentId)+ .wait(+ () => notify("Field shared.", "success"),+ (failure) => {+ setNameError(failure.reason.message)+ setNameDraft(field.name)+ }+ )+ },+ })+ }+ },+ (failure) => {+ setNameError(failure.reason.message)+ setNameDraft(field.name)+ }+ )+ }++ const options: PdfWidgetAnnoOption[] =+ field.type === PDF_FORM_FIELD_TYPE.COMBOBOX ||+ field.type === PDF_FORM_FIELD_TYPE.LISTBOX+ ? ((field as { options?: PdfWidgetAnnoOption[] }).options ?? [])+ : []+ const setOptions = (next: PdfWidgetAnnoOption[]) =>+ updateField({ options: next } as Partial<PdfWidgetAnnoField>)++ const isTextField = field.type === PDF_FORM_FIELD_TYPE.TEXTFIELD+ const textField = field as PdfTextWidgetAnnoField+ const maxLength = isTextField ? (textField.maxLen ?? 0) : 0+ const isComb = Boolean(field.flag & PDF_FORM_FIELD_FLAG.TEXT_COMB)++ return (+ <PdfEditorSection title={`${fieldLabel} settings`}>+ <div className="space-y-3">+ <div className="space-y-1.5">+ <PdfEditorFieldLabel htmlFor={`pdf-editor-field-name-${widget.id}`}>+ Field name+ </PdfEditorFieldLabel>+ <Input+ id={`pdf-editor-field-name-${widget.id}`}+ size="sm"+ value={nameDraft}+ onChange={(event: React.ChangeEvent<HTMLInputElement>) =>+ setNameDraft(event.target.value)+ }+ onBlur={commitName}+ onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {+ if (event.key === "Enter") event.currentTarget.blur()+ }}+ />+ {nameError ? (+ <div className="text-xs text-destructive">{nameError}</div>+ ) : null}+ </div>++ {isTextField ? (+ <>+ <TextControl+ label="Default value"+ value={field.value ?? ""}+ onChange={(next) => updateField({ value: next })}+ />+ <div className="space-y-1.5">+ <PdfEditorFieldLabel>Max length</PdfEditorFieldLabel>+ <Input+ type="number"+ size="sm"+ min={0}+ placeholder="Unlimited"+ value={maxLength || ""}+ onChange={(event: React.ChangeEvent<HTMLInputElement>) => {+ const parsed = Number.parseInt(event.target.value, 10)+ const next =+ Number.isNaN(parsed) || parsed <= 0 ? undefined : parsed+ updateField({ maxLen: next } as Partial<PdfWidgetAnnoField>)+ if (!next && isComb)+ toggleFlag(PDF_FORM_FIELD_FLAG.TEXT_COMB, false)+ }}+ />+ </div>+ </>+ ) : null}++ {options.length > 0 ||+ field.type === PDF_FORM_FIELD_TYPE.COMBOBOX ||+ field.type === PDF_FORM_FIELD_TYPE.LISTBOX ? (+ <div className="space-y-1.5">+ <PdfEditorFieldLabel>Options</PdfEditorFieldLabel>+ <div className="space-y-1.5">+ {options.map((option, index) => (+ <div key={index} className="flex items-center gap-1.5">+ <Input+ size="sm"+ defaultValue={option.label}+ onBlur={(event: React.FocusEvent<HTMLInputElement>) => {+ const nextLabel = event.target.value+ if (nextLabel === option.label) return+ setOptions(+ options.map((item, itemIndex) =>+ itemIndex === index+ ? { ...item, label: nextLabel }+ : item+ )+ )+ }}+ onKeyDown={(+ event: React.KeyboardEvent<HTMLInputElement>+ ) => {+ if (event.key === "Enter") event.currentTarget.blur()+ }}+ />+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ aria-label="Remove option"+ onClick={() =>+ setOptions(+ options.filter((_, itemIndex) => itemIndex !== index)+ )+ }+ >+ <TrashGlyph className="size-3.5" />+ </Button>+ </div>+ ))}+ <Button+ type="button"+ variant="outline"+ size="xs"+ onClick={() =>+ setOptions([+ ...options,+ {+ label: `Option ${options.length + 1}`,+ isSelected: false,+ },+ ])+ }+ >+ Add option+ </Button>+ </div>+ </div>+ ) : null}++ <div className="space-y-0.5">+ <PropertySwitch+ checked={Boolean(field.flag & PDF_FORM_FIELD_FLAG.READONLY)}+ onCheckedChange={(checked) =>+ toggleFlag(PDF_FORM_FIELD_FLAG.READONLY, checked)+ }+ label="Read only"+ />+ <PropertySwitch+ checked={Boolean(field.flag & PDF_FORM_FIELD_FLAG.REQUIRED)}+ onCheckedChange={(checked) =>+ toggleFlag(PDF_FORM_FIELD_FLAG.REQUIRED, checked)+ }+ label="Required"+ />+ {isTextField ? (+ <>+ <PropertySwitch+ checked={Boolean(+ field.flag & PDF_FORM_FIELD_FLAG.TEXT_MULTIPLINE+ )}+ onCheckedChange={(checked) =>+ toggleFlag(PDF_FORM_FIELD_FLAG.TEXT_MULTIPLINE, checked)+ }+ label="Multiline"+ />+ <PropertySwitch+ checked={isComb}+ disabled={maxLength <= 0}+ onCheckedChange={(checked) =>+ toggleFlag(PDF_FORM_FIELD_FLAG.TEXT_COMB, checked)+ }+ label="Comb of characters"+ description="Requires a max length."+ />+ </>+ ) : null}+ {field.type === PDF_FORM_FIELD_TYPE.LISTBOX ? (+ <PropertySwitch+ checked={Boolean(+ field.flag & PDF_FORM_FIELD_FLAG.CHOICE_MULTL_SELECT+ )}+ onCheckedChange={(checked) =>+ toggleFlag(PDF_FORM_FIELD_FLAG.CHOICE_MULTL_SELECT, checked)+ }+ label="Allow multiple selections"+ />+ ) : null}+ </div>+ </div>+ </PdfEditorSection>+ )+}++/* -------------------------------------------------------------------------- */+/* Panel */+/* -------------------------------------------------------------------------- */++export function PdfEditorPropertiesPanel({+ documentId,+}: {+ documentId: string+}) {+ const { provides: annotationCapability } = useAnnotationCapability()+ const { provides: annotation, state } = useAnnotation(documentId)+ const { permissions } = usePdfEditor()+ const [toolSnapshot, setToolSnapshot] = React.useState<{+ source: typeof annotationCapability+ tools: AnnotationTool[]+ } | null>(null)++ React.useEffect(() => {+ if (!annotationCapability) return++ return annotationCapability.onToolsChange(({ tools }) =>+ setToolSnapshot({ source: annotationCapability, tools })+ )+ }, [annotationCapability])++ const selected = React.useMemo(() => getSelectedAnnotations(state), [state])+ const tools =+ toolSnapshot?.source === annotationCapability+ ? toolSnapshot.tools+ : (annotationCapability?.getTools() ?? [])+ const activeTool: AnnotationTool | null =+ state.activeToolId && annotationCapability+ ? (tools.find((tool) => tool.id === state.activeToolId) ?? null)+ : null+ const colorPresets = annotationCapability?.getColorPresets() ?? []++ const selectedToolIds = React.useMemo(+ () =>+ selected+ .map(+ (item) => annotationCapability?.findToolForAnnotation(item.object)?.id+ )+ .filter((id): id is string => Boolean(id)),+ [annotationCapability, selected]+ )++ const isEditing = selected.length > 0+ const propertyKeys = isEditing+ ? getSharedProperties(selectedToolIds)+ : activeTool+ ? (TOOL_PROPERTIES[activeTool.id] ?? [])+ : []+ const configs = propertyKeys+ .map((key) => PROPERTY_CONFIGS[key])+ .filter((config): config is PropertyConfig => Boolean(config))+ .filter((config) => isEditing || !config.editOnly)++ const values = React.useMemo<Record<string, unknown>>(() => {+ if (isEditing)+ return selected[0].object as unknown as Record<string, unknown>+ if (activeTool)+ return activeTool.defaults as unknown as Record<string, unknown>+ return {}+ }, [activeTool, isEditing, selected])++ const canEdit = permissions.canModifyAnnotations+ const structurallyLocked = selected.some((item) =>+ annotation ? annotation.isAnnotationStructurallyLocked(item.object) : false+ )++ const applyPatch = React.useCallback(+ (patch: Record<string, unknown>) => {+ if (isEditing) {+ annotation?.updateAnnotations(+ selected.map((item) => ({+ pageIndex: item.object.pageIndex,+ id: item.object.id,+ patch: {+ ...patch,+ modified: new Date(),+ } as Partial<PdfAnnotationObject>,+ }))+ )+ return+ }++ if (activeTool && annotationCapability) {+ annotationCapability.setToolDefaults(+ activeTool.id,+ patch as Partial<PdfAnnotationObject> & Record<string, unknown>+ )+ }+ },+ [activeTool, annotation, annotationCapability, isEditing, selected]+ )++ const applyRotation = React.useCallback(+ (rotation: number) => {+ if (!annotation || !annotationCapability) return++ for (const item of selected) {+ const current = item.object.rotation ?? 0+ let patch: Partial<PdfAnnotationObject>++ try {+ patch = annotationCapability.transformAnnotation(item.object, {+ type: "rotate",+ changes: { rotation },+ metadata: {+ rotationAngle: rotation,+ rotationDelta: rotation - current,+ },+ })+ } catch {+ patch = { rotation }+ }++ annotation.updateAnnotation(item.object.pageIndex, item.object.id, {+ ...patch,+ modified: new Date(),+ })+ }+ },+ [annotation, annotationCapability, selected]+ )++ const single: TrackedAnnotation | null =+ selected.length === 1 ? selected[0] : null+ const singleMeta = single ? getAnnotationMeta(single.object) : null+ const isWidget = single?.object.type === PdfAnnotationSubtype.WIDGET++ const title = isEditing+ ? selected.length > 1+ ? `${selected.length} annotations`+ : (singleMeta?.label ?? "Annotation")+ : activeTool+ ? `${activeTool.name} defaults`+ : "Properties"++ if (!isEditing && !activeTool) {+ return (+ <PdfEditorEmptyState+ glyph={SlidersGlyph}+ title="Nothing selected"+ description="Select an annotation on the page, or pick a tool to edit its default style."+ />+ )+ }++ const flags = single?.object.flags ?? []+ const contents =+ single && !isWidget && typeof single.object.contents === "string"+ ? single.object.contents+ : ""+ const verticalAlignmentConfig = configs.find(+ (config) => config.kind === "verticalAlign"+ )++ return (+ <div className="space-y-5 p-3">+ <div>+ <div className="text-sm font-medium text-foreground">{title}</div>+ <div className="text-xs text-muted-foreground">+ {isEditing+ ? structurallyLocked+ ? "This annotation is locked. Unlock it to make changes."+ : canEdit+ ? "Changes apply immediately."+ : "This document does not allow annotation changes."+ : "New annotations use these settings."}+ </div>+ </div>++ {configs.length > 0 ? (+ <PdfEditorSection title="Appearance">+ <fieldset+ disabled={isEditing && (!canEdit || structurallyLocked)}+ className="space-y-4 disabled:opacity-60"+ >+ {configs.map((config) => {+ if (+ config.kind === "verticalAlign" &&+ configs.some((item) => item.kind === "textAlign")+ ) {+ return null+ }++ if (config.kind === "textAlign" && verticalAlignmentConfig) {+ return (+ <div+ key="alignment-controls"+ className="grid grid-cols-2 items-start gap-3"+ >+ <PropertyControl+ config={config}+ values={values}+ colorPresets={colorPresets}+ onPatch={applyPatch}+ onRotate={isEditing ? applyRotation : undefined}+ />+ <PropertyControl+ config={verticalAlignmentConfig}+ values={values}+ colorPresets={colorPresets}+ onPatch={applyPatch}+ onRotate={isEditing ? applyRotation : undefined}+ />+ </div>+ )+ }++ return (+ <PropertyControl+ key={config.key + config.kind}+ config={config}+ values={values}+ colorPresets={colorPresets}+ onPatch={applyPatch}+ onRotate={isEditing ? applyRotation : undefined}+ />+ )+ })}+ </fieldset>+ </PdfEditorSection>+ ) : null}++ {single && isWidget ? (+ <WidgetProperties+ documentId={documentId}+ widget={single.object as PdfWidgetAnnoObject}+ />+ ) : null}++ {single && !isWidget ? (+ <PdfEditorSection title="Note">+ <NoteEditor+ key={single.object.id}+ value={contents}+ disabled={!canEdit}+ onChange={(next) =>+ annotation?.updateAnnotation(+ single.object.pageIndex,+ single.object.id,+ {+ contents: next,+ modified: new Date(),+ }+ )+ }+ />+ </PdfEditorSection>+ ) : null}++ {isEditing ? (+ <PdfEditorSection title="Behavior">+ <div className="space-y-0.5">+ {FLAG_OPTIONS.map((option) => {+ const checked = selected.every((item) =>+ (item.object.flags ?? []).includes(option.flag)+ )++ return (+ <PropertySwitch+ key={option.flag}+ checked={checked}+ disabled={!canEdit}+ onCheckedChange={(next) => {+ annotation?.updateAnnotations(+ selected.map((item) => {+ const current = item.object.flags ?? []+ const nextFlags = next+ ? current.includes(option.flag)+ ? current+ : [...current, option.flag]+ : current.filter((flag) => flag !== option.flag)++ return {+ pageIndex: item.object.pageIndex,+ id: item.object.id,+ patch: { flags: nextFlags },+ }+ })+ )+ }}+ label={option.label}+ description={option.description}+ />+ )+ })}+ </div>+ </PdfEditorSection>+ ) : null}++ {single ? (+ <PdfEditorSection title="Details">+ <dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs">+ <dt className="text-muted-foreground">Type</dt>+ <dd>{singleMeta?.label}</dd>+ <dt className="text-muted-foreground">Page</dt>+ <dd>{single.object.pageIndex + 1}</dd>+ <dt className="text-muted-foreground">Author</dt>+ <dd className="truncate">{single.object.author || "—"}</dd>+ <dt className="text-muted-foreground">Created</dt>+ <dd>{formatDateTime(single.object.created)}</dd>+ <dt className="text-muted-foreground">Modified</dt>+ <dd>{formatDateTime(single.object.modified)}</dd>+ {flags.length > 0 ? (+ <>+ <dt className="text-muted-foreground">Flags</dt>+ <dd className="truncate">{flags.join(", ")}</dd>+ </>+ ) : null}+ </dl>+ </PdfEditorSection>+ ) : null}+ </div>+ )+}++function NoteEditor({+ value,+ disabled,+ onChange,+}: {+ value: string+ disabled?: boolean+ onChange: (value: string) => void+}) {+ const [draft, setDraft] = React.useState(value)++ React.useEffect(() => {+ setDraft(value)+ }, [value])++ return (+ <textarea+ value={draft}+ disabled={disabled}+ rows={3}+ placeholder="Add a note…"+ onChange={(event) => setDraft(event.target.value)}+ onBlur={() => {+ if (draft !== value) onChange(draft)+ }}+ className={cn(+ "w-full resize-y rounded-lg border border-input bg-background px-2.5 py-2 text-sm outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60"+ )}+ />+ )+}diff --git a/apps/v4/components/extend/pdf-editor-shared.tsx b/apps/v4/components/extend/pdf-editor-shared.tsxnew file mode 100644index 0000000..b725cbe--- /dev/null+++ b/apps/v4/components/extend/pdf-editor-shared.tsx@@ -0,0 +1,2512 @@+"use client"++import * as React from "react"+import type { DocumentPermissions } from "@embedpdf/core/react"+import type {+ PdfAnnotationObject,+ PdfDocumentObject,+ Rect,+ Size,+} from "@embedpdf/models"+import { PdfAnnotationSubtype } from "@embedpdf/models"+import type { CaptureAreaEvent } from "@embedpdf/plugin-capture/react"++import { cn } from "@/lib/utils"+import { Button, type ButtonProps } from "@/components/ui/button"+import { Kbd } from "@/components/ui/kbd"+import { ScrollArea } from "@/components/ui/scroll-area"+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip"+import { IconPlaceholder } from "@/components/icon-placeholder"++/* -------------------------------------------------------------------------- */+/* Types */+/* -------------------------------------------------------------------------- */++export type PdfEditorMode = "view" | "annotate" | "sign" | "forms" | "redact"++export type PdfEditorLeftPanel =+ | "thumbnails"+ | "outline"+ | "attachments"+ | "pages"++export type PdfEditorRightPanel =+ | "properties"+ | "comments"+ | "redactions"+ | "stamps"+ | "signatures"+ | "forms"++export type PdfEditorFeatureFlags = {+ /** Text markup, drawing, shapes, text boxes, notes, links, and image stamps. */+ annotate?: boolean+ /** Mark text or areas for redaction and permanently apply them. */+ redact?: boolean+ /** Fill AcroForm fields and design new form widgets. */+ forms?: boolean+ /** Draw, type, or upload signatures and initials, then place them. */+ sign?: boolean+ /** Rubber stamp libraries and custom stamps. */+ stamps?: boolean+ /** Rotate, reorder, delete, insert, extract, and merge pages. */+ pages?: boolean+ /** Password protection and permission restrictions. */+ security?: boolean+ print?: boolean+ /** Area screenshot capture. */+ capture?: boolean+ /** Bookmark outline sidebar. */+ outline?: boolean+ /** Embedded file attachments sidebar. */+ attachments?: boolean+ /** Comment threads sidebar. */+ comments?: boolean+ fullscreen?: boolean+}++export type PdfEditorResolvedFeatures = Required<PdfEditorFeatureFlags>++export const PDF_EDITOR_DEFAULT_FEATURES: PdfEditorResolvedFeatures = {+ annotate: true,+ redact: true,+ forms: true,+ sign: true,+ stamps: true,+ pages: true,+ security: true,+ print: true,+ capture: true,+ outline: true,+ attachments: true,+ comments: true,+ fullscreen: true,+}++/** A rectangle expressed as percentages (0-100) of the page size. */+export type PdfEditorNormalizedRect = {+ top: number+ left: number+ width: number+ height: number+}++export type PdfEditorSelectionPage = {+ pageIndex: number+ pageNumber: number+ pageSize: Size+ /** Bounding box in PDF points (origin top-left). */+ rect: Rect+ /** Per-line rectangles in PDF points. */+ rects: Rect[]+ normalizedRect: PdfEditorNormalizedRect+ normalizedRects: PdfEditorNormalizedRect[]+}++/** Emitted for custom text-selection actions. Coordinates are page-relative. */+export type PdfEditorSelectionPayload = PdfEditorSelectionPage & {+ documentId: string+ /** The selected text across all pages, joined with newlines. */+ text: string+ /** Every page that the selection spans (usually one). */+ pages: PdfEditorSelectionPage[]+}++export type PdfEditorSelectionAction = {+ id: string+ label: string+ icon?: React.ReactNode+ /** Called with page coordinates and the selected text. */+ onSelect?: (payload: PdfEditorSelectionPayload) => void+ /** Keep the text selected after the action runs. Defaults to false. */+ keepSelection?: boolean+}++export type PdfEditorDialogRequest =+ | { type: "print" }+ | { type: "security" }+ | { type: "properties" }+ | { type: "shortcuts" }+ | { type: "signature" }+ | { type: "link"; source: "annotation" | "selection" }+ | {+ type: "confirm"+ title: string+ description?: string+ confirmLabel?: string+ destructive?: boolean+ onConfirm: () => void+ }++export type PdfEditorNoticeTone = "info" | "success" | "error"++export type PdfEditorContextValue = {+ documentId: string+ document: PdfDocumentObject | null+ fileName: string+ mode: PdfEditorMode+ setMode: (mode: PdfEditorMode) => void+ leftPanel: PdfEditorLeftPanel | null+ setLeftPanel: (panel: PdfEditorLeftPanel | null) => void+ toggleLeftPanel: (panel: PdfEditorLeftPanel) => void+ rightPanel: PdfEditorRightPanel | null+ setRightPanel: (panel: PdfEditorRightPanel | null) => void+ toggleRightPanel: (panel: PdfEditorRightPanel) => void+ openDialog: (request: PdfEditorDialogRequest) => void+ notify: (message: string, tone?: PdfEditorNoticeTone) => void+ features: PdfEditorResolvedFeatures+ permissions: DocumentPermissions+ annotationAuthor: string+ selectionActions: PdfEditorSelectionAction[]+ formDesignMode: boolean+ setFormDesignMode: React.Dispatch<React.SetStateAction<boolean>>+ /** Replaces the open document with new PDF bytes (page operations, flattening). */+ replaceDocument: (buffer: ArrayBuffer, fileName?: string) => void+ /** Downloads the current document, including pending edits. */+ downloadDocument: (fileName?: string) => Promise<void>+ /** Returns the current document bytes, including pending edits. */+ getDocumentBuffer: () => Promise<ArrayBuffer>+ scrollToPage: (pageNumber: number, options?: { smooth?: boolean }) => void+ scrollToAnnotation: (annotation: PdfAnnotationObject) => void+ onCapture?: (event: CaptureAreaEvent) => void+ onSelectionAction?: (+ actionId: string,+ payload: PdfEditorSelectionPayload+ ) => void+ signatureFontsStylesheetUrl: string | null+}++const PdfEditorContext = React.createContext<PdfEditorContextValue | null>(null)++export const PdfEditorContextProvider = PdfEditorContext.Provider++export function usePdfEditor() {+ const context = React.useContext(PdfEditorContext)++ if (!context) {+ throw new Error("usePdfEditor must be used inside a PDFEditor.")+ }++ return context+}++/* -------------------------------------------------------------------------- */+/* Constants */+/* -------------------------------------------------------------------------- */++export const PDF_EDITOR_DEFAULT_COLOR_PRESETS = [+ "#111827",+ "#e11d48",+ "#f97316",+ "#facc15",+ "#22c55e",+ "#0ea5e9",+ "#2563eb",+ "#8b5cf6",+ "#ec4899",+ "#64748b",+ "#ffffff",+]++export const PDF_EDITOR_SELECTION_COLOR = "#2563eb"++export const PDF_EDITOR_DEFAULT_STAMP_MANIFEST_URL =+ "https://cdn.jsdelivr.net/npm/@embedpdf/default-stamps/{locale}/manifest.json"++export const PDF_EDITOR_DEFAULT_SIGNATURE_FONTS_URL =+ "https://fonts.googleapis.com/css2?family=Caveat&family=Dancing+Script&family=Great+Vibes&family=Pacifico&display=swap"++export const PDF_EDITOR_SIGNATURE_FONTS: ReadonlyArray<{+ name: string+ family: string+}> = [+ { name: "Dancing Script", family: "'Dancing Script', cursive" },+ { name: "Great Vibes", family: "'Great Vibes', cursive" },+ { name: "Pacifico", family: "'Pacifico', cursive" },+ { name: "Caveat", family: "'Caveat', cursive" },+]++/* -------------------------------------------------------------------------- */+/* Icons */+/* */+/* Icons that end up in value position (tool catalogs, switch statements) are */+/* wrapped in small `*Glyph` components so the shadcn CLI can still swap the */+/* placeholder for the consumer's icon library at install time. */+/* -------------------------------------------------------------------------- */++export type PdfEditorGlyphProps = {+ className?: string+ style?: React.CSSProperties+}++export type PdfEditorGlyph = React.ComponentType<PdfEditorGlyphProps>++export function PanelLeftGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="PanelLeft"+ tabler="IconLayoutSidebar"+ hugeicons="SidebarLeftIcon"+ phosphor="SidebarIcon"+ remixicon="RiLayoutLeftLine"+ className={className}+ style={style}+ />+ )+}++export function PanelRightGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="PanelRight"+ tabler="IconLayoutSidebarRight"+ hugeicons="SidebarRightIcon"+ phosphor="SidebarSimpleIcon"+ remixicon="RiLayoutRightLine"+ className={className}+ style={style}+ />+ )+}++export function UndoGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Undo2"+ tabler="IconArrowBackUp"+ hugeicons="Undo02Icon"+ phosphor="ArrowUUpLeftIcon"+ remixicon="RiArrowGoBackLine"+ className={className}+ style={style}+ />+ )+}++export function RedoGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Redo2"+ tabler="IconArrowForwardUp"+ hugeicons="Redo02Icon"+ phosphor="ArrowUUpRightIcon"+ remixicon="RiArrowGoForwardLine"+ className={className}+ style={style}+ />+ )+}++export function ZoomOutGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="CircleMinus"+ tabler="IconCircleMinus"+ hugeicons="MinusSignCircleIcon"+ phosphor="MinusCircleIcon"+ remixicon="RiIndeterminateCircleLine"+ className={className}+ style={style}+ />+ )+}++export function ZoomInGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="CirclePlus"+ tabler="IconCirclePlus"+ hugeicons="PlusSignCircleIcon"+ phosphor="PlusCircleIcon"+ remixicon="RiAddCircleLine"+ className={className}+ style={style}+ />+ )+}++export function RotateGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="RotateCw"+ tabler="IconRotateClockwise"+ hugeicons="RotateClockwiseIcon"+ phosphor="ArrowClockwiseIcon"+ remixicon="RiClockwiseLine"+ className={className}+ style={style}+ />+ )+}++export function SearchGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Search"+ tabler="IconSearch"+ hugeicons="Search01Icon"+ phosphor="MagnifyingGlassIcon"+ remixicon="RiSearchLine"+ className={className}+ style={style}+ />+ )+}++export function MoreGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Ellipsis"+ tabler="IconDots"+ hugeicons="MoreHorizontalIcon"+ phosphor="DotsThreeIcon"+ remixicon="RiMoreLine"+ className={className}+ style={style}+ />+ )+}++export function DownloadGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Download"+ tabler="IconDownload"+ hugeicons="Download01Icon"+ phosphor="DownloadSimpleIcon"+ remixicon="RiDownload2Line"+ className={className}+ style={style}+ />+ )+}++export function UploadGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Upload"+ tabler="IconUpload"+ hugeicons="Upload01Icon"+ phosphor="UploadSimpleIcon"+ remixicon="RiUpload2Line"+ className={className}+ style={style}+ />+ )+}++export function PrintGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Printer"+ tabler="IconPrinter"+ hugeicons="PrinterIcon"+ phosphor="PrinterIcon"+ remixicon="RiPrinterLine"+ className={className}+ style={style}+ />+ )+}++export function FullscreenGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Maximize"+ tabler="IconMaximize"+ hugeicons="FullScreenIcon"+ phosphor="CornersOutIcon"+ remixicon="RiFullscreenLine"+ className={className}+ style={style}+ />+ )+}++export function ExitFullscreenGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Minimize"+ tabler="IconMinimize"+ hugeicons="MinimizeScreenIcon"+ phosphor="CornersInIcon"+ remixicon="RiFullscreenExitLine"+ className={className}+ style={style}+ />+ )+}++export function HandGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Hand"+ tabler="IconHandStop"+ hugeicons="HandIcon"+ phosphor="HandIcon"+ remixicon="RiHand"+ className={className}+ style={style}+ />+ )+}++export function CursorGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="MousePointer2"+ tabler="IconPointer"+ hugeicons="Cursor01Icon"+ phosphor="CursorIcon"+ remixicon="RiCursorLine"+ className={className}+ style={style}+ />+ )+}++export function CameraGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Camera"+ tabler="IconCamera"+ hugeicons="Camera01Icon"+ phosphor="CameraIcon"+ remixicon="RiScreenshotLine"+ className={className}+ style={style}+ />+ )+}++export function MarqueeZoomGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="ScanSearch"+ tabler="IconZoomInArea"+ hugeicons="ZoomInAreaIcon"+ phosphor="MagnifyingGlassPlusIcon"+ remixicon="RiZoomInLine"+ className={className}+ style={style}+ />+ )+}++export function BookOpenGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="BookOpen"+ tabler="IconBook"+ hugeicons="Book01Icon"+ phosphor="BookOpenIcon"+ remixicon="RiBookOpenLine"+ className={className}+ style={style}+ />+ )+}++export function FileGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="File"+ tabler="IconFile"+ hugeicons="File01Icon"+ phosphor="FileIcon"+ remixicon="RiFileLine"+ className={className}+ style={style}+ />+ )+}++export function ArrowsHorizontalGlyph({+ className,+ style,+}: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="MoveHorizontal"+ tabler="IconArrowsHorizontal"+ hugeicons="ArrowLeftRightIcon"+ phosphor="ArrowsHorizontalIcon"+ remixicon="RiArrowLeftRightLine"+ className={className}+ style={style}+ />+ )+}++export function ArrowsVerticalGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="MoveVertical"+ tabler="IconArrowsVertical"+ hugeicons="ArrowUpDownIcon"+ phosphor="ArrowsVerticalIcon"+ remixicon="RiArrowUpDownLine"+ className={className}+ style={style}+ />+ )+}++export function HighlighterGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Highlighter"+ tabler="IconHighlight"+ hugeicons="HighlighterIcon"+ phosphor="HighlighterIcon"+ remixicon="RiMarkPenLine"+ className={className}+ style={style}+ />+ )+}++export function UnderlineGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Underline"+ tabler="IconUnderline"+ hugeicons="TextUnderlineIcon"+ phosphor="TextUnderlineIcon"+ remixicon="RiUnderline"+ className={className}+ style={style}+ />+ )+}++export function StrikethroughGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Strikethrough"+ tabler="IconStrikethrough"+ hugeicons="TextStrikethroughIcon"+ phosphor="TextStrikethroughIcon"+ remixicon="RiStrikethrough"+ className={className}+ style={style}+ />+ )+}++export function SquigglyGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="LineSquiggle"+ tabler="IconWaveSine"+ hugeicons="WaveIcon"+ phosphor="WaveSineIcon"+ remixicon="RiPulseLine"+ className={className}+ style={style}+ />+ )+}++export function PenGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Pen"+ tabler="IconPencil"+ hugeicons="Pen01Icon"+ phosphor="PenIcon"+ remixicon="RiPencilLine"+ className={className}+ style={style}+ />+ )+}++export function BrushGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Brush"+ tabler="IconBrush"+ hugeicons="BrushIcon"+ phosphor="PaintBrushIcon"+ remixicon="RiBrushLine"+ className={className}+ style={style}+ />+ )+}++export function TextGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Type"+ tabler="IconTypography"+ hugeicons="TextIcon"+ phosphor="TextTIcon"+ remixicon="RiText"+ className={className}+ style={style}+ />+ )+}++export function TextFontGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Type"+ tabler="IconTypography"+ hugeicons="TextFontIcon"+ phosphor="TextAaIcon"+ remixicon="RiFontSize"+ className={className}+ style={style}+ />+ )+}++export function CalloutGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="MessageSquareText"+ tabler="IconMessage2"+ hugeicons="BubbleChatIcon"+ phosphor="ChatTextIcon"+ remixicon="RiChat3Line"+ className={className}+ style={style}+ />+ )+}++export function StickyNoteGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="StickyNote"+ tabler="IconNote"+ hugeicons="StickyNote01Icon"+ phosphor="NoteIcon"+ remixicon="RiStickyNoteLine"+ className={className}+ style={style}+ />+ )+}++export function SquareGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Square"+ tabler="IconSquare"+ hugeicons="SquareIcon"+ phosphor="SquareIcon"+ remixicon="RiCheckboxBlankLine"+ className={className}+ style={style}+ />+ )+}++export function CircleGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Circle"+ tabler="IconCircle"+ hugeicons="CircleIcon"+ phosphor="CircleIcon"+ remixicon="RiCircleLine"+ className={className}+ style={style}+ />+ )+}++export function LineGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Minus"+ tabler="IconLine"+ hugeicons="LineIcon"+ phosphor="LineSegmentIcon"+ remixicon="RiSubtractLine"+ className={className}+ style={style}+ />+ )+}++export function ArrowGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="MoveUpRight"+ tabler="IconArrowUpRight"+ hugeicons="ArrowUpRight01Icon"+ phosphor="ArrowUpRightIcon"+ remixicon="RiArrowRightUpLine"+ className={className}+ style={style}+ />+ )+}++export function PolylineGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Spline"+ tabler="IconVectorSpline"+ hugeicons="SplinePointerIcon"+ phosphor="VectorTwoIcon"+ remixicon="RiRouteLine"+ className={className}+ style={style}+ />+ )+}++export function PolygonGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Pentagon"+ tabler="IconPolygon"+ hugeicons="PolygonIcon"+ phosphor="PolygonIcon"+ remixicon="RiPentagonLine"+ className={className}+ style={style}+ />+ )+}++export function ImageGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Image"+ tabler="IconPhoto"+ hugeicons="Image01Icon"+ phosphor="ImageIcon"+ remixicon="RiImageLine"+ className={className}+ style={style}+ />+ )+}++export function StampGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Stamp"+ tabler="IconRubberStamp"+ hugeicons="StampIcon"+ phosphor="StampIcon"+ remixicon="RiVerifiedBadgeLine"+ className={className}+ style={style}+ />+ )+}++export function LinkGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Link"+ tabler="IconLink"+ hugeicons="Link02Icon"+ phosphor="LinkIcon"+ remixicon="RiLink"+ className={className}+ style={style}+ />+ )+}++export function InsertTextGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="TextCursorInput"+ tabler="IconCursorText"+ hugeicons="CursorTextIcon"+ phosphor="CursorTextIcon"+ remixicon="RiInputCursorMove"+ className={className}+ style={style}+ />+ )+}++export function ReplaceTextGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Replace"+ tabler="IconReplace"+ hugeicons="ReplaceIcon"+ phosphor="ArrowsLeftRightIcon"+ remixicon="RiFindReplaceLine"+ className={className}+ style={style}+ />+ )+}++export function TrashGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Trash2"+ tabler="IconTrash"+ hugeicons="Delete02Icon"+ phosphor="TrashIcon"+ remixicon="RiDeleteBinLine"+ className={className}+ style={style}+ />+ )+}++export function GroupGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Group"+ tabler="IconLayersUnion"+ hugeicons="GroupItemsIcon"+ phosphor="StackIcon"+ remixicon="RiStackLine"+ className={className}+ style={style}+ />+ )+}++export function UngroupGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Ungroup"+ tabler="IconLayersSubtract"+ hugeicons="UngroupItemsIcon"+ phosphor="StackSimpleIcon"+ remixicon="RiStackLine"+ className={className}+ style={style}+ />+ )+}++export function LockGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Lock"+ tabler="IconLock"+ hugeicons="SquareLock02Icon"+ phosphor="LockIcon"+ remixicon="RiLockLine"+ className={className}+ style={style}+ />+ )+}++export function UnlockGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="LockOpen"+ tabler="IconLockOpen"+ hugeicons="SquareUnlock02Icon"+ phosphor="LockOpenIcon"+ remixicon="RiLockUnlockLine"+ className={className}+ style={style}+ />+ )+}++export function CommentGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="MessageCircle"+ tabler="IconMessageCircle"+ hugeicons="Comment01Icon"+ phosphor="ChatCircleIcon"+ remixicon="RiChat1Line"+ className={className}+ style={style}+ />+ )+}++export function CommentsGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="MessagesSquare"+ tabler="IconMessages"+ hugeicons="CommentAdd01Icon"+ phosphor="ChatsIcon"+ remixicon="RiChat3Line"+ className={className}+ style={style}+ />+ )+}++export function CheckGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Check"+ tabler="IconCheck"+ hugeicons="Tick02Icon"+ phosphor="CheckIcon"+ remixicon="RiCheckLine"+ className={className}+ style={style}+ />+ )+}++export function CloseGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="X"+ tabler="IconX"+ hugeicons="Cancel01Icon"+ phosphor="XIcon"+ remixicon="RiCloseLine"+ className={className}+ style={style}+ />+ )+}++export function PlusGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Plus"+ tabler="IconPlus"+ hugeicons="Add01Icon"+ phosphor="PlusIcon"+ remixicon="RiAddLine"+ className={className}+ style={style}+ />+ )+}++export function MinusGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Minus"+ tabler="IconMinus"+ hugeicons="MinusSignIcon"+ phosphor="MinusIcon"+ remixicon="RiSubtractLine"+ className={className}+ style={style}+ />+ )+}++export function CopyGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Copy"+ tabler="IconCopy"+ hugeicons="Copy01Icon"+ phosphor="CopyIcon"+ remixicon="RiFileCopyLine"+ className={className}+ style={style}+ />+ )+}++export function EyeOffGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="EyeOff"+ tabler="IconEyeOff"+ hugeicons="ViewOffIcon"+ phosphor="EyeSlashIcon"+ remixicon="RiEyeOffLine"+ className={className}+ style={style}+ />+ )+}++export function EyeGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Eye"+ tabler="IconEye"+ hugeicons="ViewIcon"+ phosphor="EyeIcon"+ remixicon="RiEyeLine"+ className={className}+ style={style}+ />+ )+}++export function RedactAreaGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="SquareDashed"+ tabler="IconSquareDashed"+ hugeicons="CursorRectangleSelection01Icon"+ phosphor="SelectionIcon"+ remixicon="RiCropLine"+ className={className}+ style={style}+ />+ )+}++export function SignatureGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Signature"+ tabler="IconSignature"+ hugeicons="SignatureIcon"+ phosphor="SignatureIcon"+ remixicon="RiQuillPenLine"+ className={className}+ style={style}+ />+ )+}++export function TextFieldGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="RectangleEllipsis"+ tabler="IconForms"+ hugeicons="InputTextIcon"+ phosphor="TextboxIcon"+ remixicon="RiInputField"+ className={className}+ style={style}+ />+ )+}++export function CheckboxGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="SquareCheck"+ tabler="IconSquareCheck"+ hugeicons="CheckmarkSquare01Icon"+ phosphor="CheckSquareIcon"+ remixicon="RiCheckboxLine"+ className={className}+ style={style}+ />+ )+}++export function RadioGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="CircleDot"+ tabler="IconCircleDot"+ hugeicons="RadioButtonIcon"+ phosphor="RadioButtonIcon"+ remixicon="RiRadioButtonLine"+ className={className}+ style={style}+ />+ )+}++export function ComboboxGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="ChevronsUpDown"+ tabler="IconSelect"+ hugeicons="UnfoldMoreIcon"+ phosphor="CaretUpDownIcon"+ remixicon="RiArrowUpDownLine"+ className={className}+ style={style}+ />+ )+}++export function ListboxGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="List"+ tabler="IconList"+ hugeicons="LeftToRightListBulletIcon"+ phosphor="ListIcon"+ remixicon="RiListUnordered"+ className={className}+ style={style}+ />+ )+}++export function ListTreeGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="ListTree"+ tabler="IconListTree"+ hugeicons="ListTreeIcon"+ phosphor="TreeStructureIcon"+ remixicon="RiNodeTree"+ className={className}+ style={style}+ />+ )+}++export function PaperclipGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Paperclip"+ tabler="IconPaperclip"+ hugeicons="Attachment01Icon"+ phosphor="PaperclipIcon"+ remixicon="RiAttachment2"+ className={className}+ style={style}+ />+ )+}++export function GridGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="LayoutGrid"+ tabler="IconLayoutGrid"+ hugeicons="GridViewIcon"+ phosphor="SquaresFourIcon"+ remixicon="RiLayoutGridLine"+ className={className}+ style={style}+ />+ )+}++export function SlidersGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="SlidersHorizontal"+ tabler="IconAdjustmentsHorizontal"+ hugeicons="SlidersHorizontalIcon"+ phosphor="SlidersHorizontalIcon"+ remixicon="RiEqualizerLine"+ className={className}+ style={style}+ />+ )+}++export function InfoGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Info"+ tabler="IconInfoCircle"+ hugeicons="InformationCircleIcon"+ phosphor="InfoIcon"+ remixicon="RiInformationLine"+ className={className}+ style={style}+ />+ )+}++export function ShieldGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="ShieldCheck"+ tabler="IconShieldLock"+ hugeicons="Shield01Icon"+ phosphor="ShieldCheckIcon"+ remixicon="RiShieldKeyholeLine"+ className={className}+ style={style}+ />+ )+}++export function FileTextGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="FileText"+ tabler="IconFileText"+ hugeicons="File01Icon"+ phosphor="FileTextIcon"+ remixicon="RiFileTextLine"+ className={className}+ style={style}+ />+ )+}++export function ChevronDownGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="ChevronDown"+ tabler="IconChevronDown"+ hugeicons="ArrowDown01Icon"+ phosphor="CaretDownIcon"+ remixicon="RiArrowDownSLine"+ className={className}+ style={style}+ />+ )+}++export function ChevronUpGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="ChevronUp"+ tabler="IconChevronUp"+ hugeicons="ArrowUp01Icon"+ phosphor="CaretUpIcon"+ remixicon="RiArrowUpSLine"+ className={className}+ style={style}+ />+ )+}++export function ChevronLeftGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="ChevronLeft"+ tabler="IconChevronLeft"+ hugeicons="ArrowLeft01Icon"+ phosphor="CaretLeftIcon"+ remixicon="RiArrowLeftSLine"+ className={className}+ style={style}+ />+ )+}++export function ChevronRightGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="ChevronRight"+ tabler="IconChevronRight"+ hugeicons="ArrowRight01Icon"+ phosphor="CaretRightIcon"+ remixicon="RiArrowRightSLine"+ className={className}+ style={style}+ />+ )+}++export function LayersGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Layers"+ tabler="IconStack2"+ hugeicons="Layers01Icon"+ phosphor="StackIcon"+ remixicon="RiStackLine"+ className={className}+ style={style}+ />+ )+}++export function FilePlusGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="FilePlus"+ tabler="IconFilePlus"+ hugeicons="FileAddIcon"+ phosphor="FilePlusIcon"+ remixicon="RiFileAddLine"+ className={className}+ style={style}+ />+ )+}++export function ScissorsGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Scissors"+ tabler="IconScissors"+ hugeicons="Scissor01Icon"+ phosphor="ScissorsIcon"+ remixicon="RiScissorsLine"+ className={className}+ style={style}+ />+ )+}++export function MergeGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Merge"+ tabler="IconArrowMerge"+ hugeicons="GitMergeIcon"+ phosphor="GitMergeIcon"+ remixicon="RiGitMergeLine"+ className={className}+ style={style}+ />+ )+}++export function RefreshGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="RefreshCw"+ tabler="IconRefresh"+ hugeicons="RefreshIcon"+ phosphor="ArrowsClockwiseIcon"+ remixicon="RiRefreshLine"+ className={className}+ style={style}+ />+ )+}++export function SaveGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Save"+ tabler="IconDeviceFloppy"+ hugeicons="FloppyDiskIcon"+ phosphor="FloppyDiskIcon"+ remixicon="RiSaveLine"+ className={className}+ style={style}+ />+ )+}++export function KeyboardGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Keyboard"+ tabler="IconKeyboard"+ hugeicons="KeyboardIcon"+ phosphor="KeyboardIcon"+ remixicon="RiKeyboardLine"+ className={className}+ style={style}+ />+ )+}++export function PaletteGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Palette"+ tabler="IconPalette"+ hugeicons="PaintBoardIcon"+ phosphor="PaletteIcon"+ remixicon="RiPaletteLine"+ className={className}+ style={style}+ />+ )+}++export function BoldGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Bold"+ tabler="IconBold"+ hugeicons="TextBoldIcon"+ phosphor="TextBIcon"+ remixicon="RiBold"+ className={className}+ style={style}+ />+ )+}++export function ItalicGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Italic"+ tabler="IconItalic"+ hugeicons="TextItalicIcon"+ phosphor="TextItalicIcon"+ remixicon="RiItalic"+ className={className}+ style={style}+ />+ )+}++export function AlignLeftGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="TextAlignStart"+ tabler="IconAlignLeft"+ hugeicons="TextAlignLeft01Icon"+ phosphor="TextAlignLeftIcon"+ remixicon="RiAlignLeft"+ className={className}+ style={style}+ />+ )+}++export function AlignCenterGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="TextAlignCenter"+ tabler="IconAlignCenter"+ hugeicons="TextAlignCenterIcon"+ phosphor="TextAlignCenterIcon"+ remixicon="RiAlignCenter"+ className={className}+ style={style}+ />+ )+}++export function AlignRightGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="TextAlignEnd"+ tabler="IconAlignRight"+ hugeicons="TextAlignRight01Icon"+ phosphor="TextAlignRightIcon"+ remixicon="RiAlignRight"+ className={className}+ style={style}+ />+ )+}++export function AlignTopGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="ArrowUpToLine"+ tabler="IconAlignBoxTopCenter"+ hugeicons="AlignBoxTopCenterIcon"+ phosphor="AlignTopIcon"+ remixicon="RiAlignTop"+ className={className}+ style={style}+ />+ )+}++export function AlignMiddleGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="AlignVerticalJustifyCenter"+ tabler="IconAlignBoxCenterMiddle"+ hugeicons="AlignBoxMiddleCenterIcon"+ phosphor="AlignCenterVerticalIcon"+ remixicon="RiAlignVertically"+ className={className}+ style={style}+ />+ )+}++export function AlignBottomGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="ArrowDownToLine"+ tabler="IconAlignBoxBottomCenter"+ hugeicons="AlignBoxBottomCenterIcon"+ phosphor="AlignBottomIcon"+ remixicon="RiAlignBottom"+ className={className}+ style={style}+ />+ )+}++export function FlagGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Flag"+ tabler="IconFlag"+ hugeicons="Flag01Icon"+ phosphor="FlagIcon"+ remixicon="RiFlagLine"+ className={className}+ style={style}+ />+ )+}++export function ClipboardGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Clipboard"+ tabler="IconClipboard"+ hugeicons="ClipboardIcon"+ phosphor="ClipboardIcon"+ remixicon="RiClipboardLine"+ className={className}+ style={style}+ />+ )+}++export function KeyGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Key"+ tabler="IconKey"+ hugeicons="Key01Icon"+ phosphor="KeyIcon"+ remixicon="RiKey2Line"+ className={className}+ style={style}+ />+ )+}++export function ExternalLinkGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="ExternalLink"+ tabler="IconExternalLink"+ hugeicons="ExternalLinkIcon"+ phosphor="ArrowSquareOutIcon"+ remixicon="RiExternalLinkLine"+ className={className}+ style={style}+ />+ )+}++export function MoveGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Move"+ tabler="IconArrowsMove"+ hugeicons="MoveIcon"+ phosphor="ArrowsOutCardinalIcon"+ remixicon="RiDragMove2Line"+ className={className}+ style={style}+ />+ )+}++export function AlertGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="TriangleAlert"+ tabler="IconAlertTriangle"+ hugeicons="Alert01Icon"+ phosphor="WarningIcon"+ remixicon="RiAlertLine"+ className={className}+ style={style}+ />+ )+}++export function ArrowUpGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="ArrowUp"+ tabler="IconArrowUp"+ hugeicons="ArrowUp02Icon"+ phosphor="ArrowUpIcon"+ remixicon="RiArrowUpLine"+ className={className}+ style={style}+ />+ )+}++export function ArrowDownGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="ArrowDown"+ tabler="IconArrowDown"+ hugeicons="ArrowDown02Icon"+ phosphor="ArrowDownIcon"+ remixicon="RiArrowDownLine"+ className={className}+ style={style}+ />+ )+}++export function EditGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Pencil"+ tabler="IconEdit"+ hugeicons="PencilEdit01Icon"+ phosphor="PencilSimpleIcon"+ remixicon="RiEditLine"+ className={className}+ style={style}+ />+ )+}++export function SparklesGlyph({ className, style }: PdfEditorGlyphProps) {+ return (+ <IconPlaceholder+ lucide="Sparkles"+ tabler="IconSparkles"+ hugeicons="SparklesIcon"+ phosphor="SparkleIcon"+ remixicon="RiSparklingLine"+ className={className}+ style={style}+ />+ )+}++/* -------------------------------------------------------------------------- */+/* Tool catalogs */+/* -------------------------------------------------------------------------- */++export type PdfEditorToolDefinition = {+ /** EmbedPDF annotation tool id. */+ id: string+ label: string+ glyph: PdfEditorGlyph+ /** Short hint shown in the tooltip. */+ hint?: string+}++export type PdfEditorToolGroup = {+ id: string+ label: string+ tools: PdfEditorToolDefinition[]+}++export const PDF_EDITOR_ANNOTATION_TOOL_GROUPS: PdfEditorToolGroup[] = [+ {+ id: "markup",+ label: "Text markup",+ tools: [+ {+ id: "highlight",+ label: "Highlight",+ glyph: HighlighterGlyph,+ hint: "Select text to highlight",+ },+ {+ id: "underline",+ label: "Underline",+ glyph: UnderlineGlyph,+ hint: "Select text to underline",+ },+ {+ id: "strikeout",+ label: "Strikethrough",+ glyph: StrikethroughGlyph,+ hint: "Select text to strike through",+ },+ {+ id: "squiggly",+ label: "Squiggly",+ glyph: SquigglyGlyph,+ hint: "Select text for a squiggly underline",+ },+ ],+ },+ {+ id: "draw",+ label: "Draw",+ tools: [+ {+ id: "ink",+ label: "Pen",+ glyph: PenGlyph,+ hint: "Draw freehand",+ },+ {+ id: "inkHighlighter",+ label: "Highlighter pen",+ glyph: BrushGlyph,+ hint: "Draw a translucent highlighter stroke",+ },+ ],+ },+ {+ id: "text",+ label: "Text",+ tools: [+ {+ id: "freeText",+ label: "Text box",+ glyph: TextGlyph,+ hint: "Click or drag to add text",+ },+ {+ id: "freeTextCallout",+ label: "Callout",+ glyph: CalloutGlyph,+ hint: "Drag to add a callout with a leader line",+ },+ {+ id: "textComment",+ label: "Sticky note",+ glyph: StickyNoteGlyph,+ hint: "Click to add a note",+ },+ ],+ },+ {+ id: "shapes",+ label: "Shapes",+ tools: [+ { id: "square", label: "Rectangle", glyph: SquareGlyph },+ { id: "circle", label: "Ellipse", glyph: CircleGlyph },+ { id: "line", label: "Line", glyph: LineGlyph },+ { id: "lineArrow", label: "Arrow", glyph: ArrowGlyph },+ {+ id: "polyline",+ label: "Polyline",+ glyph: PolylineGlyph,+ hint: "Click to add points, double-click to finish",+ },+ {+ id: "polygon",+ label: "Polygon",+ glyph: PolygonGlyph,+ hint: "Click to add points, double-click to finish",+ },+ ],+ },+ {+ id: "insert",+ label: "Insert",+ tools: [+ {+ id: "stamp",+ label: "Image",+ glyph: ImageGlyph,+ hint: "Click the page to place an image",+ },+ {+ id: "link",+ label: "Link area",+ glyph: LinkGlyph,+ hint: "Drag to add a link rectangle",+ },+ {+ id: "insertText",+ label: "Insert text mark",+ glyph: InsertTextGlyph,+ hint: "Select text to mark an insertion point",+ },+ {+ id: "replaceText",+ label: "Replace text mark",+ glyph: ReplaceTextGlyph,+ hint: "Select text to mark it for replacement",+ },+ ],+ },+]++export const PDF_EDITOR_ANNOTATION_TOOLS: PdfEditorToolDefinition[] =+ PDF_EDITOR_ANNOTATION_TOOL_GROUPS.flatMap((group) => group.tools)++export const PDF_EDITOR_FORM_TOOLS: PdfEditorToolDefinition[] = [+ {+ id: "formTextField",+ label: "Text field",+ glyph: TextFieldGlyph,+ hint: "Click or drag to add a text field",+ },+ {+ id: "formCheckbox",+ label: "Checkbox",+ glyph: CheckboxGlyph,+ hint: "Click to add a checkbox",+ },+ {+ id: "formRadioButton",+ label: "Radio button",+ glyph: RadioGlyph,+ hint: "Click to add a radio button",+ },+ {+ id: "formCombobox",+ label: "Dropdown",+ glyph: ComboboxGlyph,+ hint: "Click or drag to add a dropdown",+ },+ {+ id: "formListbox",+ label: "List box",+ glyph: ListboxGlyph,+ hint: "Click or drag to add a list box",+ },+]++export const PDF_EDITOR_MODE_OPTIONS: Array<{+ id: PdfEditorMode+ label: string+ glyph: PdfEditorGlyph+ feature: keyof PdfEditorFeatureFlags | null+}> = [+ { id: "view", label: "View", glyph: EyeGlyph, feature: null },+ { id: "annotate", label: "Annotate", glyph: PenGlyph, feature: "annotate" },+ { id: "sign", label: "Sign", glyph: SignatureGlyph, feature: "sign" },+ { id: "forms", label: "Forms", glyph: TextFieldGlyph, feature: "forms" },+ { id: "redact", label: "Redact", glyph: EyeOffGlyph, feature: "redact" },+]++export type PdfEditorAnnotationMeta = {+ label: string+ glyph: PdfEditorGlyph+ /** The most representative color of the annotation, if any. */+ color?: string+}++export function getAnnotationColor(+ annotation: PdfAnnotationObject+): string | undefined {+ const record = annotation as unknown as Record<string, unknown>+ const candidates = [record.strokeColor, record.fontColor, record.color]++ for (const candidate of candidates) {+ if (typeof candidate === "string" && candidate.trim()) return candidate+ }++ return undefined+}++export function getAnnotationMeta(+ annotation: PdfAnnotationObject+): PdfEditorAnnotationMeta {+ const color = getAnnotationColor(annotation)+ const intent = annotation.intent ?? ""++ switch (annotation.type) {+ case PdfAnnotationSubtype.HIGHLIGHT:+ return { label: "Highlight", glyph: HighlighterGlyph, color }+ case PdfAnnotationSubtype.UNDERLINE:+ return { label: "Underline", glyph: UnderlineGlyph, color }+ case PdfAnnotationSubtype.STRIKEOUT:+ return intent === "StrikeOutTextReplace"+ ? { label: "Replace text", glyph: ReplaceTextGlyph, color }+ : { label: "Strikethrough", glyph: StrikethroughGlyph, color }+ case PdfAnnotationSubtype.SQUIGGLY:+ return { label: "Squiggly", glyph: SquigglyGlyph, color }+ case PdfAnnotationSubtype.INK:+ return intent === "InkHighlight"+ ? { label: "Highlighter pen", glyph: BrushGlyph, color }+ : { label: "Ink", glyph: PenGlyph, color }+ case PdfAnnotationSubtype.SQUARE:+ return { label: "Rectangle", glyph: SquareGlyph, color }+ case PdfAnnotationSubtype.CIRCLE:+ return { label: "Ellipse", glyph: CircleGlyph, color }+ case PdfAnnotationSubtype.LINE:+ return intent === "LineArrow"+ ? { label: "Arrow", glyph: ArrowGlyph, color }+ : { label: "Line", glyph: LineGlyph, color }+ case PdfAnnotationSubtype.POLYLINE:+ return { label: "Polyline", glyph: PolylineGlyph, color }+ case PdfAnnotationSubtype.POLYGON:+ return { label: "Polygon", glyph: PolygonGlyph, color }+ case PdfAnnotationSubtype.FREETEXT:+ return intent === "FreeTextCallout"+ ? { label: "Callout", glyph: CalloutGlyph, color }+ : { label: "Text box", glyph: TextGlyph, color }+ case PdfAnnotationSubtype.TEXT:+ return { label: "Note", glyph: StickyNoteGlyph, color }+ case PdfAnnotationSubtype.STAMP:+ return { label: "Stamp", glyph: StampGlyph, color }+ case PdfAnnotationSubtype.LINK:+ return { label: "Link", glyph: LinkGlyph, color }+ case PdfAnnotationSubtype.CARET:+ return { label: "Insert text", glyph: InsertTextGlyph, color }+ case PdfAnnotationSubtype.REDACT:+ return { label: "Redaction", glyph: EyeOffGlyph, color }+ case PdfAnnotationSubtype.WIDGET:+ return { label: "Form field", glyph: TextFieldGlyph, color }+ case PdfAnnotationSubtype.FILEATTACHMENT:+ return { label: "Attachment", glyph: PaperclipGlyph, color }+ default:+ return { label: "Annotation", glyph: FlagGlyph, color }+ }+}++/* -------------------------------------------------------------------------- */+/* Helpers */+/* -------------------------------------------------------------------------- */++export function clamp(value: number, min: number, max: number) {+ return Math.min(max, Math.max(min, value))+}++export function ensurePdfExtension(fileName: string) {+ return fileName.toLowerCase().endsWith(".pdf") ? fileName : `${fileName}.pdf`+}++export function getPdfFileName(fileName: string | undefined, src?: string) {+ if (fileName?.trim()) return ensurePdfExtension(fileName.trim())++ if (src && !src.startsWith("blob:") && !src.startsWith("data:")) {+ const pathname = src.split(/[?#]/)[0] ?? ""+ const rawName = pathname.split("/").pop() || ""++ if (rawName) {+ try {+ return ensurePdfExtension(decodeURIComponent(rawName))+ } catch {+ return ensurePdfExtension(rawName)+ }+ }+ }++ return "document.pdf"+}++export function withFileNameSuffix(fileName: string, suffix: string) {+ return ensurePdfExtension(fileName.replace(/\.pdf$/i, "") + suffix)+}++export function downloadBlob(blob: Blob, fileName: string) {+ const url = URL.createObjectURL(blob)+ const anchor = document.createElement("a")++ anchor.href = url+ anchor.download = fileName+ anchor.rel = "noopener"+ document.body.append(anchor)+ anchor.click()+ anchor.remove()+ window.setTimeout(() => URL.revokeObjectURL(url), 0)+}++export function downloadArrayBuffer(+ buffer: ArrayBuffer | Uint8Array,+ fileName: string,+ type = "application/pdf"+) {+ const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer)+ const copy = new ArrayBuffer(bytes.byteLength)+ new Uint8Array(copy).set(bytes)++ downloadBlob(new Blob([copy], { type }), fileName)+}++export function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {+ const copy = new ArrayBuffer(bytes.byteLength)+ new Uint8Array(copy).set(bytes)+ return copy+}++export function readFileAsArrayBuffer(file: Blob) {+ return file.arrayBuffer()+}++export function formatBytes(bytes: number | undefined) {+ if (bytes === undefined || Number.isNaN(bytes)) return "—"+ if (bytes < 1024) return `${bytes} B`+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`+}++export function formatDateTime(date: Date | undefined | null) {+ if (!date) return "—"++ const value = date instanceof Date ? date : new Date(date)++ if (Number.isNaN(value.getTime())) return "—"++ return value.toLocaleString(undefined, {+ dateStyle: "medium",+ timeStyle: "short",+ })+}++export function formatRelativeDate(date: Date | undefined | null) {+ if (!date) return ""++ const value = date instanceof Date ? date : new Date(date)++ if (Number.isNaN(value.getTime())) return ""++ const diff = Date.now() - value.getTime()+ const minutes = Math.round(diff / 60000)++ if (minutes < 1) return "just now"+ if (minutes < 60) return `${minutes}m ago`++ const hours = Math.round(minutes / 60)++ if (hours < 24) return `${hours}h ago`++ return value.toLocaleDateString(undefined, {+ month: "short",+ day: "numeric",+ })+}++export function toNormalizedRect(+ rect: Rect,+ pageSize: Size+): PdfEditorNormalizedRect {+ const width = pageSize.width || 1+ const height = pageSize.height || 1++ return {+ top: (rect.origin.y / height) * 100,+ left: (rect.origin.x / width) * 100,+ width: (rect.size.width / width) * 100,+ height: (rect.size.height / height) * 100,+ }+}++export function isTypingTarget(target: EventTarget | null) {+ if (!(target instanceof HTMLElement)) return false+ if (target.isContentEditable) return true++ return Boolean(+ target.closest(+ "input, textarea, select, [contenteditable='true'], [contenteditable='']"+ )+ )+}++export function isMacPlatform() {+ if (typeof navigator === "undefined") return false++ return /mac|iphone|ipad|ipod/i.test(navigator.platform)+}++export function formatShortcut(shortcut: string) {+ const mac = isMacPlatform()++ return shortcut+ .replace(/mod/gi, mac ? "⌘" : "Ctrl")+ .replace(/shift/gi, mac ? "⇧" : "Shift")+ .replace(/alt/gi, mac ? "⌥" : "Alt")+}++export function uniqueName(base: string, existing: Iterable<string>) {+ const taken = new Set(existing)++ if (!taken.has(base)) return base++ let index = 2++ while (taken.has(`${base} ${index}`)) index += 1++ return `${base} ${index}`+}++export function noop() {}++/* -------------------------------------------------------------------------- */+/* Small UI primitives shared by the editor files */+/* -------------------------------------------------------------------------- */++export function PdfEditorTooltip({+ label,+ shortcut,+ children,+}: {+ label: React.ReactNode+ shortcut?: string+ children: React.ReactNode+}) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="inline-flex">{children}</span>+ </TooltipTrigger>+ <TooltipContent side="bottom">+ <span className="inline-flex items-center gap-2">+ {label}+ {shortcut ? (+ <Kbd className="h-4 min-w-4 px-1 text-[10px]">+ {formatShortcut(shortcut)}+ </Kbd>+ ) : null}+ </span>+ </TooltipContent>+ </Tooltip>+ )+}++export function PdfEditorToolButton({+ label,+ shortcut,+ active = false,+ className,+ children,+ size = "icon-sm",+ variant = "ghost",+ ...props+}: Omit<ButtonProps, "variant" | "size" | "children"> & {+ label: string+ shortcut?: string+ active?: boolean+ size?: ButtonProps["size"]+ variant?: ButtonProps["variant"]+ children: React.ReactNode+}) {+ return (+ <PdfEditorTooltip label={label} shortcut={shortcut}>+ <Button+ type="button"+ variant={variant}+ size={size}+ aria-label={label}+ aria-pressed={active}+ data-active={active ? "" : undefined}+ className={cn(+ active &&+ "bg-accent text-accent-foreground ring-1 ring-ring/40 ring-inset",+ className+ )}+ {...props}+ >+ {children}+ </Button>+ </PdfEditorTooltip>+ )+}++export function PdfEditorToolbarSeparator({+ className,+}: {+ className?: string+}) {+ return (+ <div+ aria-hidden="true"+ className={cn("mx-1 h-4 w-px shrink-0 self-center bg-border", className)}+ />+ )+}++export function PdfEditorPanelHeader({+ title,+ description,+ actions,+ onClose,+}: {+ title: React.ReactNode+ description?: React.ReactNode+ actions?: React.ReactNode+ onClose?: () => void+}) {+ return (+ <div className="flex shrink-0 items-start justify-between gap-2 border-b px-3 py-2.5">+ <div className="min-w-0">+ <div className="truncate text-sm font-medium text-foreground">+ {title}+ </div>+ {description ? (+ <div className="mt-0.5 text-xs text-muted-foreground">+ {description}+ </div>+ ) : null}+ </div>+ <div className="flex shrink-0 items-center gap-1">+ {actions}+ {onClose ? (+ <PdfEditorToolButton+ label="Close panel"+ size="icon-xs"+ onClick={onClose}+ >+ <CloseGlyph className="size-3.5" />+ </PdfEditorToolButton>+ ) : null}+ </div>+ </div>+ )+}++export function PdfEditorEmptyState({+ glyph: Glyph,+ title,+ description,+ action,+ className,+}: {+ glyph?: PdfEditorGlyph+ title: React.ReactNode+ description?: React.ReactNode+ action?: React.ReactNode+ className?: string+}) {+ return (+ <div+ className={cn(+ "flex flex-col items-center gap-2 px-4 py-10 text-center",+ className+ )}+ >+ {Glyph ? (+ <div className="grid size-10 place-items-center rounded-full bg-muted text-muted-foreground">+ <Glyph className="size-5" />+ </div>+ ) : null}+ <div className="text-sm font-medium text-foreground">{title}</div>+ {description ? (+ <div className="max-w-56 text-xs text-muted-foreground">+ {description}+ </div>+ ) : null}+ {action ? <div className="mt-2">{action}</div> : null}+ </div>+ )+}++export function PdfEditorSection({+ title,+ actions,+ children,+ className,+}: {+ title?: React.ReactNode+ actions?: React.ReactNode+ children: React.ReactNode+ className?: string+}) {+ return (+ <section className={cn("space-y-2", className)}>+ {title || actions ? (+ <div className="flex items-center justify-between gap-2">+ {title ? (+ <div className="text-xs font-medium text-muted-foreground">+ {title}+ </div>+ ) : (+ <span />+ )}+ {actions}+ </div>+ ) : null}+ {children}+ </section>+ )+}++export function PdfEditorFieldLabel({+ children,+ htmlFor,+ className,+}: {+ children: React.ReactNode+ htmlFor?: string+ className?: string+}) {+ return (+ <label+ htmlFor={htmlFor}+ className={cn("block text-xs font-medium text-foreground", className)}+ >+ {children}+ </label>+ )+}++export function PdfEditorCheckbox({+ checked,+ disabled,+ label,+ description,+ onCheckedChange,+ className,+}: {+ checked: boolean+ disabled?: boolean+ label: React.ReactNode+ description?: React.ReactNode+ onCheckedChange: (checked: boolean) => void+ className?: string+}) {+ return (+ <button+ type="button"+ role="checkbox"+ aria-checked={checked}+ disabled={disabled}+ onClick={() => onCheckedChange(!checked)}+ className={cn(+ "flex w-full items-start gap-2 rounded-md px-1 py-1 text-left text-sm outline-none hover:bg-accent/60 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",+ className+ )}+ >+ <span+ aria-hidden="true"+ className={cn(+ "mt-0.5 grid size-4 shrink-0 place-items-center rounded border transition-colors",+ checked+ ? "border-primary bg-primary text-primary-foreground"+ : "border-input bg-background"+ )}+ >+ {checked ? <CheckGlyph className="size-3" /> : null}+ </span>+ <span className="min-w-0">+ <span className="block leading-4">{label}</span>+ {description ? (+ <span className="block text-xs text-muted-foreground">+ {description}+ </span>+ ) : null}+ </span>+ </button>+ )+}++export function PdfEditorSwatch({+ color,+ active,+ label,+ onClick,+ size = "md",+}: {+ color: string+ active?: boolean+ label?: string+ onClick?: () => void+ size?: "sm" | "md"+}) {+ const isTransparent = color === "transparent"+ const accessibleLabel = label ?? (isTransparent ? "No fill" : color)++ const swatch = (+ <button+ type="button"+ aria-label={accessibleLabel}+ aria-pressed={active}+ onClick={onClick}+ className={cn(+ "relative shrink-0 rounded-full border border-black/10 transition-transform outline-none focus-visible:ring-2 focus-visible:ring-ring dark:border-white/15",+ size === "sm" ? "size-4" : "size-5",+ active && "ring-2 ring-ring ring-offset-2 ring-offset-background"+ )}+ style={+ isTransparent+ ? {+ backgroundImage:+ "linear-gradient(45deg, transparent 45%, #ef4444 45%, #ef4444 55%, transparent 55%)",+ backgroundColor: "#fff",+ }+ : { backgroundColor: color }+ }+ />+ )++ return label ? (+ <PdfEditorTooltip label={label}>{swatch}</PdfEditorTooltip>+ ) : (+ swatch+ )+}++/* -------------------------------------------------------------------------- */+/* Scroll area with a resolvable viewport (mirrors the PDF viewer) */+/* -------------------------------------------------------------------------- */++export type PdfEditorScrollAreaViewportResolver = (+ container: HTMLDivElement+) => HTMLDivElement | null++const DEFAULT_SCROLL_AREA_VIEWPORT_SELECTOR =+ '[data-slot="scroll-area-viewport"]'++export function resolveDefaultScrollAreaViewport(container: HTMLDivElement) {+ return container.querySelector<HTMLDivElement>(+ DEFAULT_SCROLL_AREA_VIEWPORT_SELECTOR+ )+}++export const PdfEditorScrollAreaResolverContext =+ React.createContext<PdfEditorScrollAreaViewportResolver>(+ resolveDefaultScrollAreaViewport+ )++function setRefValue<T>(ref: React.Ref<T> | undefined, value: T | null) {+ if (!ref) return++ if (typeof ref === "function") {+ ref(value)+ } else {+ ref.current = value+ }+}++export function PdfEditorScrollArea({+ children,+ className,+ orientation = "vertical",+ scrollbarGutter = true,+ viewportClassName,+ viewportProps,+ viewportRef,+}: {+ children: React.ReactNode+ className?: string+ orientation?: "vertical" | "horizontal" | "both"+ scrollbarGutter?: boolean+ viewportClassName?: string+ viewportProps?: React.HTMLAttributes<HTMLDivElement>+ viewportRef?: React.Ref<HTMLDivElement>+}) {+ const resolveViewport = React.useContext(PdfEditorScrollAreaResolverContext)+ const containerRef = React.useRef<HTMLDivElement | null>(null)+ const { className: viewportPropsClassName, ...resolvedViewportProps } =+ viewportProps ?? {}++ const setViewportRef = React.useCallback(+ (viewport: HTMLDivElement | null) => {+ setRefValue(viewportRef, viewport)+ },+ [viewportRef]+ )++ React.useLayoutEffect(() => {+ const container = containerRef.current+ if (!container) return++ const viewport = resolveViewport(container)++ if (!viewport) {+ console.error(+ `PDFEditor could not resolve the scroll viewport. Add ${DEFAULT_SCROLL_AREA_VIEWPORT_SELECTOR} to your ScrollArea viewport or pass resolveScrollAreaViewport.`+ )+ return+ }++ setViewportRef(viewport)++ return () => setViewportRef(null)+ }, [resolveViewport, setViewportRef])++ return (+ <div+ ref={containerRef}+ data-slot="pdf-editor-scroll-area"+ className={cn("size-full min-h-0", className)}+ >+ <ScrollArea+ className="size-full min-h-0"+ orientation={orientation}+ scrollbarGutter={scrollbarGutter}+ >+ <div+ {...resolvedViewportProps}+ data-slot="pdf-editor-scroll-content"+ className={cn(+ "min-h-full",+ viewportPropsClassName,+ viewportClassName+ )}+ >+ {children}+ </div>+ </ScrollArea>+ </div>+ )+}diff --git a/apps/v4/components/extend/pdf-editor.tsx b/apps/v4/components/extend/pdf-editor.tsxnew file mode 100644index 0000000..fab8b0d--- /dev/null+++ b/apps/v4/components/extend/pdf-editor.tsx@@ -0,0 +1,4352 @@+"use client"++import * as React from "react"+import { createPluginRegistration } from "@embedpdf/core"+import {+ EmbedPDF,+ useDocumentPermissions,+ useDocumentState,+ useRegistry,+} from "@embedpdf/core/react"+import {+ PdfAnnotationSubtype,+ PdfErrorCode,+ PdfPageFlattenFlag,+ uuidV4,+ type PdfAnnotationObject,+ type PdfDocumentObject,+ type PdfEngine,+ type PdfLinkAnnoObject,+ type PdfPrintOptions,+} from "@embedpdf/models"+import {+ AnnotationLayer,+ AnnotationPluginPackage,+ getSelectedAnnotations,+ LockModeType,+ useAnnotation,+ useAnnotationCapability,+ type AnnotationEvent,+ type AnnotationSelectionMenuProps,+ type AnnotationTransferItem,+ type GroupSelectionMenuProps,+} from "@embedpdf/plugin-annotation/react"+import { AttachmentPluginPackage } from "@embedpdf/plugin-attachment/react"+import { BookmarkPluginPackage } from "@embedpdf/plugin-bookmark/react"+import {+ CapturePluginPackage,+ MarqueeCapture,+ useCapture,+ type CaptureAreaEvent,+} from "@embedpdf/plugin-capture/react"+import {+ DocumentManagerPluginPackage,+ useActiveDocument,+ useDocumentManagerCapability,+} from "@embedpdf/plugin-document-manager/react"+import { ExportPluginPackage, useExport } from "@embedpdf/plugin-export/react"+import {+ FormPluginPackage,+ useFormCapability,+} from "@embedpdf/plugin-form/react"+import {+ FullscreenPluginPackage,+ useFullscreen,+} from "@embedpdf/plugin-fullscreen/react"+import {+ HistoryPluginPackage,+ useHistoryCapability,+} from "@embedpdf/plugin-history/react"+import {+ GlobalPointerProvider,+ InteractionManagerPluginPackage,+ PagePointerProvider,+} from "@embedpdf/plugin-interaction-manager/react"+import { PanPluginPackage, usePan } from "@embedpdf/plugin-pan/react"+import { PrintPluginPackage, usePrint } from "@embedpdf/plugin-print/react"+import {+ RedactionLayer,+ RedactionMode,+ RedactionPluginPackage,+ useRedaction,+ type RedactionSelectionMenuProps,+} from "@embedpdf/plugin-redaction/react"+import { RenderLayer, RenderPluginPackage } from "@embedpdf/plugin-render/react"+import {+ Rotate,+ RotatePluginPackage,+ useRotate,+} from "@embedpdf/plugin-rotate/react"+import {+ Scroller,+ ScrollPluginPackage,+ ScrollStrategy,+ useScroll,+ useScrollCapability,+ type PageLayout,+} from "@embedpdf/plugin-scroll/react"+import {+ SearchLayer,+ SearchPluginPackage,+ useSearch,+} from "@embedpdf/plugin-search/react"+import {+ CopyToClipboard,+ SelectionLayer,+ SelectionPluginPackage,+ useSelectionCapability,+ type SelectionSelectionMenuProps,+} from "@embedpdf/plugin-selection/react"+import {+ deserializeEntries,+ serializeEntries,+ SignatureMode,+ SignaturePluginPackage,+ useSignatureCapability,+} from "@embedpdf/plugin-signature/react"+import {+ SpreadMode,+ SpreadPluginPackage,+ useSpread,+} from "@embedpdf/plugin-spread/react"+import { StampPluginPackage } from "@embedpdf/plugin-stamp/react"+import { ThumbnailPluginPackage } from "@embedpdf/plugin-thumbnail/react"+import { TilingLayer, TilingPluginPackage } from "@embedpdf/plugin-tiling/react"+import {+ useIsViewportGated,+ useViewportCapability,+ useViewportElement,+ useViewportRef,+ ViewportElementContext,+ ViewportPluginPackage,+} from "@embedpdf/plugin-viewport/react"+import {+ MarqueeZoom,+ useZoom,+ ZoomMode,+ ZoomPluginPackage,+} from "@embedpdf/plugin-zoom/react"++import { loadSharedPdfEngine } from "@/lib/pdf-thumbnail-utils"+import { cn } from "@/lib/utils"+import { Badge } from "@/components/ui/badge"+import { Button } from "@/components/ui/button"+import { ColorPicker } from "@/components/ui/color-picker"+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSeparator,+ DropdownMenuShortcut,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu"+import { Input } from "@/components/ui/input"+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover"+import { ScrollArea } from "@/components/ui/scroll-area"+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select"+import { Spinner } from "@/components/ui/spinner"+import { ToastPrimitive, ToastProvider } from "@/components/ui/toast"+import { TooltipProvider } from "@/components/ui/tooltip"+import {+ DocumentViewerSidebarSkeleton,+ DocumentViewerThumbnailSidebar,+ useElementWidth,+ useInlineThumbnailSidebar,+} from "@/components/extend/document-viewer-sidebar"+import {+ PdfEditorCaptureDialog,+ PdfEditorConfirmDialog,+ PdfEditorLinkDialog,+ PdfEditorPasswordPrompt,+ PdfEditorPrintDialog,+ PdfEditorPropertiesDialog,+ PdfEditorSecurityDialog,+ PdfEditorShortcutsDialog,+ PdfEditorSignatureDialog,+} from "@/components/extend/pdf-editor-dialogs"+import {+ PdfEditorAttachmentsPanel,+ PdfEditorCommentsPanel,+ PdfEditorFormsPanel,+ PdfEditorOutlinePanel,+ PdfEditorPagesPanel,+ PdfEditorRedactionsPanel,+ PdfEditorSignaturesPanel,+ PdfEditorStampsPanel,+ PdfEditorThumbnailsPanel,+} from "@/components/extend/pdf-editor-panels"+import { PdfEditorPropertiesPanel } from "@/components/extend/pdf-editor-properties"+import {+ BookOpenGlyph,+ CameraGlyph,+ ChevronLeftGlyph,+ ChevronRightGlyph,+ CloseGlyph,+ CommentGlyph,+ CommentsGlyph,+ CopyGlyph,+ CursorGlyph,+ downloadArrayBuffer,+ downloadBlob,+ DownloadGlyph,+ EditGlyph,+ ExitFullscreenGlyph,+ ExternalLinkGlyph,+ EyeOffGlyph,+ FileTextGlyph,+ FullscreenGlyph,+ getPdfFileName,+ GridGlyph,+ GroupGlyph,+ HandGlyph,+ HighlighterGlyph,+ InfoGlyph,+ isTypingTarget,+ KeyboardGlyph,+ LayersGlyph,+ LinkGlyph,+ ListTreeGlyph,+ LockGlyph,+ MarqueeZoomGlyph,+ MoreGlyph,+ noop,+ PaletteGlyph,+ PanelLeftGlyph,+ PanelRightGlyph,+ PaperclipGlyph,+ PDF_EDITOR_ANNOTATION_TOOL_GROUPS,+ PDF_EDITOR_DEFAULT_COLOR_PRESETS,+ PDF_EDITOR_DEFAULT_FEATURES,+ PDF_EDITOR_DEFAULT_SIGNATURE_FONTS_URL,+ PDF_EDITOR_DEFAULT_STAMP_MANIFEST_URL,+ PDF_EDITOR_FORM_TOOLS,+ PDF_EDITOR_MODE_OPTIONS,+ PDF_EDITOR_SELECTION_COLOR,+ PdfEditorContextProvider,+ PdfEditorScrollArea,+ PdfEditorScrollAreaResolverContext,+ PdfEditorToolbarSeparator,+ PdfEditorToolButton,+ PdfEditorTooltip,+ PlusGlyph,+ PrintGlyph,+ RedactAreaGlyph,+ RedoGlyph,+ resolveDefaultScrollAreaViewport,+ RotateGlyph,+ SearchGlyph,+ ShieldGlyph,+ SignatureGlyph,+ SlidersGlyph,+ StampGlyph,+ StrikethroughGlyph,+ TextFieldGlyph,+ TextGlyph,+ toNormalizedRect,+ TrashGlyph,+ UnderlineGlyph,+ UndoGlyph,+ UngroupGlyph,+ UnlockGlyph,+ UploadGlyph,+ usePdfEditor,+ ZoomInGlyph,+ ZoomOutGlyph,+ type PdfEditorContextValue,+ type PdfEditorDialogRequest,+ type PdfEditorFeatureFlags,+ type PdfEditorGlyph,+ type PdfEditorLeftPanel,+ type PdfEditorMode,+ type PdfEditorNoticeTone,+ type PdfEditorResolvedFeatures,+ type PdfEditorRightPanel,+ type PdfEditorScrollAreaViewportResolver,+ type PdfEditorSelectionAction,+ type PdfEditorSelectionPage,+ type PdfEditorSelectionPayload,+} from "@/components/extend/pdf-editor-shared"++export type {+ PdfEditorFeatureFlags,+ PdfEditorLeftPanel,+ PdfEditorMode,+ PdfEditorNormalizedRect,+ PdfEditorRightPanel,+ PdfEditorSelectionAction,+ PdfEditorSelectionPayload,+} from "@/components/extend/pdf-editor-shared"++/* -------------------------------------------------------------------------- */+/* Public types */+/* -------------------------------------------------------------------------- */++export type PDFEditorPageOverlayProps = {+ pageNumber: number+ pageWidth: number+ pageHeight: number+ scale: number+ rotation: number+}++export type PDFEditorZoomLevel = number | "fit-page" | "fit-width" | "automatic"++export type PDFEditorToast = {+ message: string+ tone: PdfEditorNoticeTone+}++export type PDFEditorHandle = {+ /** Current PDF bytes including annotations, form values, and pending security changes. */+ getDocumentBuffer: () => Promise<ArrayBuffer>+ download: (fileName?: string) => Promise<void>+ print: (options?: PdfPrintOptions) => Promise<void>+ exportAnnotations: () => Promise<AnnotationTransferItem[]>+ importAnnotations: (items: AnnotationTransferItem[]) => void+ getFormValues: () => Record<string, string>+ setFormValues: (values: Record<string, string>) => Promise<void>+ /** Permanently applies every pending redaction mark. */+ applyRedactions: () => Promise<void>+ setMode: (mode: PdfEditorMode) => void+ /** Activates an EmbedPDF annotation tool id such as `highlight` or `ink`; `null` returns to selection. */+ setActiveTool: (toolId: string | null) => void+ scrollToPage: (pageNumber: number, options?: ScrollIntoViewOptions) => void+ undo: () => void+ redo: () => void+ getViewportElement: () => HTMLDivElement | null+}++export type PDFEditorProps = {+ className?: string+ /** A URL, or the PDF bytes as an ArrayBuffer, Uint8Array, Blob, or File. */+ src?: string | ArrayBuffer | Uint8Array | Blob+ fileName?: string+ defaultZoom?: PDFEditorZoomLevel+ defaultMode?: PdfEditorMode+ /** Author written into new annotations. Defaults to "Guest". */+ annotationAuthor?: string+ colorPresets?: string[]+ /** Turn individual editing capabilities off. Everything is enabled by default. */+ features?: PdfEditorFeatureFlags+ showToolbar?: boolean+ showUpload?: boolean+ showDownload?: boolean+ toolbarActions?: React.ReactNode+ /** Extra actions for the text selection menu. Each receives normalized page coordinates. */+ selectionActions?: PdfEditorSelectionAction[]+ /** Persist saved signatures in localStorage. Pass a string to use a custom storage key. */+ persistSignatures?: boolean | string+ /** Additional rubber stamp manifests to load next to the built-in library. */+ stampManifests?: string[]+ /** Stylesheet used for the typed-signature fonts. Pass `null` to skip loading web fonts. */+ signatureFontsStylesheetUrl?: string | null+ resolveScrollAreaViewport?: PdfEditorScrollAreaViewportResolver+ renderPageOverlay?: (props: PDFEditorPageOverlayProps) => React.ReactNode+ onDocumentLoadSuccess?: (info: {+ numPages: number+ documentId: string+ fileName: string+ }) => void+ onDocumentLoadError?: (message: string) => void+ onActivePageChange?: (pageNumber: number) => void+ onModeChange?: (mode: PdfEditorMode) => void+ onAnnotationEvent?: (event: AnnotationEvent) => void+ /** Fires with the full annotation set after every committed change (debounced). */+ onAnnotationsChange?: (items: AnnotationTransferItem[]) => void+ onFormValuesChange?: (values: Record<string, string>) => void+ onRedactionsApplied?: () => void+ onSave?: (result: { buffer: ArrayBuffer; fileName: string }) => void+ onCapture?: (event: CaptureAreaEvent) => void+ onPdfUpload?: (file: File) => void+ /** Routes editor notices to a host-owned toast system instead of the built-in viewport. */+ onToast?: (toast: PDFEditorToast) => void+ onSelectionAction?: (+ actionId: string,+ payload: PdfEditorSelectionPayload+ ) => void+}++/* -------------------------------------------------------------------------- */+/* Constants */+/* -------------------------------------------------------------------------- */++const PAGE_GAP = 24+const THUMBNAIL_PAGE_WIDTH = 92+const THUMBNAIL_IMAGE_PADDING = 8+const THUMBNAIL_WIDTH = THUMBNAIL_PAGE_WIDTH + THUMBNAIL_IMAGE_PADDING * 2+const THUMBNAIL_LABEL_HEIGHT = 24+const THUMBNAIL_GAP = 12+const THUMBNAIL_PANE_PADDING_Y = 16+const LEFT_SIDEBAR_WIDTH_CLASS = "w-56"+const LEFT_SIDEBAR_CLOSED_CLASS = "-ml-56"+const RIGHT_PANEL_WIDTH_CLASS = "w-84"+const RIGHT_PANEL_INLINE_MIN_WIDTH = 1100+const TOOLBAR_STACK_MAX_WIDTH = 640+const ZOOM_PRESETS = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 3, 4]+const MIN_ZOOM = 0.1+const MAX_ZOOM = 8+const PAGE_BASE_RENDER_MAX_SCALE = 1+const PAGE_BASE_RENDER_DPR = 1+const SEARCH_DEBOUNCE_MS = 300+const NOTICE_DURATION_MS = 4200+const TOOLTIP_DELAY_MS = 5+const SELECTION_MENU_OFFSET = 8+const SELECTION_MENU_HEIGHT = 36+const DEFAULT_SIGNATURE_STORAGE_KEY = "pdf-editor:signatures"+const DEFAULT_ANNOTATION_AUTHOR = "Guest"++const ZOOM_MODE_LABELS: Record<ZoomMode, string> = {+ [ZoomMode.FitPage]: "Fit page",+ [ZoomMode.FitWidth]: "Fit width",+ [ZoomMode.Automatic]: "Automatic",+}+const SPREAD_MODE_OPTIONS = [+ { label: "Single page", value: SpreadMode.None },+ { label: "Two pages", value: SpreadMode.Odd },+ { label: "Two pages, cover", value: SpreadMode.Even },+]+const SCROLL_DIRECTION_OPTIONS = [+ { label: "Scroll down", value: "vertical" },+ { label: "Scroll sideways", value: "horizontal" },+]++function toZoomLevel(level: PDFEditorZoomLevel): ZoomMode | number {+ if (level === "fit-page") return ZoomMode.FitPage+ if (level === "fit-width") return ZoomMode.FitWidth+ if (level === "automatic") return ZoomMode.Automatic+ return level+}++function isZoomMode(value: unknown): value is ZoomMode {+ return (+ value === ZoomMode.FitPage ||+ value === ZoomMode.FitWidth ||+ value === ZoomMode.Automatic+ )+}++/* -------------------------------------------------------------------------- */+/* Engine + document source */+/* -------------------------------------------------------------------------- */++function useSharedPdfEngine() {+ const [engine, setEngine] = React.useState<PdfEngine | null>(null)+ const [error, setError] = React.useState<Error | null>(null)++ React.useEffect(() => {+ let cancelled = false++ loadSharedPdfEngine().then(+ (loadedEngine) => {+ if (!cancelled) setEngine(loadedEngine)+ },+ (loadError: Error) => {+ if (!cancelled) setError(loadError)+ }+ )++ return () => {+ cancelled = true+ }+ }, [])++ return { engine, error }+}++type EditorSource =+ | { key: string; kind: "url"; url: string; name: string }+ | { key: string; kind: "buffer"; buffer: ArrayBuffer; name: string }++let sourceCounter = 0++function nextSourceKey() {+ sourceCounter += 1+ return `pdf-editor-source-${sourceCounter}`+}++function bytesToArrayBuffer(bytes: Uint8Array) {+ const copy = new ArrayBuffer(bytes.byteLength)+ new Uint8Array(copy).set(bytes)+ return copy+}++function useEditorSource(+ src: PDFEditorProps["src"],+ fileName: string | undefined+) {+ const [state, setState] = React.useState<{+ src: PDFEditorProps["src"]+ source: EditorSource | null+ loading: boolean+ }>({ src: undefined, source: null, loading: false })++ React.useEffect(() => {+ if (src === undefined || src === null) {+ setState({ src, source: null, loading: false })+ return+ }++ if (typeof src === "string") {+ setState({+ src,+ source: {+ key: nextSourceKey(),+ kind: "url",+ url: src,+ name: getPdfFileName(fileName, src),+ },+ loading: false,+ })+ return+ }++ if (src instanceof ArrayBuffer) {+ setState({+ src,+ source: {+ key: nextSourceKey(),+ kind: "buffer",+ buffer: src.slice(0),+ name: getPdfFileName(fileName),+ },+ loading: false,+ })+ return+ }++ if (src instanceof Uint8Array) {+ setState({+ src,+ source: {+ key: nextSourceKey(),+ kind: "buffer",+ buffer: bytesToArrayBuffer(src),+ name: getPdfFileName(fileName),+ },+ loading: false,+ })+ return+ }++ let cancelled = false+ const blobName = fileName ?? (src instanceof File ? src.name : undefined)++ setState({ src, source: null, loading: true })+ src.arrayBuffer().then((buffer) => {+ if (cancelled) return++ setState({+ src,+ source: {+ key: nextSourceKey(),+ kind: "buffer",+ buffer,+ name: getPdfFileName(blobName),+ },+ loading: false,+ })+ })++ return () => {+ cancelled = true+ }+ }, [fileName, src])++ const replace = React.useCallback((buffer: ArrayBuffer, name: string) => {+ setState((previous) => ({+ ...previous,+ source: { key: nextSourceKey(), kind: "buffer", buffer, name },+ loading: false,+ }))+ }, [])++ return { source: state.source, loading: state.loading, replace }+}++/* -------------------------------------------------------------------------- */+/* Annotation JSON serialization */+/* -------------------------------------------------------------------------- */++function arrayBufferToBase64(buffer: ArrayBuffer) {+ const bytes = new Uint8Array(buffer)+ let binary = ""++ for (let index = 0; index < bytes.length; index += 0x8000) {+ binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000))+ }++ return btoa(binary)+}++function base64ToArrayBuffer(value: string) {+ const binary = atob(value)+ const bytes = new Uint8Array(binary.length)++ for (let index = 0; index < binary.length; index += 1) {+ bytes[index] = binary.charCodeAt(index)+ }++ return bytes.buffer+}++type SerializedAnnotationItem = {+ annotation: PdfAnnotationObject+ ctx?: { data: string; mimeType?: string }+}++export function serializeAnnotationItems(items: AnnotationTransferItem[]) {+ return {+ format: "extend-ui/pdf-editor-annotations",+ version: 1,+ exportedAt: new Date().toISOString(),+ annotations: items.map((item): SerializedAnnotationItem => {+ const context = item.ctx as+ | { data?: ArrayBuffer; mimeType?: string }+ | undefined++ return {+ annotation: item.annotation,+ ...(context?.data instanceof ArrayBuffer+ ? {+ ctx: {+ data: arrayBufferToBase64(context.data),+ mimeType: context.mimeType,+ },+ }+ : {}),+ }+ }),+ }+}++export function deserializeAnnotationItems(+ payload: unknown+): AnnotationTransferItem[] {+ const list = Array.isArray(payload)+ ? payload+ : payload &&+ typeof payload === "object" &&+ Array.isArray((payload as { annotations?: unknown }).annotations)+ ? (payload as { annotations: unknown[] }).annotations+ : null++ if (!list) throw new Error("Unrecognized annotation export.")++ return list.map((entry) => {+ const item = entry as SerializedAnnotationItem++ if (!item || typeof item !== "object" || !item.annotation) {+ throw new Error("Unrecognized annotation export.")+ }++ return {+ annotation: item.annotation,+ ...(item.ctx?.data+ ? {+ ctx: {+ data: base64ToArrayBuffer(item.ctx.data),+ mimeType: item.ctx.mimeType,+ } as AnnotationTransferItem["ctx"],+ }+ : {}),+ }+ })+}++/* -------------------------------------------------------------------------- */+/* Viewport */+/* -------------------------------------------------------------------------- */++function PdfEditorViewport({+ children,+ className,+ documentId,+}: {+ children: React.ReactNode+ className?: string+ documentId: string+}) {+ const viewportRef = useViewportRef(documentId)+ const { provides: viewport } = useViewportCapability()+ const isGated = useIsViewportGated(documentId)+ const viewportGap = viewport?.getViewportGap() ?? 0++ return (+ <ViewportElementContext.Provider value={viewportRef}>+ <PdfEditorScrollArea+ className={className}+ orientation="both"+ scrollbarGutter={false}+ viewportClassName="relative select-none selection:bg-transparent selection:text-inherit"+ viewportProps={{ style: { padding: viewportGap } }}+ viewportRef={viewportRef}+ >+ {isGated ? null : children}+ </PdfEditorScrollArea>+ </ViewportElementContext.Provider>+ )+}++function PdfEditorViewportBridge({+ viewportElementRef,+}: {+ viewportElementRef: React.MutableRefObject<HTMLDivElement | null>+}) {+ const elementRef = useViewportElement()++ React.useEffect(() => {+ viewportElementRef.current = elementRef?.current ?? null+ })++ return null+}++/* -------------------------------------------------------------------------- */+/* Selection menus rendered inside the page layers */+/* -------------------------------------------------------------------------- */++function SelectionMenuShell({+ rect,+ placement,+ menuWrapperProps,+ children,+}: {+ rect: SelectionSelectionMenuProps["rect"]+ placement: SelectionSelectionMenuProps["placement"]+ menuWrapperProps: SelectionSelectionMenuProps["menuWrapperProps"]+ children: React.ReactNode+}) {+ return (+ <div {...menuWrapperProps}>+ <div+ data-slot="pdf-editor-selection-menu"+ className="flex items-center gap-0.5 rounded-lg border bg-popover p-1 text-popover-foreground shadow-lg"+ style={{+ position: "absolute",+ left: 0,+ top: placement.suggestTop+ ? -(SELECTION_MENU_HEIGHT + SELECTION_MENU_OFFSET)+ : rect.size.height + SELECTION_MENU_OFFSET,+ pointerEvents: "auto",+ cursor: "default",+ whiteSpace: "nowrap",+ }}+ onPointerDown={(event) => event.stopPropagation()}+ >+ <TooltipProvider delay={TOOLTIP_DELAY_MS}>{children}</TooltipProvider>+ </div>+ </div>+ )+}++function MenuButton({+ label,+ glyph: Glyph,+ onClick,+ disabled,+ destructive,+}: {+ label: string+ glyph: PdfEditorGlyph+ onClick: () => void+ disabled?: boolean+ destructive?: boolean+}) {+ return (+ <PdfEditorToolButton+ label={label}+ size="icon-xs"+ disabled={disabled}+ className={cn(destructive && "text-destructive hover:text-destructive")}+ onClick={(event) => {+ event.stopPropagation()+ onClick()+ }}+ >+ <Glyph className="size-3.5" />+ </PdfEditorToolButton>+ )+}++async function buildSelectionPayload(+ documentId: string,+ document: PdfDocumentObject | null,+ selectionScope: ReturnType<+ NonNullable<+ ReturnType<typeof useSelectionCapability>["provides"]+ >["forDocument"]+ >+): Promise<PdfEditorSelectionPayload | null> {+ const formatted = selectionScope.getFormattedSelection()++ if (formatted.length === 0) return null++ let text = ""++ try {+ const lines = await selectionScope.getSelectedText().toPromise()+ text = lines.join("\n")+ } catch {+ text = ""+ }++ const pages: PdfEditorSelectionPage[] = formatted.map((page) => {+ const pageSize = document?.pages[page.pageIndex]?.size ?? {+ width: 1,+ height: 1,+ }++ return {+ pageIndex: page.pageIndex,+ pageNumber: page.pageIndex + 1,+ pageSize,+ rect: page.rect,+ rects: page.segmentRects,+ normalizedRect: toNormalizedRect(page.rect, pageSize),+ normalizedRects: page.segmentRects.map((rect) =>+ toNormalizedRect(rect, pageSize)+ ),+ }+ })++ return { documentId, text, pages, ...pages[0] }+}++function PdfEditorTextSelectionMenu({+ documentId,+ rect,+ placement,+ menuWrapperProps,+}: SelectionSelectionMenuProps & { documentId: string }) {+ const { provides: selectionCapability } = useSelectionCapability()+ const { provides: annotationCapability } = useAnnotationCapability()+ const { provides: annotation } = useAnnotation(documentId)+ const { provides: redaction } = useRedaction(documentId)+ const editor = usePdfEditor()+ const selectionScope = React.useMemo(+ () => selectionCapability?.forDocument(documentId) ?? null,+ [documentId, selectionCapability]+ )+ const canAnnotate =+ editor.features.annotate && editor.permissions.canModifyAnnotations+ const canRedact =+ editor.features.redact && editor.permissions.canModifyContents++ const createMarkup = (+ toolId: string,+ subtype:+ | PdfAnnotationSubtype.HIGHLIGHT+ | PdfAnnotationSubtype.UNDERLINE+ | PdfAnnotationSubtype.STRIKEOUT,+ options: { select?: boolean; openComments?: boolean } = {}+ ) => {+ if (!selectionScope || !annotation) return++ const formatted = selectionScope.getFormattedSelection()++ if (formatted.length === 0) return++ const defaults = (annotationCapability?.getTool(toolId)?.defaults ??+ {}) as Record<string, unknown>++ const finish = (text: string[]) => {+ let firstId: { pageIndex: number; id: string } | null = null++ for (const page of formatted) {+ const id = uuidV4()++ annotation.createAnnotation(page.pageIndex, {+ ...defaults,+ id,+ type: subtype,+ pageIndex: page.pageIndex,+ rect: page.rect,+ segmentRects: page.segmentRects,+ author: editor.annotationAuthor,+ created: new Date(),+ modified: new Date(),+ flags: ["print"],+ custom: text.length ? { text: text.join("\n") } : undefined,+ } as PdfAnnotationObject)++ firstId ??= { pageIndex: page.pageIndex, id }+ }++ selectionScope.clear()++ if (options.select && firstId) {+ annotation.selectAnnotation(firstId.pageIndex, firstId.id)+ }++ if (options.openComments) editor.setRightPanel("comments")+ }++ selectionScope.getSelectedText().wait(finish, () => finish([]))+ }++ const runCustomAction = async (action: PdfEditorSelectionAction) => {+ if (!selectionScope) return++ const payload = await buildSelectionPayload(+ documentId,+ editor.document,+ selectionScope+ )++ if (!payload) return++ action.onSelect?.(payload)+ editor.onSelectionAction?.(action.id, payload)++ if (!action.keepSelection) selectionScope.clear()+ }++ return (+ <SelectionMenuShell+ rect={rect}+ placement={placement}+ menuWrapperProps={menuWrapperProps}+ >+ <MenuButton+ label="Copy"+ glyph={CopyGlyph}+ onClick={() => {+ selectionScope?.copyToClipboard()+ selectionScope?.clear()+ }}+ />+ {canAnnotate ? (+ <>+ <PdfEditorToolbarSeparator />+ <MenuButton+ label="Highlight"+ glyph={HighlighterGlyph}+ onClick={() =>+ createMarkup("highlight", PdfAnnotationSubtype.HIGHLIGHT)+ }+ />+ <MenuButton+ label="Underline"+ glyph={UnderlineGlyph}+ onClick={() =>+ createMarkup("underline", PdfAnnotationSubtype.UNDERLINE)+ }+ />+ <MenuButton+ label="Strikethrough"+ glyph={StrikethroughGlyph}+ onClick={() =>+ createMarkup("strikeout", PdfAnnotationSubtype.STRIKEOUT)+ }+ />+ {editor.features.comments ? (+ <MenuButton+ label="Comment"+ glyph={CommentGlyph}+ onClick={() =>+ createMarkup("highlight", PdfAnnotationSubtype.HIGHLIGHT, {+ select: true,+ openComments: true,+ })+ }+ />+ ) : null}+ <MenuButton+ label="Add link"+ glyph={LinkGlyph}+ onClick={() =>+ editor.openDialog({ type: "link", source: "selection" })+ }+ />+ </>+ ) : null}+ {canRedact ? (+ <>+ <PdfEditorToolbarSeparator />+ <MenuButton+ label="Mark for redaction"+ glyph={EyeOffGlyph}+ onClick={() => {+ redaction?.queueCurrentSelectionAsPending().wait(+ () => {+ selectionScope?.clear()+ editor.setRightPanel("redactions")+ },+ () =>+ editor.notify("The selection could not be marked.", "error")+ )+ }}+ />+ </>+ ) : null}+ {editor.selectionActions.length > 0 ? (+ <>+ <PdfEditorToolbarSeparator />+ {editor.selectionActions.map((action) => (+ <PdfEditorTooltip key={action.id} label={action.label}>+ <Button+ type="button"+ size="xs"+ variant="ghost"+ onClick={(event) => {+ event.stopPropagation()+ void runCustomAction(action)+ }}+ >+ {action.icon}+ {action.label}+ </Button>+ </PdfEditorTooltip>+ ))}+ </>+ ) : null}+ </SelectionMenuShell>+ )+}++const STAMP_SOURCE_TYPES = new Set<PdfAnnotationSubtype>([+ PdfAnnotationSubtype.INK,+ PdfAnnotationSubtype.SQUARE,+ PdfAnnotationSubtype.CIRCLE,+ PdfAnnotationSubtype.LINE,+ PdfAnnotationSubtype.POLYLINE,+ PdfAnnotationSubtype.POLYGON,+ PdfAnnotationSubtype.FREETEXT,+ PdfAnnotationSubtype.STAMP,+ PdfAnnotationSubtype.TEXT,+])++function PdfEditorAnnotationMenu({+ documentId,+ selected,+ context,+ rect,+ placement,+ menuWrapperProps,+}: AnnotationSelectionMenuProps & { documentId: string }) {+ const { provides: annotation } = useAnnotation(documentId)+ const { provides: redaction } = useRedaction(documentId)+ const editor = usePdfEditor()++ if (!selected || !annotation) return null++ const object = context.annotation.object+ const { pageIndex, id } = object+ const isRedact = object.type === PdfAnnotationSubtype.REDACT+ const isWidget = object.type === PdfAnnotationSubtype.WIDGET+ const isLink = object.type === PdfAnnotationSubtype.LINK+ const isLocked = (object.flags ?? []).includes("locked")+ const canModify = editor.permissions.canModifyAnnotations+ const canDelete = canModify && !context.structurallyLocked++ const remove = () => annotation.deleteAnnotation(pageIndex, id)++ if (isRedact) {+ return (+ <SelectionMenuShell+ rect={rect}+ placement={placement}+ menuWrapperProps={menuWrapperProps}+ >+ <MenuButton+ label="Apply redaction"+ glyph={EyeOffGlyph}+ disabled={!editor.permissions.canModifyContents}+ onClick={() =>+ editor.openDialog({+ type: "confirm",+ title: "Apply this redaction?",+ description: "The marked content is removed permanently.",+ confirmLabel: "Apply",+ onConfirm: () => {+ redaction+ ?.commitPending(pageIndex, id)+ .wait(noop, () =>+ editor.notify(+ "The redaction could not be applied.",+ "error"+ )+ )+ },+ })+ }+ />+ <MenuButton+ label="Style"+ glyph={SlidersGlyph}+ onClick={() => editor.setRightPanel("properties")}+ />+ <MenuButton+ label="Remove mark"+ glyph={TrashGlyph}+ destructive+ onClick={remove}+ />+ </SelectionMenuShell>+ )+ }++ if (isLink) {+ const target = (object as PdfLinkAnnoObject).target++ return (+ <SelectionMenuShell+ rect={rect}+ placement={placement}+ menuWrapperProps={menuWrapperProps}+ >+ <MenuButton+ label="Open link"+ glyph={ExternalLinkGlyph}+ disabled={!target}+ onClick={() => {+ if (!target) return++ annotation.navigateTarget(target).wait((result) => {+ if (result.outcome === "uri") {+ window.open(result.uri, "_blank", "noopener")+ }+ }, noop)+ }}+ />+ <MenuButton+ label="Edit link"+ glyph={EditGlyph}+ disabled={!canModify}+ onClick={() =>+ editor.openDialog({ type: "link", source: "annotation" })+ }+ />+ <MenuButton+ label="Delete"+ glyph={TrashGlyph}+ destructive+ disabled={!canDelete}+ onClick={remove}+ />+ </SelectionMenuShell>+ )+ }++ return (+ <SelectionMenuShell+ rect={rect}+ placement={placement}+ menuWrapperProps={menuWrapperProps}+ >+ {!isWidget && editor.features.comments ? (+ <MenuButton+ label="Comment"+ glyph={CommentGlyph}+ onClick={() => editor.setRightPanel("comments")}+ />+ ) : null}+ <MenuButton+ label="Properties"+ glyph={SlidersGlyph}+ onClick={() => editor.setRightPanel("properties")}+ />+ {!isWidget && canModify ? (+ <MenuButton+ label="Add link"+ glyph={LinkGlyph}+ onClick={() =>+ editor.openDialog({ type: "link", source: "annotation" })+ }+ />+ ) : null}+ {!isWidget &&+ editor.features.stamps &&+ canModify &&+ STAMP_SOURCE_TYPES.has(object.type) ? (+ <MenuButton+ label="Save as stamp"+ glyph={StampGlyph}+ onClick={() => editor.setRightPanel("stamps")}+ />+ ) : null}+ {!isWidget && canModify ? (+ <MenuButton+ label={isLocked ? "Unlock" : "Lock"}+ glyph={isLocked ? UnlockGlyph : LockGlyph}+ onClick={() => {+ const flags = object.flags ?? []+ annotation.updateAnnotation(pageIndex, id, {+ flags: isLocked+ ? flags.filter((flag) => flag !== "locked")+ : [...flags, "locked"],+ })+ }}+ />+ ) : null}+ <MenuButton+ label="Delete"+ glyph={TrashGlyph}+ destructive+ disabled={!canDelete}+ onClick={remove}+ />+ </SelectionMenuShell>+ )+}++function PdfEditorGroupMenu({+ documentId,+ selected,+ context,+ rect,+ placement,+ menuWrapperProps,+}: GroupSelectionMenuProps & { documentId: string }) {+ const { provides: annotation } = useAnnotation(documentId)+ const editor = usePdfEditor()++ if (!selected || !annotation) return null++ const groupingAction = annotation.getGroupingAction()+ const canModify = editor.permissions.canModifyAnnotations++ return (+ <SelectionMenuShell+ rect={rect}+ placement={placement}+ menuWrapperProps={menuWrapperProps}+ >+ <span className="px-1.5 text-xs text-muted-foreground">+ {context.annotations.length} selected+ </span>+ <MenuButton+ label={groupingAction === "ungroup" ? "Ungroup" : "Group"}+ glyph={groupingAction === "ungroup" ? UngroupGlyph : GroupGlyph}+ disabled={!canModify || groupingAction === "disabled"}+ onClick={() => {+ if (groupingAction === "ungroup") {+ annotation.ungroupAnnotations(context.annotations[0].object.id)+ } else {+ annotation.groupAnnotations()+ }+ }}+ />+ <MenuButton+ label="Properties"+ glyph={SlidersGlyph}+ onClick={() => editor.setRightPanel("properties")}+ />+ <MenuButton+ label="Delete all"+ glyph={TrashGlyph}+ destructive+ disabled={!canModify}+ onClick={() =>+ annotation.deleteAnnotations(+ context.annotations.map((item) => ({+ pageIndex: item.object.pageIndex,+ id: item.object.id,+ }))+ )+ }+ />+ </SelectionMenuShell>+ )+}++function PdfEditorRedactionMenu({+ documentId,+ selected,+ context,+ rect,+ placement,+ menuWrapperProps,+}: RedactionSelectionMenuProps & { documentId: string }) {+ const { provides: redaction } = useRedaction(documentId)+ const editor = usePdfEditor()++ if (!selected || !redaction) return null++ const { page, id } = context.item++ return (+ <SelectionMenuShell+ rect={rect}+ placement={placement}+ menuWrapperProps={menuWrapperProps}+ >+ <MenuButton+ label="Apply redaction"+ glyph={EyeOffGlyph}+ disabled={!editor.permissions.canModifyContents}+ onClick={() =>+ editor.openDialog({+ type: "confirm",+ title: "Apply this redaction?",+ description: "The marked content is removed permanently.",+ confirmLabel: "Apply",+ onConfirm: () => {+ redaction+ .commitPending(page, id)+ .wait(noop, () =>+ editor.notify("The redaction could not be applied.", "error")+ )+ },+ })+ }+ />+ <MenuButton+ label="Remove mark"+ glyph={TrashGlyph}+ destructive+ onClick={() => redaction.removePending(page, id)}+ />+ </SelectionMenuShell>+ )+}++/* -------------------------------------------------------------------------- */+/* Toolbar controls */+/* -------------------------------------------------------------------------- */++function PdfEditorPageControl({+ activePage,+ numPages,+ disabled,+ onPageChange,+}: {+ activePage: number+ numPages: number+ disabled: boolean+ onPageChange: (pageNumber: number) => void+}) {+ const inputRef = React.useRef<HTMLInputElement>(null)+ const displayPage = numPages ? activePage : 1+ const [isEditing, setIsEditing] = React.useState(false)+ const [draftPage, setDraftPage] = React.useState(() => String(displayPage))++ React.useEffect(() => {+ if (!isEditing) return++ inputRef.current?.focus()+ inputRef.current?.select()+ }, [isEditing])++ const applyPageDraft = React.useCallback(+ (value: string) => {+ const trimmedValue = value.trim()++ if (!trimmedValue) return++ const parsedPage = Number(trimmedValue)++ if (!Number.isInteger(parsedPage)) return++ onPageChange(Math.min(Math.max(parsedPage, 1), Math.max(numPages, 1)))+ },+ [numPages, onPageChange]+ )++ return (+ <div className="flex items-center text-sm whitespace-nowrap text-primary">+ <span>Page</span>+ {isEditing ? (+ <Input+ ref={inputRef}+ aria-label="Page number"+ inputMode="numeric"+ pattern="[0-9]*"+ size="sm"+ value={draftPage}+ className="mx-1 w-14 min-w-14 rounded-md [&_[data-slot=input]]:text-center"+ onBlur={() => setIsEditing(false)}+ onChange={(event: React.ChangeEvent<HTMLInputElement>) => {+ const nextValue = event.target.value++ setDraftPage(nextValue)+ applyPageDraft(nextValue)+ }}+ onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {+ if (event.key === "Enter" || event.key === "Escape") {+ event.currentTarget.blur()+ }+ }}+ />+ ) : (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="font-normal"+ aria-label={`Current page ${displayPage}. Edit page number`}+ disabled={disabled || !numPages}+ onClick={() => {+ setDraftPage(String(displayPage))+ setIsEditing(true)+ }}+ >+ {displayPage}+ </Button>+ )}+ <span>of {numPages || "–"}</span>+ </div>+ )+}++function PdfEditorZoomControl({+ documentId,+ disabled,+}: {+ documentId: string+ disabled: boolean+}) {+ const { state, provides: zoom } = useZoom(documentId)+ const current = state.currentZoomLevel+ const selectValue = isZoomMode(state.zoomLevel)+ ? state.zoomLevel+ : String(Number(current.toFixed(2)))+ const presets = ZOOM_PRESETS.includes(Number(current.toFixed(2)))+ ? ZOOM_PRESETS+ : [...ZOOM_PRESETS, Number(current.toFixed(2))].sort((a, b) => a - b)++ return (+ <div className="flex items-center gap-0.5">+ <PdfEditorToolButton+ label="Zoom out"+ shortcut="mod+-"+ disabled={disabled || current <= MIN_ZOOM}+ onClick={() => zoom?.zoomOut()}+ >+ <ZoomOutGlyph className="size-4" />+ </PdfEditorToolButton>+ <Select+ value={selectValue}+ disabled={disabled}+ modal={false}+ onValueChange={(value) => {+ const next = String(value)+ zoom?.requestZoom(isZoomMode(next) ? next : Number(next))+ }}+ >+ <SelectTrigger+ size="sm"+ className="w-[104px] min-w-[104px]"+ aria-label="Zoom level"+ >+ <SelectValue placeholder="Zoom">+ {Math.round(current * 100)}%+ </SelectValue>+ </SelectTrigger>+ <SelectContent alignItemWithTrigger={false}>+ {(Object.keys(ZOOM_MODE_LABELS) as ZoomMode[]).map((mode) => (+ <SelectItem key={mode} value={mode}>+ {ZOOM_MODE_LABELS[mode]}+ </SelectItem>+ ))}+ {presets.map((preset) => (+ <SelectItem key={preset} value={String(preset)}>+ {Math.round(preset * 100)}%+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <PdfEditorToolButton+ label="Zoom in"+ shortcut="mod+="+ disabled={disabled || current >= MAX_ZOOM}+ onClick={() => zoom?.zoomIn()}+ >+ <ZoomInGlyph className="size-4" />+ </PdfEditorToolButton>+ </div>+ )+}++function PdfEditorSearchControl({+ documentId,+ disabled,+ open,+ onOpenChange,+}: {+ documentId: string+ disabled: boolean+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { state, provides } = useSearch(documentId)+ const { provides: scroll } = useScroll(documentId)+ const [draft, setDraft] = React.useState("")+ const [query, setQuery] = React.useState("")+ const [isSearching, setIsSearching] = React.useState(false)+ const providesRef = React.useRef(provides)+ const scrollRef = React.useRef(scroll)+ const requestIdRef = React.useRef(0)+ const inputRef = React.useRef<HTMLInputElement>(null)++ React.useEffect(() => {+ providesRef.current = provides+ scrollRef.current = scroll+ }, [provides, scroll])++ React.useEffect(() => {+ if (!open) return++ const frame = window.requestAnimationFrame(() => inputRef.current?.focus())++ return () => window.cancelAnimationFrame(frame)+ }, [open])++ const scrollToResult = React.useCallback(+ (index: number) => {+ const result = state.results[index]+ if (!result || !scroll) return++ const firstRect = result.rects[0]++ scroll.scrollToPage({+ pageNumber: result.pageIndex + 1,+ ...(firstRect+ ? {+ pageCoordinates: { x: firstRect.origin.x, y: firstRect.origin.y },+ alignY: 30,+ }+ : {}),+ behavior: "auto",+ })+ },+ [scroll, state.results]+ )++ const runSearch = React.useCallback((rawQuery: string) => {+ const nextQuery = rawQuery.trim()+ const requestId = requestIdRef.current + 1+ requestIdRef.current = requestId+ setQuery(nextQuery)++ const searchProvider = providesRef.current+ const scrollProvider = scrollRef.current++ if (!searchProvider) {+ setIsSearching(false)+ return+ }++ if (!nextQuery) {+ searchProvider.stopSearch()+ setIsSearching(false)+ return+ }++ setIsSearching(true)+ searchProvider.startSearch()+ searchProvider.searchAllPages(nextQuery).wait(+ (result) => {+ if (requestIdRef.current !== requestId) return++ const first = result.results[0]++ if (first && scrollProvider) {+ searchProvider.goToResult(0)+ const firstRect = first.rects[0]++ scrollProvider.scrollToPage({+ pageNumber: first.pageIndex + 1,+ ...(firstRect+ ? {+ pageCoordinates: {+ x: firstRect.origin.x,+ y: firstRect.origin.y,+ },+ alignY: 30,+ }+ : {}),+ behavior: "auto",+ })+ }++ setIsSearching(false)+ },+ () => {+ if (requestIdRef.current === requestId) setIsSearching(false)+ }+ )+ }, [])++ React.useEffect(() => {+ if (!draft.trim()) return++ const timeout = window.setTimeout(+ () => runSearch(draft),+ SEARCH_DEBOUNCE_MS+ )++ return () => window.clearTimeout(timeout)+ }, [draft, runSearch])++ const clear = () => {+ requestIdRef.current += 1+ setDraft("")+ setQuery("")+ setIsSearching(false)+ provides?.stopSearch()+ }++ const navigate = (direction: 1 | -1) => {+ if (!provides || state.total === 0) return++ scrollToResult(+ direction === 1 ? provides.nextResult() : provides.previousResult()+ )+ }++ const resultLabel = isSearching+ ? "Searching…"+ : !query+ ? "Type to search"+ : state.total+ ? `${state.activeResultIndex + 1} / ${state.total}`+ : "No results"++ return (+ <Popover open={open} onOpenChange={onOpenChange}>+ <PdfEditorTooltip label="Search" shortcut="mod+F">+ <PopoverTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Search"+ disabled={disabled}+ className={cn(query && "text-primary")}+ >+ <SearchGlyph className="size-4" />+ </Button>+ </PopoverTrigger>+ </PdfEditorTooltip>+ <PopoverContent+ align="end"+ className="w-72 p-0 [&>[data-slot=popover-viewport]]:p-3.5!"+ >+ <div className="space-y-3">+ <Input+ ref={inputRef}+ placeholder="Search text"+ value={draft}+ onChange={(event: React.ChangeEvent<HTMLInputElement>) => {+ const next = event.target.value+ setDraft(next)++ if (next.trim()) {+ setIsSearching(true)+ } else {+ clear()+ }+ }}+ onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {+ if (event.key !== "Enter") return++ event.preventDefault()++ if (state.total) {+ navigate(event.shiftKey ? -1 : 1)+ } else if (draft.trim()) {+ runSearch(draft)+ }+ }}+ />+ <div className="flex items-center justify-between gap-2">+ <div className="min-w-0 truncate text-xs text-muted-foreground">+ {resultLabel}+ </div>+ <div className="flex shrink-0 items-center gap-1">+ <Button+ type="button"+ variant="outline"+ size="icon-sm"+ aria-label="Previous result"+ disabled={isSearching || state.total === 0}+ onClick={() => navigate(-1)}+ >+ <ChevronLeftGlyph className="size-4" />+ </Button>+ <Button+ type="button"+ variant="outline"+ size="icon-sm"+ aria-label="Next result"+ disabled={isSearching || state.total === 0}+ onClick={() => navigate(1)}+ >+ <ChevronRightGlyph className="size-4" />+ </Button>+ <Button type="button" variant="outline" size="sm" onClick={clear}>+ Clear+ </Button>+ </div>+ </div>+ </div>+ </PopoverContent>+ </Popover>+ )+}++function PdfEditorModeSwitch({+ mode,+ features,+ compact = false,+ onModeChange,+}: {+ mode: PdfEditorMode+ features: PdfEditorResolvedFeatures+ compact?: boolean+ onModeChange: (mode: PdfEditorMode) => void+}) {+ const options = PDF_EDITOR_MODE_OPTIONS.filter(+ (option) => option.feature === null || features[option.feature]+ )++ return (+ <div+ role="group"+ aria-label="Editor mode"+ className="flex shrink-0 items-center gap-0.5 rounded-lg bg-muted p-0.5"+ >+ {options.map((option) => {+ const Glyph = option.glyph+ const active = option.id === mode++ return (+ <Button+ key={option.id}+ type="button"+ size={compact ? "icon-xs" : "xs"}+ variant={active ? "default" : "ghost"}+ aria-pressed={active}+ aria-label={option.label}+ className={cn("gap-1.5", !active && "text-muted-foreground")}+ onClick={() => onModeChange(option.id)}+ >+ <Glyph className="size-3.5" />+ {compact ? null : (+ <span className="hidden md:inline">{option.label}</span>+ )}+ </Button>+ )+ })}+ </div>+ )+}++/* -------------------------------------------------------------------------- */+/* Side panel shells */+/* -------------------------------------------------------------------------- */++function PanelTabStrip<T extends string>({+ tabs,+ value,+ onChange,+ onClose,+ label,+}: {+ tabs: Array<{ id: T; label: string; glyph: PdfEditorGlyph }>+ value: T | null+ onChange: (value: T) => void+ onClose: () => void+ label: string+}) {+ return (+ <div className="flex shrink-0 items-center justify-between gap-1 border-b px-1.5 py-1">+ <TooltipProvider delay={TOOLTIP_DELAY_MS}>+ <div+ className="flex min-w-0 items-center gap-0.5 overflow-x-auto"+ role="tablist"+ aria-label={label}+ >+ {tabs.map((tab) => {+ const Glyph = tab.glyph++ return (+ <PdfEditorToolButton+ key={tab.id}+ label={tab.label}+ active={value === tab.id}+ role="tab"+ aria-selected={value === tab.id}+ onClick={() => onChange(tab.id)}+ >+ <Glyph className="size-4" />+ </PdfEditorToolButton>+ )+ })}+ </div>+ <PdfEditorToolButton+ label="Close panel"+ size="icon-xs"+ onClick={onClose}+ >+ <CloseGlyph className="size-3.5" />+ </PdfEditorToolButton>+ </TooltipProvider>+ </div>+ )+}++function PdfEditorRightPanelShell({+ open,+ inline,+ children,+}: {+ open: boolean+ inline: boolean+ children: React.ReactNode+}) {+ return (+ <aside+ data-slot="pdf-editor-right-panel"+ data-panel-open={open ? "true" : "false"}+ className={cn(+ "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",+ RIGHT_PANEL_WIDTH_CLASS,+ inline && "relative z-auto translate-x-0 shadow-none",+ open+ ? "mr-0 translate-x-0"+ : inline+ ? "-mr-84 border-l-0"+ : "pointer-events-none translate-x-full border-l-0"+ )}+ >+ {children}+ </aside>+ )+}++/* -------------------------------------------------------------------------- */+/* Signature persistence + engine warm-up utilities */+/* -------------------------------------------------------------------------- */++function PdfEditorSignaturePersistence({+ storageKey,+}: {+ storageKey: string | null+}) {+ const { provides: signatureCapability } = useSignatureCapability()++ React.useEffect(() => {+ if (!signatureCapability || !storageKey) return++ try {+ const raw = window.localStorage.getItem(storageKey)++ if (raw && signatureCapability.getEntries().length === 0) {+ signatureCapability.loadEntries(deserializeEntries(JSON.parse(raw)))+ }+ } catch {+ // Ignore corrupt or unavailable storage.+ }++ return signatureCapability.onEntriesChange((entries) => {+ try {+ window.localStorage.setItem(+ storageKey,+ JSON.stringify(serializeEntries(entries))+ )+ } catch {+ // Storage may be unavailable (private mode, quota).+ }+ })+ }, [signatureCapability, storageKey])++ return null+}++/* -------------------------------------------------------------------------- */+/* Fallback shell (engine loading, document loading, errors, empty) */+/* -------------------------------------------------------------------------- */++function PdfEditorFallbackShell({+ className,+ fileName,+ showToolbar,+ showUpload,+ state,+ errorMessage = "The PDF could not be loaded.",+ onUploadFile,+ children,+}: {+ className?: string+ fileName?: string+ showToolbar: boolean+ showUpload: boolean+ state: "loading" | "error" | "empty" | "password"+ errorMessage?: string+ onUploadFile?: (file: File) => void+ children?: React.ReactNode+}) {+ const inputRef = React.useRef<HTMLInputElement>(null)++ return (+ <div+ data-slot="pdf-editor"+ data-state={state}+ className={cn(+ "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",+ className+ )}+ >+ {showToolbar ? (+ <div className="flex min-h-12 items-center justify-between gap-2 border-b px-3 py-2">+ <div className="flex min-w-0 items-center gap-2 text-sm">+ <FileTextGlyph className="size-4 shrink-0 text-muted-foreground" />+ <span className="truncate text-muted-foreground">+ {fileName ?? "PDF editor"}+ </span>+ </div>+ {showUpload && onUploadFile ? (+ <>+ <input+ ref={inputRef}+ type="file"+ accept="application/pdf,.pdf"+ className="sr-only"+ tabIndex={-1}+ onChange={(event) => {+ const file = event.target.files?.[0]+ if (file) onUploadFile(file)+ event.currentTarget.value = ""+ }}+ />+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={() => inputRef.current?.click()}+ >+ <UploadGlyph className="size-4" />+ Open PDF+ </Button>+ </>+ ) : null}+ </div>+ ) : null}+ <div className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30">+ {children ? (+ children+ ) : state === "loading" ? (+ <div className="grid flex-1 place-items-center">+ <Spinner className="size-4" />+ </div>+ ) : state === "error" ? (+ <div className="grid flex-1 place-items-center p-6 text-center text-sm text-muted-foreground">+ {errorMessage}+ </div>+ ) : (+ <div className="grid flex-1 place-items-center p-6 text-center text-sm text-muted-foreground">+ <div className="max-w-sm space-y-3">+ <div className="font-medium text-foreground">+ Open a PDF to start editing+ </div>+ <div>+ Pass a URL or file with the <code>src</code> prop, or use the+ upload control.+ </div>+ </div>+ </div>+ )}+ </div>+ </div>+ )+}++/* -------------------------------------------------------------------------- */+/* Editor (per loaded document) */+/* -------------------------------------------------------------------------- */++type EditorHandleImpl = PDFEditorHandle++type PdfEditorInnerProps = {+ documentId: string+ document: PdfDocumentObject | null+ fileName: string+ className?: string+ defaultZoom: PDFEditorZoomLevel+ defaultMode: PdfEditorMode+ leftPanel: PdfEditorLeftPanel | null+ setLeftPanel: React.Dispatch<React.SetStateAction<PdfEditorLeftPanel | null>>+ formDesignMode: boolean+ setFormDesignMode: React.Dispatch<React.SetStateAction<boolean>>+ annotationAuthor: string+ features: PdfEditorResolvedFeatures+ showToolbar: boolean+ showUpload: boolean+ showDownload: boolean+ toolbarActions?: React.ReactNode+ selectionActions: PdfEditorSelectionAction[]+ signatureFontsStylesheetUrl: string | null+ renderPageOverlay?: (props: PDFEditorPageOverlayProps) => React.ReactNode+ handleRef: React.MutableRefObject<EditorHandleImpl | null>+ onReplaceDocument: (buffer: ArrayBuffer, fileName: string) => void+ onUploadFile: (file: File) => void+ onActivePageChange?: (pageNumber: number) => void+ onModeChange?: (mode: PdfEditorMode) => void+ onAnnotationEvent?: (event: AnnotationEvent) => void+ onAnnotationsChange?: (items: AnnotationTransferItem[]) => void+ onFormValuesChange?: (values: Record<string, string>) => void+ onRedactionsApplied?: () => void+ onSave?: (result: { buffer: ArrayBuffer; fileName: string }) => void+ onCapture?: (event: CaptureAreaEvent) => void+ onToast?: (toast: PDFEditorToast) => void+ onSelectionAction?: (+ actionId: string,+ payload: PdfEditorSelectionPayload+ ) => void+}++const LEFT_PANEL_TABS: Array<{+ id: PdfEditorLeftPanel+ label: string+ glyph: PdfEditorGlyph+ feature: keyof PdfEditorFeatureFlags | null+}> = [+ { id: "thumbnails", label: "Thumbnails", glyph: GridGlyph, feature: null },+ { id: "outline", label: "Outline", glyph: ListTreeGlyph, feature: "outline" },+ {+ id: "attachments",+ label: "Attachments",+ glyph: PaperclipGlyph,+ feature: "attachments",+ },+ {+ id: "pages",+ label: "Organize pages",+ glyph: LayersGlyph,+ feature: "pages",+ },+]++const RIGHT_PANEL_TABS: Array<{+ id: PdfEditorRightPanel+ label: string+ glyph: PdfEditorGlyph+ feature: keyof PdfEditorFeatureFlags | null+}> = [+ { id: "properties", label: "Properties", glyph: SlidersGlyph, feature: null },+ {+ id: "comments",+ label: "Comments",+ glyph: CommentsGlyph,+ feature: "comments",+ },+ {+ id: "redactions",+ label: "Redactions",+ glyph: EyeOffGlyph,+ feature: "redact",+ },+ { id: "stamps", label: "Stamps", glyph: StampGlyph, feature: "stamps" },+ {+ id: "signatures",+ label: "Signatures",+ glyph: SignatureGlyph,+ feature: "sign",+ },+ {+ id: "forms",+ label: "Form fields",+ glyph: TextFieldGlyph,+ feature: "forms",+ },+]++function PdfEditorInner({+ documentId,+ document: pdfDocument,+ fileName,+ className,+ defaultZoom,+ defaultMode,+ leftPanel,+ setLeftPanel,+ formDesignMode,+ setFormDesignMode,+ annotationAuthor,+ features,+ showToolbar,+ showUpload,+ showDownload,+ toolbarActions,+ selectionActions,+ signatureFontsStylesheetUrl,+ renderPageOverlay,+ handleRef,+ onReplaceDocument,+ onUploadFile,+ onActivePageChange,+ onModeChange,+ onAnnotationEvent,+ onAnnotationsChange,+ onFormValuesChange,+ onRedactionsApplied,+ onSave,+ onCapture,+ onToast,+ onSelectionAction,+}: PdfEditorInnerProps) {+ const { registry } = useRegistry()+ const permissions = useDocumentPermissions(documentId)+ const { state: scrollState, provides: scroll } = useScroll(documentId)+ const { provides: scrollCapability } = useScrollCapability()+ const { state: zoomState, provides: zoom } = useZoom(documentId)+ const { provides: rotate } = useRotate(documentId)+ const { spreadMode, provides: spread } = useSpread(documentId)+ const { provides: pan, isPanning } = usePan(documentId)+ const { state: captureState, provides: capture } = useCapture(documentId)+ const { provides: fullscreen, state: fullscreenState } = useFullscreen()+ const { provides: historyCapability } = useHistoryCapability()+ const { provides: annotationCapability } = useAnnotationCapability()+ const { state: annotationState, provides: annotation } =+ useAnnotation(documentId)+ const { state: redactionState, provides: redaction } =+ useRedaction(documentId)+ const { provides: exportScope } = useExport(documentId)+ const { provides: print } = usePrint(documentId)+ const { provides: formCapability } = useFormCapability()+ const { provides: selectionCapability } = useSelectionCapability()++ const [mode, setModeState] = React.useState<PdfEditorMode>(defaultMode)+ const [rightPanel, setRightPanel] =+ React.useState<PdfEditorRightPanel | null>(null)+ const [dialog, setDialog] = React.useState<PdfEditorDialogRequest | null>(+ null+ )+ const [searchOpen, setSearchOpen] = React.useState(false)+ const [historyState, setHistoryState] = React.useState({+ canUndo: false,+ canRedo: false,+ })+ const [horizontalScroll, setHorizontalScroll] = React.useState(false)+ const [isDownloading, setIsDownloading] = React.useState(false)++ const rootRef = React.useRef<HTMLDivElement | null>(null)+ const [toastContainer, setToastContainer] =+ React.useState<HTMLDivElement | null>(null)+ const [editorToastManager] = React.useState(() =>+ ToastPrimitive.createToastManager()+ )+ const viewportElementRef = React.useRef<HTMLDivElement | null>(null)+ const uploadInputRef = React.useRef<HTMLInputElement>(null)+ const annotationImportInputRef = React.useRef<HTMLInputElement>(null)+ const [shellRef, shellWidth] = useElementWidth<HTMLDivElement>()+ const leftInline = useInlineThumbnailSidebar(shellWidth)+ const rightInline = shellWidth >= RIGHT_PANEL_INLINE_MIN_WIDTH+ const compactToolbar = shellWidth > 0 && shellWidth <= TOOLBAR_STACK_MAX_WIDTH++ const activePage = scrollState.currentPage+ const numPages = pdfDocument?.pageCount ?? 0+ const isLoading = !pdfDocument+ const controlsDisabled = !numPages+ const currentZoom = zoomState.currentZoomLevel+ const selectedAnnotations = React.useMemo(+ () => getSelectedAnnotations(annotationState),+ [annotationState]+ )+ const activeToolId = annotationState.activeToolId+ const activeTool = React.useMemo(+ () =>+ activeToolId && annotationCapability+ ? annotationCapability.getTool(activeToolId)+ : null,+ [activeToolId, annotationCapability]+ )+ const historyScope = React.useMemo(+ () => historyCapability?.forDocument(documentId) ?? null,+ [documentId, historyCapability]+ )+ const formScope = React.useMemo(+ () => formCapability?.forDocument(documentId) ?? null,+ [documentId, formCapability]+ )+ const selectionScope = React.useMemo(+ () => selectionCapability?.forDocument(documentId) ?? null,+ [documentId, selectionCapability]+ )++ /* ---- notices ---------------------------------------------------------- */++ const notify = React.useCallback(+ (message: string, tone: PdfEditorNoticeTone = "info") => {+ if (onToast) {+ onToast({ message, tone })+ return+ }++ editorToastManager.add({ title: message, type: tone })+ },+ [editorToastManager, onToast]+ )++ const setRootElement = React.useCallback((element: HTMLDivElement | null) => {+ rootRef.current = element+ setToastContainer(element)+ }, [])++ /* ---- tool helpers ----------------------------------------------------- */++ const deactivateTools = React.useCallback(() => {+ annotation?.setActiveTool(null)+ if (redactionState.isRedacting) redaction?.endRedact()+ if (isPanning) pan?.disablePan()+ if (captureState.isMarqueeCaptureActive) capture?.disableMarqueeCapture()+ if (zoomState.isMarqueeZoomActive) zoom?.disableMarqueeZoom()+ }, [+ annotation,+ capture,+ captureState.isMarqueeCaptureActive,+ isPanning,+ pan,+ redaction,+ redactionState.isRedacting,+ zoom,+ zoomState.isMarqueeZoomActive,+ ])++ const setActiveTool = React.useCallback(+ (toolId: string | null) => {+ if (!annotation) return++ if (isPanning) pan?.disablePan()+ if (captureState.isMarqueeCaptureActive) capture?.disableMarqueeCapture()+ if (zoomState.isMarqueeZoomActive) zoom?.disableMarqueeZoom()+ if (redactionState.isRedacting) redaction?.endRedact()++ annotation.setActiveTool(+ toolId !== null && annotationState.activeToolId === toolId+ ? null+ : toolId+ )+ },+ [+ annotation,+ annotationState.activeToolId,+ capture,+ captureState.isMarqueeCaptureActive,+ isPanning,+ pan,+ redaction,+ redactionState.isRedacting,+ zoom,+ zoomState.isMarqueeZoomActive,+ ]+ )++ const setMode = React.useCallback(+ (nextMode: PdfEditorMode) => {+ setModeState((previous) => {+ if (previous === nextMode) return previous++ onModeChange?.(nextMode)+ return nextMode+ })++ const defaultPanel: Record<PdfEditorMode, PdfEditorRightPanel | null> = {+ view: null,+ annotate: "properties",+ sign: "signatures",+ forms: "forms",+ redact: "redactions",+ }+ const panel = defaultPanel[nextMode]++ if (panel) setRightPanel(panel)+ else setRightPanel(null)+ },+ [onModeChange]+ )++ React.useEffect(() => {+ deactivateTools()+ annotation?.deselectAnnotation()+ // Only react to mode changes here; tool state is otherwise managed by the toolbar.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [mode])++ React.useEffect(() => {+ annotation?.setLocked(+ mode === "forms" && formDesignMode+ ? { type: LockModeType.None }+ : { type: LockModeType.Include, categories: ["form"] }+ )+ }, [annotation, formDesignMode, mode])++ React.useEffect(() => {+ if (mode !== "forms" && formDesignMode) setFormDesignMode(false)+ }, [formDesignMode, mode, setFormDesignMode])++ /* ---- history ---------------------------------------------------------- */++ React.useEffect(() => {+ if (!historyScope) return++ const sync = () => {+ const state = historyScope.getHistoryState()+ setHistoryState({+ canUndo: state.global.canUndo,+ canRedo: state.global.canRedo,+ })+ }++ sync()+ return historyScope.onHistoryChange(sync)+ }, [historyScope])++ /* ---- callbacks: page, annotations, forms, redactions ------------------ */++ React.useEffect(() => {+ if (activePage > 0) onActivePageChange?.(activePage)+ }, [activePage, onActivePageChange])++ const onAnnotationEventRef = React.useRef(onAnnotationEvent)+ const onAnnotationsChangeRef = React.useRef(onAnnotationsChange)+ const onFormValuesChangeRef = React.useRef(onFormValuesChange)+ const onRedactionsAppliedRef = React.useRef(onRedactionsApplied)++ React.useEffect(() => {+ onAnnotationEventRef.current = onAnnotationEvent+ onAnnotationsChangeRef.current = onAnnotationsChange+ onFormValuesChangeRef.current = onFormValuesChange+ onRedactionsAppliedRef.current = onRedactionsApplied+ })++ React.useEffect(() => {+ if (!annotation) return++ let timeout: number | null = null++ const unsubscribe = annotation.onAnnotationEvent((event) => {+ onAnnotationEventRef.current?.(event)++ if (!onAnnotationsChangeRef.current) return+ if (event.type === "loaded" || !event.committed) return++ if (timeout !== null) window.clearTimeout(timeout)++ timeout = window.setTimeout(() => {+ timeout = null+ annotation.exportAnnotations().wait((items) => {+ onAnnotationsChangeRef.current?.(items)+ }, noop)+ }, 400)+ })++ return () => {+ if (timeout !== null) window.clearTimeout(timeout)+ unsubscribe()+ }+ }, [annotation])++ React.useEffect(() => {+ if (!formScope) return++ return formScope.onFieldValueChange(() => {+ onFormValuesChangeRef.current?.(formScope.getFormValues())+ })+ }, [formScope])++ React.useEffect(() => {+ if (!redaction) return++ return redaction.onRedactionEvent((event) => {+ if (event.type !== "commit") return++ if (event.success) {+ notify(+ "Redactions applied. The content was removed from the document.",+ "success"+ )+ onRedactionsAppliedRef.current?.()+ } else {+ notify("The redactions could not be applied.", "error")+ }+ })+ }, [notify, redaction])++ /* ---- initial zoom (numeric defaults never lift the viewport gate) ----- */++ const initialZoomDocumentRef = React.useRef<string | null>(null)++ React.useEffect(() => {+ if (!pdfDocument || !zoom) return+ if (initialZoomDocumentRef.current === documentId) return++ initialZoomDocumentRef.current = documentId+ zoom.requestZoom(toZoomLevel(defaultZoom))+ }, [defaultZoom, documentId, pdfDocument, zoom])++ /* ---- document actions ------------------------------------------------- */++ const scrollToPage = React.useCallback(+ (+ pageNumber: number,+ options?: { smooth?: boolean } | ScrollIntoViewOptions+ ) => {+ const smooth =+ options && "smooth" in options+ ? options.smooth+ : options && "behavior" in options+ ? options.behavior === "smooth"+ : false++ scroll?.scrollToPage({ pageNumber, behavior: smooth ? "smooth" : "auto" })+ },+ [scroll]+ )++ const scrollToAnnotation = React.useCallback(+ (target: PdfAnnotationObject) => {+ scroll?.scrollToPage({+ pageNumber: target.pageIndex + 1,+ pageCoordinates: { x: target.rect.origin.x, y: target.rect.origin.y },+ alignX: 50,+ alignY: 25,+ behavior: "smooth",+ })+ },+ [scroll]+ )++ const getDocumentBuffer = React.useCallback(async () => {+ if (!exportScope) throw new Error("The document is not ready.")++ if (annotation && annotationState.hasPendingChanges) {+ try {+ await annotation.commit().toPromise()+ } catch {+ // Continue with whatever the engine currently holds.+ }+ }++ return exportScope.saveAsCopy().toPromise()+ }, [annotation, annotationState.hasPendingChanges, exportScope])++ const downloadDocument = React.useCallback(+ async (name?: string) => {+ const targetName = getPdfFileName(name ?? fileName)++ setIsDownloading(true)++ try {+ const buffer = await getDocumentBuffer()+ downloadArrayBuffer(buffer, targetName)+ onSave?.({ buffer, fileName: targetName })+ } catch (error) {+ console.error(error)+ notify("The document could not be saved.", "error")+ } finally {+ setIsDownloading(false)+ }+ },+ [fileName, getDocumentBuffer, notify, onSave]+ )++ const flattenDocument = React.useCallback(() => {+ setDialog({+ type: "confirm",+ title: "Flatten annotations and form fields?",+ description:+ "Annotations and filled form fields become part of the page content and can no longer be edited.",+ confirmLabel: "Flatten",+ destructive: true,+ onConfirm: async () => {+ if (!registry || !pdfDocument) return++ try {+ if (annotation && annotationState.hasPendingChanges) {+ await annotation.commit().toPromise()+ }++ const engine = registry.getEngine()++ for (const page of pdfDocument.pages) {+ await engine+ .flattenPage(pdfDocument, page, {+ flag: PdfPageFlattenFlag.Display,+ })+ .toPromise()+ }++ const buffer = await engine.saveAsCopy(pdfDocument).toPromise()+ onReplaceDocument(buffer, fileName)+ notify("Annotations flattened into the page content.", "success")+ } catch (error) {+ console.error(error)+ notify("The document could not be flattened.", "error")+ }+ },+ })+ }, [+ annotation,+ annotationState.hasPendingChanges,+ fileName,+ notify,+ onReplaceDocument,+ pdfDocument,+ registry,+ ])++ const exportAnnotationsJson = React.useCallback(() => {+ if (!annotation) return++ annotation.exportAnnotations().wait(+ (items) => {+ downloadBlob(+ new Blob([JSON.stringify(serializeAnnotationItems(items), null, 2)], {+ type: "application/json",+ }),+ `${fileName.replace(/\.pdf$/i, "")}-annotations.json`+ )+ notify(+ `Exported ${items.length} annotation${items.length === 1 ? "" : "s"}.`,+ "success"+ )+ },+ () => notify("The annotations could not be exported.", "error")+ )+ }, [annotation, fileName, notify])++ const importAnnotationsFile = React.useCallback(+ async (file: File) => {+ if (!annotation) return++ try {+ const items = deserializeAnnotationItems(JSON.parse(await file.text()))+ annotation.importAnnotations(items)+ notify(+ `Imported ${items.length} annotation${items.length === 1 ? "" : "s"}.`,+ "success"+ )+ } catch {+ notify("The file is not a valid annotation export.", "error")+ }+ },+ [annotation, notify]+ )++ const deleteSelectedAnnotations = React.useCallback(() => {+ if (!annotation || selectedAnnotations.length === 0) return++ const deletable = selectedAnnotations.filter(+ (item) => !annotation.isAnnotationStructurallyLocked(item.object)+ )++ if (deletable.length === 0) return++ annotation.deleteAnnotations(+ deletable.map((item) => ({+ pageIndex: item.object.pageIndex,+ id: item.object.id,+ }))+ )+ }, [annotation, selectedAnnotations])++ const applyAllRedactions = React.useCallback(() => {+ if (!redaction || redactionState.pendingCount === 0) return++ setDialog({+ type: "confirm",+ title: `Apply ${redactionState.pendingCount} redaction${redactionState.pendingCount === 1 ? "" : "s"}?`,+ description:+ "Redaction permanently removes the marked content from the document. This cannot be undone.",+ confirmLabel: "Apply redactions",+ onConfirm: () => {+ redaction.commitAllPending().wait(noop, noop)+ },+ })+ }, [redaction, redactionState.pendingCount])++ /* ---- imperative handle ------------------------------------------------ */++ React.useEffect(() => {+ handleRef.current = {+ getDocumentBuffer,+ download: downloadDocument,+ print: async (options) => {+ if (!print) throw new Error("Printing is not available.")+ await print.print(options).toPromise()+ },+ exportAnnotations: async () => {+ if (!annotation) return []+ return annotation.exportAnnotations().toPromise()+ },+ importAnnotations: (items) => annotation?.importAnnotations(items),+ getFormValues: () => formScope?.getFormValues() ?? {},+ setFormValues: async (values) => {+ if (!formScope) return+ await formScope.setFormValues(values).toPromise()+ },+ applyRedactions: async () => {+ if (!redaction) return+ await redaction.commitAllPending().toPromise()+ },+ setMode,+ setActiveTool: (toolId) => annotation?.setActiveTool(toolId),+ scrollToPage: (pageNumber, options) => scrollToPage(pageNumber, options),+ undo: () => historyScope?.undo(),+ redo: () => historyScope?.redo(),+ getViewportElement: () => viewportElementRef.current,+ }++ return () => {+ handleRef.current = null+ }+ }, [+ annotation,+ downloadDocument,+ formScope,+ getDocumentBuffer,+ handleRef,+ historyScope,+ print,+ redaction,+ scrollToPage,+ setMode,+ ])++ /* ---- keyboard shortcuts ----------------------------------------------- */++ const handleKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLDivElement>) => {+ const key = event.key+ const mod = event.metaKey || event.ctrlKey++ if (isTypingTarget(event.target)) {+ if (key === "Escape") (event.target as HTMLElement).blur()+ return+ }++ if (key === "Escape") {+ deactivateTools()+ annotation?.deselectAnnotation()+ selectionScope?.clear()+ setSearchOpen(false)+ event.preventDefault()+ return+ }++ if (+ (key === "Delete" || key === "Backspace") &&+ selectedAnnotations.length > 0+ ) {+ deleteSelectedAnnotations()+ event.preventDefault()+ return+ }++ if (mod && key.toLowerCase() === "z") {+ if (event.shiftKey) historyScope?.redo()+ else historyScope?.undo()+ event.preventDefault()+ return+ }++ if (mod && key.toLowerCase() === "y") {+ historyScope?.redo()+ event.preventDefault()+ return+ }++ if (mod && (key === "=" || key === "+")) {+ zoom?.zoomIn()+ event.preventDefault()+ return+ }++ if (mod && key === "-") {+ zoom?.zoomOut()+ event.preventDefault()+ return+ }++ if (mod && key === "0") {+ zoom?.requestZoom(ZoomMode.FitPage)+ event.preventDefault()+ return+ }++ if (mod && key.toLowerCase() === "p" && features.print) {+ setDialog({ type: "print" })+ event.preventDefault()+ return+ }++ if (mod && key.toLowerCase() === "s" && showDownload) {+ void downloadDocument()+ event.preventDefault()+ return+ }++ if (mod && key.toLowerCase() === "f") {+ setSearchOpen(true)+ event.preventDefault()+ return+ }++ if (mod && key.toLowerCase() === "a" && annotation && mode !== "view") {+ const ids = annotationState.pages[Math.max(0, activePage - 1)] ?? []++ if (ids.length > 0) {+ annotation.setSelection(ids)+ event.preventDefault()+ }+ return+ }++ if (!mod && !event.altKey && key.toLowerCase() === "h") {+ pan?.togglePan()+ event.preventDefault()+ return+ }++ if (!mod && !event.altKey && key.toLowerCase() === "v") {+ deactivateTools()+ event.preventDefault()+ }+ },+ [+ activePage,+ annotation,+ annotationState.pages,+ deactivateTools,+ deleteSelectedAnnotations,+ downloadDocument,+ features.print,+ historyScope,+ mode,+ pan,+ selectedAnnotations.length,+ selectionScope,+ showDownload,+ zoom,+ ]+ )++ const handlePointerDownCapture = React.useCallback(+ (event: React.PointerEvent<HTMLDivElement>) => {+ const root = rootRef.current+ if (!root) return++ const active = window.document.activeElement++ if (active && root.contains(active) && active !== root) return+ if (!(event.target instanceof Node) || !root.contains(event.target))+ return+ if (isTypingTarget(event.target)) return++ root.focus({ preventScroll: true })+ },+ []+ )++ /* ---- context ---------------------------------------------------------- */++ const openDialog = React.useCallback(+ (request: PdfEditorDialogRequest) => setDialog(request),+ []+ )+ const toggleLeftPanel = React.useCallback(+ (panel: PdfEditorLeftPanel) =>+ setLeftPanel((previous) => (previous === panel ? null : panel)),+ [setLeftPanel]+ )+ const toggleRightPanel = React.useCallback(+ (panel: PdfEditorRightPanel) =>+ setRightPanel((previous) => (previous === panel ? null : panel)),+ []+ )++ const contextValue = React.useMemo<PdfEditorContextValue>(+ () => ({+ documentId,+ document: pdfDocument,+ fileName,+ mode,+ setMode,+ leftPanel,+ setLeftPanel,+ toggleLeftPanel,+ rightPanel,+ setRightPanel,+ toggleRightPanel,+ openDialog,+ notify,+ features,+ permissions,+ annotationAuthor,+ selectionActions,+ formDesignMode,+ setFormDesignMode,+ replaceDocument: (buffer, name) =>+ onReplaceDocument(buffer, name ?? fileName),+ downloadDocument,+ getDocumentBuffer,+ scrollToPage,+ scrollToAnnotation,+ onCapture,+ onSelectionAction,+ signatureFontsStylesheetUrl,+ }),+ [+ annotationAuthor,+ documentId,+ downloadDocument,+ features,+ fileName,+ formDesignMode,+ getDocumentBuffer,+ leftPanel,+ mode,+ notify,+ onCapture,+ onReplaceDocument,+ onSelectionAction,+ openDialog,+ pdfDocument,+ permissions,+ rightPanel,+ scrollToAnnotation,+ scrollToPage,+ selectionActions,+ setFormDesignMode,+ setLeftPanel,+ setMode,+ signatureFontsStylesheetUrl,+ toggleLeftPanel,+ toggleRightPanel,+ ]+ )++ /* ---- page renderer ---------------------------------------------------- */++ const renderPage = React.useCallback(+ (page: PageLayout) => (+ <Rotate documentId={documentId} pageIndex={page.pageIndex}>+ <PagePointerProvider+ documentId={documentId}+ pageIndex={page.pageIndex}+ data-pdf-editor-page={page.pageNumber}+ className="relative border border-transparent bg-transparent shadow-xs select-none selection:bg-transparent selection:text-inherit"+ style={{ backgroundColor: "transparent" }}+ >+ <div+ aria-hidden="true"+ className="pointer-events-none absolute inset-0 bg-white"+ />+ <RenderLayer+ documentId={documentId}+ pageIndex={page.pageIndex}+ scale={Math.min(currentZoom, PAGE_BASE_RENDER_MAX_SCALE)}+ dpr={PAGE_BASE_RENDER_DPR}+ className="pointer-events-none absolute inset-0 h-full w-full object-fill opacity-100 blur-[0.35px] transition-none"+ />+ <TilingLayer+ documentId={documentId}+ pageIndex={page.pageIndex}+ className="pointer-events-none opacity-100 transition-none [&_img]:opacity-100 [&_img]:transition-none"+ />+ <SearchLayer+ documentId={documentId}+ pageIndex={page.pageIndex}+ className="pointer-events-none"+ highlightColor="rgba(253, 224, 71, 0.45)"+ activeHighlightColor="rgba(249, 115, 22, 0.55)"+ />+ <MarqueeZoom documentId={documentId} pageIndex={page.pageIndex} />+ <MarqueeCapture documentId={documentId} pageIndex={page.pageIndex} />+ <SelectionLayer+ documentId={documentId}+ pageIndex={page.pageIndex}+ textStyle={{ background: "rgba(59, 130, 246, 0.3)" }}+ selectionMenu={(props) => (+ <PdfEditorTextSelectionMenu {...props} documentId={documentId} />+ )}+ />+ <AnnotationLayer+ documentId={documentId}+ pageIndex={page.pageIndex}+ selectionOutline={{+ color: PDF_EDITOR_SELECTION_COLOR,+ style: "solid",+ width: 1,+ offset: 2,+ }}+ groupSelectionOutline={{+ color: PDF_EDITOR_SELECTION_COLOR,+ style: "dashed",+ width: 1,+ offset: 3,+ }}+ resizeUI={{ size: 10, color: PDF_EDITOR_SELECTION_COLOR }}+ vertexUI={{ size: 10, color: PDF_EDITOR_SELECTION_COLOR }}+ rotationUI={{+ size: 18,+ color: "#ffffff",+ iconColor: PDF_EDITOR_SELECTION_COLOR,+ connectorColor: PDF_EDITOR_SELECTION_COLOR,+ showConnector: true,+ }}+ selectionMenu={(props) => (+ <PdfEditorAnnotationMenu {...props} documentId={documentId} />+ )}+ groupSelectionMenu={(props) => (+ <PdfEditorGroupMenu {...props} documentId={documentId} />+ )}+ />+ <RedactionLayer+ documentId={documentId}+ pageIndex={page.pageIndex}+ selectionMenu={(props) => (+ <PdfEditorRedactionMenu {...props} documentId={documentId} />+ )}+ />+ {renderPageOverlay?.({+ pageNumber: page.pageNumber,+ pageWidth: page.width,+ pageHeight: page.height,+ scale: currentZoom,+ rotation: 0,+ })}+ </PagePointerProvider>+ </Rotate>+ ),+ [currentZoom, documentId, renderPageOverlay]+ )++ /* ---- toolbar pieces --------------------------------------------------- */++ const activeToolColorKey = React.useMemo(() => {+ if (!activeTool) return null++ const defaults = activeTool.defaults as Record<string, unknown>++ if ("fontColor" in defaults) return "fontColor"+ if ("strokeColor" in defaults) return "strokeColor"+ if ("color" in defaults) return "color"+ return null+ }, [activeTool])+ const activeToolColor = activeToolColorKey+ ? String(+ (activeTool?.defaults as Record<string, unknown>)[activeToolColorKey] ??+ "#111827"+ )+ : null++ const visibleLeftTabs = LEFT_PANEL_TABS.filter(+ (tab) => tab.feature === null || features[tab.feature]+ )+ const visibleRightTabs = RIGHT_PANEL_TABS.filter(+ (tab) => tab.feature === null || features[tab.feature]+ )++ const canAnnotate = features.annotate && permissions.canModifyAnnotations+ const canRedact = features.redact && permissions.canModifyContents+ const canDesignForms = features.forms && permissions.canModifyAnnotations++ const selectToolButton = (+ <PdfEditorToolButton+ label="Select"+ shortcut="V"+ active={+ !activeToolId &&+ !isPanning &&+ !captureState.isMarqueeCaptureActive &&+ !zoomState.isMarqueeZoomActive &&+ !redactionState.isRedacting+ }+ onClick={deactivateTools}+ >+ <CursorGlyph className="size-4" />+ </PdfEditorToolButton>+ )++ const renderToolButton = (+ tool: { id: string; label: string; glyph: PdfEditorGlyph; hint?: string },+ disabled: boolean+ ) => {+ const Glyph = tool.glyph++ return (+ <PdfEditorToolButton+ key={tool.id}+ label={tool.hint ? `${tool.label} · ${tool.hint}` : tool.label}+ active={activeToolId === tool.id}+ disabled={disabled}+ onClick={() => setActiveTool(tool.id)}+ >+ <Glyph className="size-4" />+ </PdfEditorToolButton>+ )+ }++ let ribbon: React.ReactNode = null++ if (mode === "view") {+ ribbon = (+ <>+ {selectToolButton}+ <PdfEditorToolButton+ label="Hand tool"+ shortcut="H"+ active={isPanning}+ onClick={() => pan?.togglePan()}+ >+ <HandGlyph className="size-4" />+ </PdfEditorToolButton>+ <PdfEditorToolButton+ label="Zoom to area"+ active={zoomState.isMarqueeZoomActive}+ onClick={() => zoom?.toggleMarqueeZoom()}+ >+ <MarqueeZoomGlyph className="size-4" />+ </PdfEditorToolButton>+ {features.capture ? (+ <PdfEditorToolButton+ label="Capture area as image"+ active={captureState.isMarqueeCaptureActive}+ onClick={() => capture?.toggleMarqueeCapture()}+ >+ <CameraGlyph className="size-4" />+ </PdfEditorToolButton>+ ) : null}+ <PdfEditorToolbarSeparator />+ <Select+ items={SPREAD_MODE_OPTIONS}+ value={spreadMode}+ disabled={controlsDisabled}+ modal={false}+ onValueChange={(value) =>+ spread?.setSpreadMode(String(value) as SpreadMode)+ }+ >+ <SelectTrigger+ size="sm"+ className="w-[132px]"+ aria-label="Page layout"+ >+ <BookOpenGlyph className="size-4 text-muted-foreground" />+ <SelectValue placeholder="Layout" />+ </SelectTrigger>+ <SelectContent alignItemWithTrigger={false}>+ {SPREAD_MODE_OPTIONS.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Select+ items={SCROLL_DIRECTION_OPTIONS}+ value={horizontalScroll ? "horizontal" : "vertical"}+ disabled={controlsDisabled}+ modal={false}+ onValueChange={(value) => {+ const horizontal = value === "horizontal"+ setHorizontalScroll(horizontal)+ scrollCapability?.setScrollStrategy(+ horizontal ? ScrollStrategy.Horizontal : ScrollStrategy.Vertical,+ documentId+ )+ }}+ >+ <SelectTrigger+ size="sm"+ className="w-[128px]"+ aria-label="Scroll direction"+ >+ <SelectValue placeholder="Scroll" />+ </SelectTrigger>+ <SelectContent alignItemWithTrigger={false}>+ {SCROLL_DIRECTION_OPTIONS.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </>+ )+ } else if (mode === "annotate") {+ ribbon = (+ <>+ {selectToolButton}+ {PDF_EDITOR_ANNOTATION_TOOL_GROUPS.map((group) => (+ <React.Fragment key={group.id}>+ <PdfEditorToolbarSeparator />+ {group.tools.map((tool) => renderToolButton(tool, !canAnnotate))}+ </React.Fragment>+ ))}+ {features.stamps ? (+ <PdfEditorToolButton+ label="Rubber stamps"+ active={rightPanel === "stamps"}+ disabled={!canAnnotate}+ onClick={() => toggleRightPanel("stamps")}+ >+ <StampGlyph className="size-4" />+ </PdfEditorToolButton>+ ) : null}+ {activeTool && activeToolColorKey && activeToolColor ? (+ <>+ <PdfEditorToolbarSeparator />+ <ColorPicker+ label={`${activeTool.name} color`}+ icon={PaletteGlyph}+ color={activeToolColor}+ onChange={(color) =>+ annotationCapability?.setToolDefaults(activeTool.id, {+ [activeToolColorKey]: color,+ })+ }+ />+ </>+ ) : null}+ <div className="ml-auto flex items-center gap-0.5">+ <PdfEditorToolButton+ label="Delete selected"+ shortcut="Delete"+ disabled={selectedAnnotations.length === 0}+ onClick={deleteSelectedAnnotations}+ >+ <TrashGlyph className="size-4" />+ </PdfEditorToolButton>+ {features.comments ? (+ <PdfEditorToolButton+ label="Comments"+ active={rightPanel === "comments"}+ onClick={() => toggleRightPanel("comments")}+ >+ <CommentsGlyph className="size-4" />+ </PdfEditorToolButton>+ ) : null}+ <PdfEditorToolButton+ label="Properties"+ active={rightPanel === "properties"}+ onClick={() => toggleRightPanel("properties")}+ >+ <SlidersGlyph className="size-4" />+ </PdfEditorToolButton>+ </div>+ </>+ )+ } else if (mode === "sign") {+ ribbon = (+ <>+ {selectToolButton}+ <PdfEditorToolbarSeparator />+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={!canAnnotate}+ onClick={() => setDialog({ type: "signature" })}+ >+ <PlusGlyph className="size-4" />+ Create signature+ </Button>+ <PdfEditorToolButton+ label="Saved signatures"+ active={rightPanel === "signatures"}+ onClick={() => toggleRightPanel("signatures")}+ >+ <SignatureGlyph className="size-4" />+ </PdfEditorToolButton>+ <PdfEditorToolbarSeparator />+ {renderToolButton(+ {+ id: "freeText",+ label: "Text box",+ glyph: TextGlyph,+ hint: "Click to add text",+ },+ !canAnnotate+ )}+ <PdfEditorToolButton+ label="Date · Click to add today's date"+ disabled={!canAnnotate}+ active={+ activeToolId === "freeText" &&+ Boolean(annotationState.activeToolContext?.date)+ }+ onClick={() => {+ if (!annotation) return++ annotationCapability?.setToolDefaults("freeText", {+ contents: new Date().toLocaleDateString(),+ })+ annotation.setActiveTool("freeText", { date: true })+ }}+ >+ <FileTextGlyph className="size-4" />+ </PdfEditorToolButton>+ {renderToolButton(+ { id: "ink", label: "Draw", glyph: EditGlyph, hint: "Sign by hand" },+ !canAnnotate+ )}+ </>+ )+ } else if (mode === "forms") {+ ribbon = (+ <>+ {selectToolButton}+ <PdfEditorToolbarSeparator />+ <div+ role="group"+ aria-label="Form mode"+ className="flex shrink-0 items-center gap-0.5 rounded-lg bg-muted p-0.5"+ >+ <Button+ type="button"+ size="xs"+ variant={formDesignMode ? "ghost" : "default"}+ aria-pressed={!formDesignMode}+ onClick={() => setFormDesignMode(false)}+ >+ Fill+ </Button>+ <Button+ type="button"+ size="xs"+ variant={formDesignMode ? "default" : "ghost"}+ aria-pressed={formDesignMode}+ disabled={!canDesignForms}+ onClick={() => setFormDesignMode(true)}+ >+ Design+ </Button>+ </div>+ {formDesignMode ? (+ <>+ <PdfEditorToolbarSeparator />+ {PDF_EDITOR_FORM_TOOLS.map((tool) =>+ renderToolButton(tool, !canDesignForms)+ )}+ </>+ ) : null}+ <div className="ml-auto flex items-center gap-0.5">+ <PdfEditorToolButton+ label="Delete selected"+ shortcut="Delete"+ disabled={selectedAnnotations.length === 0 || !formDesignMode}+ onClick={deleteSelectedAnnotations}+ >+ <TrashGlyph className="size-4" />+ </PdfEditorToolButton>+ <PdfEditorToolButton+ label="Form fields"+ active={rightPanel === "forms"}+ onClick={() => toggleRightPanel("forms")}+ >+ <TextFieldGlyph className="size-4" />+ </PdfEditorToolButton>+ <PdfEditorToolButton+ label="Properties"+ active={rightPanel === "properties"}+ onClick={() => toggleRightPanel("properties")}+ >+ <SlidersGlyph className="size-4" />+ </PdfEditorToolButton>+ </div>+ </>+ )+ } else if (mode === "redact") {+ const activeType = redactionState.activeType+ const pendingCount = redactionState.pendingCount++ ribbon = (+ <>+ {selectToolButton}+ <PdfEditorToolbarSeparator />+ <PdfEditorToolButton+ label="Redact · Select text or drag an area"+ active={activeType === RedactionMode.Redact}+ disabled={!canRedact}+ onClick={() => {+ deactivateTools()+ if (activeType !== RedactionMode.Redact) redaction?.enableRedact()+ }}+ >+ <EyeOffGlyph className="size-4" />+ </PdfEditorToolButton>+ <PdfEditorToolButton+ label="Mark text"+ active={activeType === RedactionMode.RedactSelection}+ disabled={!canRedact}+ onClick={() => {+ deactivateTools()+ if (activeType !== RedactionMode.RedactSelection)+ redaction?.enableRedactSelection()+ }}+ >+ <StrikethroughGlyph className="size-4" />+ </PdfEditorToolButton>+ <PdfEditorToolButton+ label="Mark area"+ active={activeType === RedactionMode.MarqueeRedact}+ disabled={!canRedact}+ onClick={() => {+ deactivateTools()+ if (activeType !== RedactionMode.MarqueeRedact)+ redaction?.enableMarqueeRedact()+ }}+ >+ <RedactAreaGlyph className="size-4" />+ </PdfEditorToolButton>+ <PdfEditorToolbarSeparator />+ <Badge+ variant={pendingCount > 0 ? "secondary" : "outline"}+ className="me-1 tabular-nums"+ >+ {pendingCount} pending+ </Badge>+ <Button+ type="button"+ size="sm"+ disabled={!canRedact || pendingCount === 0}+ onClick={applyAllRedactions}+ >+ Apply all+ </Button>+ <Button+ type="button"+ size="sm"+ variant="ghost"+ disabled={pendingCount === 0}+ onClick={() => redaction?.clearPending()}+ >+ Clear+ </Button>+ <div className="ml-auto flex items-center gap-0.5">+ <PdfEditorToolButton+ label="Redactions"+ active={rightPanel === "redactions"}+ onClick={() => toggleRightPanel("redactions")}+ >+ <EyeOffGlyph className="size-4" />+ </PdfEditorToolButton>+ <PdfEditorToolButton+ label="Properties"+ active={rightPanel === "properties"}+ onClick={() => toggleRightPanel("properties")}+ >+ <SlidersGlyph className="size-4" />+ </PdfEditorToolButton>+ </div>+ </>+ )+ }++ let rightPanelContent: React.ReactNode = null++ switch (rightPanel) {+ case "properties":+ rightPanelContent = <PdfEditorPropertiesPanel documentId={documentId} />+ break+ case "comments":+ rightPanelContent = <PdfEditorCommentsPanel documentId={documentId} />+ break+ case "redactions":+ rightPanelContent = <PdfEditorRedactionsPanel documentId={documentId} />+ break+ case "stamps":+ rightPanelContent = <PdfEditorStampsPanel documentId={documentId} />+ break+ case "signatures":+ rightPanelContent = <PdfEditorSignaturesPanel documentId={documentId} />+ break+ case "forms":+ rightPanelContent = <PdfEditorFormsPanel documentId={documentId} />+ break+ default:+ rightPanelContent = null+ }++ let leftPanelContent: React.ReactNode = null++ switch (leftPanel) {+ case "thumbnails":+ leftPanelContent = (+ <PdfEditorThumbnailsPanel+ documentId={documentId}+ activePage={activePage}+ pageCount={numPages}+ onSelectPage={(pageNumber) => scrollToPage(pageNumber)}+ />+ )+ break+ case "outline":+ leftPanelContent = <PdfEditorOutlinePanel documentId={documentId} />+ break+ case "attachments":+ leftPanelContent = <PdfEditorAttachmentsPanel documentId={documentId} />+ break+ case "pages":+ leftPanelContent = (+ <PdfEditorPagesPanel documentId={documentId} activePage={activePage} />+ )+ break+ default:+ leftPanelContent = null+ }++ return (+ <PdfEditorContextProvider value={contextValue}>+ <ToastProvider+ limit={3}+ timeout={NOTICE_DURATION_MS}+ toastManager={editorToastManager}+ portalProps={{ container: toastContainer }}+ viewportProps={{ className: "absolute" }}+ >+ <div+ data-slot="pdf-editor"+ data-mode={mode}+ data-fullscreen={fullscreenState.isFullscreen ? "" : undefined}+ className={cn(+ "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",+ className,+ // The fullscreen plugin auto-mounts a wrapper around the EmbedPDF+ // tree; when that wrapper is fullscreen, fill it instead of the+ // consumer-provided height.+ fullscreenState.isFullscreen && "h-full max-h-full"+ )}+ >+ <div+ ref={setRootElement}+ tabIndex={-1}+ className="relative flex h-full min-h-0 flex-1 flex-col outline-none"+ onKeyDown={handleKeyDown}+ onPointerDownCapture={handlePointerDownCapture}+ >+ <input+ ref={uploadInputRef}+ type="file"+ accept="application/pdf,.pdf"+ className="sr-only"+ tabIndex={-1}+ onChange={(event) => {+ const file = event.target.files?.[0]+ if (file) onUploadFile(file)+ event.currentTarget.value = ""+ }}+ />+ <input+ ref={annotationImportInputRef}+ type="file"+ accept="application/json,.json"+ className="sr-only"+ tabIndex={-1}+ onChange={(event) => {+ const file = event.target.files?.[0]+ if (file) void importAnnotationsFile(file)+ event.currentTarget.value = ""+ }}+ />++ {showToolbar ? (+ <TooltipProvider delay={TOOLTIP_DELAY_MS}>+ <div+ data-slot="pdf-editor-toolbar"+ className={cn(+ "flex min-h-12 flex-wrap items-center justify-between gap-2 border-b bg-background px-3 py-2",+ compactToolbar && "gap-0 px-0 py-0"+ )}+ >+ <div+ className={cn(+ "flex min-w-0 items-center gap-2",+ compactToolbar && "w-full px-3 py-2"+ )}+ >+ <PdfEditorToolButton+ label="Pages sidebar"+ active={leftPanel !== null}+ disabled={controlsDisabled}+ onClick={() => toggleLeftPanel("thumbnails")}+ >+ <PanelLeftGlyph className="size-4" />+ </PdfEditorToolButton>+ <PdfEditorPageControl+ activePage={activePage}+ numPages={numPages}+ disabled={controlsDisabled}+ onPageChange={(pageNumber) => scrollToPage(pageNumber)}+ />+ </div>+ <ScrollArea+ orientation="horizontal"+ scrollFade+ scrollbarOverflowOnly+ className={cn(+ "min-w-0 flex-1",+ compactToolbar && "h-12 w-full flex-none border-t"+ )}+ viewportClassName={cn(compactToolbar && "px-3 py-2")}+ >+ <div+ className={cn(+ "flex w-max min-w-full items-center gap-1",+ compactToolbar ? "justify-start" : "justify-end"+ )}+ >+ <div className="flex items-center gap-0.5">+ <PdfEditorToolButton+ label="Undo"+ shortcut="mod+Z"+ disabled={!historyState.canUndo}+ onClick={() => historyScope?.undo()}+ >+ <UndoGlyph className="size-4" />+ </PdfEditorToolButton>+ <PdfEditorToolButton+ label="Redo"+ shortcut="mod+shift+Z"+ disabled={!historyState.canRedo}+ onClick={() => historyScope?.redo()}+ >+ <RedoGlyph className="size-4" />+ </PdfEditorToolButton>+ </div>+ <PdfEditorToolbarSeparator />+ <PdfEditorZoomControl+ documentId={documentId}+ disabled={controlsDisabled}+ />+ <PdfEditorToolbarSeparator />+ <div className="flex items-center gap-0.5">+ <PdfEditorToolButton+ label="Rotate counterclockwise"+ disabled={controlsDisabled}+ onClick={() => rotate?.rotateBackward()}+ >+ <RotateGlyph className="size-4 -scale-x-100" />+ </PdfEditorToolButton>+ <PdfEditorToolButton+ label="Rotate clockwise"+ disabled={controlsDisabled}+ onClick={() => rotate?.rotateForward()}+ >+ <RotateGlyph className="size-4" />+ </PdfEditorToolButton>+ </div>+ <PdfEditorToolbarSeparator />+ <PdfEditorSearchControl+ documentId={documentId}+ disabled={controlsDisabled}+ open={searchOpen}+ onOpenChange={setSearchOpen}+ />+ <PdfEditorToolButton+ label="Details panel"+ active={rightPanel !== null}+ disabled={controlsDisabled}+ onClick={() => toggleRightPanel("properties")}+ >+ <PanelRightGlyph className="size-4" />+ </PdfEditorToolButton>+ {toolbarActions ? (+ <>+ <PdfEditorToolbarSeparator />+ {toolbarActions}+ </>+ ) : null}+ <PdfEditorToolbarSeparator />+ {showDownload ? (+ <PdfEditorToolButton+ label="Download"+ shortcut="mod+S"+ disabled={controlsDisabled || isDownloading}+ onClick={() => void downloadDocument()}+ >+ {isDownloading ? (+ <Spinner className="size-4" />+ ) : (+ <DownloadGlyph className="size-4" />+ )}+ </PdfEditorToolButton>+ ) : null}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="More actions"+ >+ <MoreGlyph className="size-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-60">+ <DropdownMenuGroup>+ <DropdownMenuLabel className="truncate">+ {fileName}+ </DropdownMenuLabel>+ {showUpload ? (+ <DropdownMenuItem+ onClick={() => uploadInputRef.current?.click()}+ >+ <UploadGlyph className="size-4" />+ Open PDF…+ </DropdownMenuItem>+ ) : null}+ {showDownload ? (+ <DropdownMenuItem+ disabled={controlsDisabled}+ onClick={() => void downloadDocument()}+ >+ <DownloadGlyph className="size-4" />+ Download+ <DropdownMenuShortcut>⌘S</DropdownMenuShortcut>+ </DropdownMenuItem>+ ) : null}+ {features.print ? (+ <DropdownMenuItem+ disabled={+ controlsDisabled || !permissions.canPrint+ }+ onClick={() => setDialog({ type: "print" })}+ >+ <PrintGlyph className="size-4" />+ Print…+ <DropdownMenuShortcut>⌘P</DropdownMenuShortcut>+ </DropdownMenuItem>+ ) : null}+ {features.capture ? (+ <DropdownMenuItem+ disabled={controlsDisabled}+ onClick={() => capture?.toggleMarqueeCapture()}+ >+ <CameraGlyph className="size-4" />+ Capture area as image+ </DropdownMenuItem>+ ) : null}+ {features.fullscreen ? (+ <DropdownMenuItem+ onClick={() => fullscreen?.toggleFullscreen()}+ >+ {fullscreenState.isFullscreen ? (+ <ExitFullscreenGlyph className="size-4" />+ ) : (+ <FullscreenGlyph className="size-4" />+ )}+ {fullscreenState.isFullscreen+ ? "Exit full screen"+ : "Full screen"}+ </DropdownMenuItem>+ ) : null}+ </DropdownMenuGroup>+ <DropdownMenuSeparator />+ <DropdownMenuGroup>+ <DropdownMenuItem+ disabled={controlsDisabled}+ onClick={() => setDialog({ type: "properties" })}+ >+ <InfoGlyph className="size-4" />+ Document properties…+ </DropdownMenuItem>+ {features.security ? (+ <DropdownMenuItem+ disabled={controlsDisabled}+ onClick={() => setDialog({ type: "security" })}+ >+ <ShieldGlyph className="size-4" />+ Security…+ </DropdownMenuItem>+ ) : null}+ <DropdownMenuItem+ disabled={+ controlsDisabled ||+ !permissions.canModifyContents+ }+ onClick={flattenDocument}+ >+ <LayersGlyph className="size-4" />+ Flatten annotations…+ </DropdownMenuItem>+ </DropdownMenuGroup>+ <DropdownMenuSeparator />+ <DropdownMenuGroup>+ <DropdownMenuItem+ disabled={controlsDisabled}+ onClick={exportAnnotationsJson}+ >+ <DownloadGlyph className="size-4" />+ Export annotations (JSON)+ </DropdownMenuItem>+ <DropdownMenuItem+ disabled={+ controlsDisabled ||+ !permissions.canModifyAnnotations+ }+ onClick={() =>+ annotationImportInputRef.current?.click()+ }+ >+ <UploadGlyph className="size-4" />+ Import annotations (JSON)…+ </DropdownMenuItem>+ </DropdownMenuGroup>+ <DropdownMenuSeparator />+ <DropdownMenuGroup>+ <DropdownMenuLabel>Page layout</DropdownMenuLabel>+ <DropdownMenuRadioGroup+ value={spreadMode}+ onValueChange={(value) =>+ spread?.setSpreadMode(+ String(value) as SpreadMode+ )+ }+ >+ <DropdownMenuRadioItem value={SpreadMode.None}>+ Single page+ </DropdownMenuRadioItem>+ <DropdownMenuRadioItem value={SpreadMode.Odd}>+ Two pages+ </DropdownMenuRadioItem>+ <DropdownMenuRadioItem value={SpreadMode.Even}>+ Two pages, cover first+ </DropdownMenuRadioItem>+ </DropdownMenuRadioGroup>+ </DropdownMenuGroup>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={() => setDialog({ type: "shortcuts" })}+ >+ <KeyboardGlyph className="size-4" />+ Keyboard shortcuts+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </ScrollArea>+ </div>+ <div+ data-slot="pdf-editor-ribbon"+ className="flex min-h-10 items-center gap-1 border-b bg-muted/30 px-3 py-1.5"+ >+ <PdfEditorModeSwitch+ mode={mode}+ features={features}+ compact={compactToolbar}+ onModeChange={setMode}+ />+ <PdfEditorToolbarSeparator className="mx-1.5" />+ <ScrollArea+ orientation="horizontal"+ scrollFade+ scrollbarOverflowOnly+ className="min-w-0 flex-1 self-stretch"+ >+ <div className="flex w-max min-w-full items-center gap-0.5 py-0.5">+ {ribbon}+ </div>+ </ScrollArea>+ </div>+ </TooltipProvider>+ ) : null}++ <div+ ref={shellRef}+ className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"+ >+ {isLoading ? (+ <div className="absolute inset-0 z-20 flex bg-muted/30">+ {leftPanel ? (+ <DocumentViewerSidebarSkeleton+ className={LEFT_SIDEBAR_WIDTH_CLASS}+ inline={leftInline}+ />+ ) : null}+ <div className="grid min-w-0 flex-1 place-items-center">+ <Spinner className="size-4" />+ </div>+ </div>+ ) : null}+ <div className="flex h-full max-h-full min-h-0 w-full flex-1 overflow-hidden">+ <DocumentViewerThumbnailSidebar+ closedInlineClassName={LEFT_SIDEBAR_CLOSED_CLASS}+ inline={leftInline}+ open={leftPanel !== null && !isLoading}+ widthClassName={LEFT_SIDEBAR_WIDTH_CLASS}+ >+ {leftPanel !== null && !isLoading ? (+ <div className="flex h-full flex-col">+ <PanelTabStrip+ tabs={visibleLeftTabs}+ value={leftPanel}+ onChange={setLeftPanel}+ onClose={() => setLeftPanel(null)}+ label="Sidebar panels"+ />+ <div className="min-h-0 flex-1">{leftPanelContent}</div>+ </div>+ ) : null}+ </DocumentViewerThumbnailSidebar>++ <PdfEditorViewport+ documentId={documentId}+ className="relative h-full max-h-full min-h-0 min-w-0 flex-1"+ >+ <PdfEditorViewportBridge+ viewportElementRef={viewportElementRef}+ />+ <GlobalPointerProvider documentId={documentId}>+ <Scroller documentId={documentId} renderPage={renderPage} />+ </GlobalPointerProvider>+ <CopyToClipboard />+ </PdfEditorViewport>++ <PdfEditorRightPanelShell+ open={rightPanel !== null && !isLoading}+ inline={rightInline}+ >+ {rightPanel !== null && !isLoading ? (+ <div className="flex h-full flex-col">+ <PanelTabStrip+ tabs={visibleRightTabs}+ value={rightPanel}+ onChange={setRightPanel}+ onClose={() => setRightPanel(null)}+ label="Detail panels"+ />+ <div className="min-h-0 flex-1 overflow-hidden">+ {rightPanel === "properties" ? (+ <PdfEditorScrollArea+ className="h-full w-full"+ scrollbarGutter={false}+ >+ {rightPanelContent}+ </PdfEditorScrollArea>+ ) : (+ rightPanelContent+ )}+ </div>+ </div>+ ) : null}+ </PdfEditorRightPanelShell>+ </div>+ </div>++ <PdfEditorSignaturePersistence storageKey={null} />+ {features.capture ? (+ <PdfEditorCaptureDialog documentId={documentId} />+ ) : null}+ <PdfEditorPrintDialog+ documentId={documentId}+ open={dialog?.type === "print"}+ onOpenChange={(open) => {+ if (!open) setDialog(null)+ }}+ />+ <PdfEditorSecurityDialog+ documentId={documentId}+ open={dialog?.type === "security"}+ onOpenChange={(open) => {+ if (!open) setDialog(null)+ }}+ />+ <PdfEditorPropertiesDialog+ documentId={documentId}+ open={dialog?.type === "properties"}+ onOpenChange={(open) => {+ if (!open) setDialog(null)+ }}+ />+ <PdfEditorShortcutsDialog+ open={dialog?.type === "shortcuts"}+ onOpenChange={(open) => {+ if (!open) setDialog(null)+ }}+ />+ <PdfEditorSignatureDialog+ open={dialog?.type === "signature"}+ onOpenChange={(open) => {+ if (!open) setDialog(null)+ }}+ />+ <PdfEditorLinkDialog+ documentId={documentId}+ open={dialog?.type === "link"}+ source={dialog?.type === "link" ? dialog.source : "selection"}+ onOpenChange={(open) => {+ if (!open) setDialog(null)+ }}+ />+ <PdfEditorConfirmDialog+ open={dialog?.type === "confirm"}+ title={dialog?.type === "confirm" ? dialog.title : ""}+ description={+ dialog?.type === "confirm" ? dialog.description : undefined+ }+ confirmLabel={+ dialog?.type === "confirm" ? dialog.confirmLabel : undefined+ }+ destructive={+ dialog?.type === "confirm" ? dialog.destructive : false+ }+ onConfirm={() => {+ if (dialog?.type === "confirm") dialog.onConfirm()+ }}+ onOpenChange={(open) => {+ if (!open) setDialog(null)+ }}+ />+ </div>+ </div>+ </ToastProvider>+ </PdfEditorContextProvider>+ )+}++/* -------------------------------------------------------------------------- */+/* Document loader */+/* -------------------------------------------------------------------------- */++type PdfEditorDocumentLoaderProps = Omit<+ PdfEditorInnerProps,+ | "documentId"+ | "document"+ | "fileName"+ | "leftPanel"+ | "setLeftPanel"+ | "formDesignMode"+ | "setFormDesignMode"+> & {+ source: EditorSource | null+ sourceLoading: boolean+ fileNameOverride?: string+ signatureStorageKey: string | null+ onDocumentLoadSuccess?: PDFEditorProps["onDocumentLoadSuccess"]+ onDocumentLoadError?: PDFEditorProps["onDocumentLoadError"]+}++function PdfEditorDocumentLoader({+ source,+ sourceLoading,+ fileNameOverride,+ signatureStorageKey,+ onDocumentLoadSuccess,+ onDocumentLoadError,+ ...innerProps+}: PdfEditorDocumentLoaderProps) {+ const { provides: documentManager } = useDocumentManagerCapability()+ const { activeDocumentId, activeDocument } = useActiveDocument()+ const [loadError, setLoadError] = React.useState<string | null>(null)+ const [leftPanel, setLeftPanel] = React.useState<PdfEditorLeftPanel | null>(+ null+ )+ const [formDesignMode, setFormDesignMode] = React.useState(false)+ const openedSourceRef = React.useRef<string | null>(null)+ const successRef = React.useRef(onDocumentLoadSuccess)+ const errorRef = React.useRef(onDocumentLoadError)++ React.useEffect(() => {+ successRef.current = onDocumentLoadSuccess+ errorRef.current = onDocumentLoadError+ })++ React.useEffect(() => {+ if (!documentManager || !source) return+ if (openedSourceRef.current === source.key) return++ openedSourceRef.current = source.key+ setLoadError(null)++ const previousIds = documentManager+ .getOpenDocuments()+ .map((item) => item.id)+ const fail = (message: string) => {+ if (openedSourceRef.current !== source.key) return++ setLoadError(message)+ errorRef.current?.(message)+ }++ const task =+ source.kind === "url"+ ? documentManager.openDocumentUrl({+ url: source.url,+ name: source.name,+ mode: source.url.startsWith("blob:") ? "full-fetch" : "auto",+ autoActivate: previousIds.length === 0,+ })+ : documentManager.openDocumentBuffer({+ buffer: source.buffer.slice(0),+ name: source.name,+ autoActivate: previousIds.length === 0,+ })++ task.wait(+ (response) => {+ response.task.wait(+ (openedDocument) => {+ documentManager.setActiveDocument(response.documentId)+ successRef.current?.({+ numPages: openedDocument.pageCount,+ documentId: response.documentId,+ fileName: source.name,+ })+ previousIds.forEach((id) => {+ if (id !== response.documentId) {+ documentManager.closeDocument(id).wait(noop, noop)+ }+ })+ },+ (failure) => {+ // Password prompts are handled through the document state.+ if (failure?.reason?.code === PdfErrorCode.Password) return+ fail(failure?.reason?.message ?? "The PDF could not be loaded.")+ }+ )+ },+ (failure) =>+ fail(failure?.reason?.message ?? "The PDF could not be loaded.")+ )+ }, [documentManager, source])++ const fileName = fileNameOverride+ ? getPdfFileName(fileNameOverride)+ : (source?.name ?? getPdfFileName(undefined))+ const passwordRequired =+ activeDocument?.status === "error" &&+ activeDocument.errorCode === PdfErrorCode.Password+ const documentFailed =+ loadError !== null ||+ (activeDocument?.status === "error" && !passwordRequired)++ if (+ !source ||+ sourceLoading ||+ !activeDocumentId ||+ documentFailed ||+ passwordRequired+ ) {+ return (+ <PdfEditorFallbackShell+ className={innerProps.className}+ fileName={source?.name}+ showToolbar={innerProps.showToolbar}+ showUpload={innerProps.showUpload}+ state={+ !source && !sourceLoading+ ? "empty"+ : passwordRequired+ ? "password"+ : documentFailed+ ? "error"+ : "loading"+ }+ errorMessage={loadError ?? activeDocument?.error ?? undefined}+ onUploadFile={innerProps.onUploadFile}+ >+ {passwordRequired && activeDocument ? (+ <div className="flex-1">+ <PdfEditorPasswordPrompt documentState={activeDocument} />+ </div>+ ) : null}+ </PdfEditorFallbackShell>+ )+ }++ const document =+ activeDocument?.status === "loaded" ? activeDocument.document : null++ return (+ <>+ <PdfEditorSignaturePersistence storageKey={signatureStorageKey} />+ <PdfEditorInner+ key={activeDocumentId}+ {...innerProps}+ documentId={activeDocumentId}+ document={document}+ fileName={fileName}+ leftPanel={leftPanel}+ setLeftPanel={setLeftPanel}+ formDesignMode={formDesignMode}+ setFormDesignMode={setFormDesignMode}+ />+ </>+ )+}++/* -------------------------------------------------------------------------- */+/* Root */+/* -------------------------------------------------------------------------- */++export const PDFEditor = React.forwardRef<PDFEditorHandle, PDFEditorProps>(+ function PDFEditor(+ {+ className,+ src,+ fileName,+ defaultZoom = "fit-width",+ defaultMode = "view",+ annotationAuthor = DEFAULT_ANNOTATION_AUTHOR,+ colorPresets = PDF_EDITOR_DEFAULT_COLOR_PRESETS,+ features,+ showToolbar = true,+ showUpload = true,+ showDownload = true,+ toolbarActions,+ selectionActions,+ persistSignatures = true,+ stampManifests,+ signatureFontsStylesheetUrl = PDF_EDITOR_DEFAULT_SIGNATURE_FONTS_URL,+ resolveScrollAreaViewport,+ renderPageOverlay,+ onDocumentLoadSuccess,+ onDocumentLoadError,+ onActivePageChange,+ onModeChange,+ onAnnotationEvent,+ onAnnotationsChange,+ onFormValuesChange,+ onRedactionsApplied,+ onSave,+ onCapture,+ onPdfUpload,+ onToast,+ onSelectionAction,+ },+ ref+ ) {+ const { engine, error: engineError } = useSharedPdfEngine()+ const {+ source,+ loading: sourceLoading,+ replace,+ } = useEditorSource(src, fileName)+ const handleRef = React.useRef<EditorHandleImpl | null>(null)+ const resolvedFeatures = React.useMemo<PdfEditorResolvedFeatures>(+ () => ({ ...PDF_EDITOR_DEFAULT_FEATURES, ...features }),+ [features]+ )+ const resolvedSelectionActions = React.useMemo(+ () => selectionActions ?? [],+ [selectionActions]+ )+ const signatureStorageKey =+ persistSignatures === false+ ? null+ : typeof persistSignatures === "string"+ ? persistSignatures+ : DEFAULT_SIGNATURE_STORAGE_KEY++ const handleUploadFile = React.useCallback(+ (file: File) => {+ file.arrayBuffer().then((buffer) => {+ replace(buffer, getPdfFileName(file.name))+ onPdfUpload?.(file)+ })+ },+ [onPdfUpload, replace]+ )++ // Plugin registrations are created once per editor instance.+ const [plugins] = React.useState(() => [+ createPluginRegistration(DocumentManagerPluginPackage),+ createPluginRegistration(ViewportPluginPackage, {+ viewportGap: PAGE_GAP,+ }),+ createPluginRegistration(ScrollPluginPackage, {+ defaultPageGap: PAGE_GAP,+ defaultBufferSize: 2,+ }),+ createPluginRegistration(RenderPluginPackage),+ createPluginRegistration(TilingPluginPackage, {+ tileSize: 768,+ overlapPx: 2.5,+ extraRings: 0,+ }),+ createPluginRegistration(InteractionManagerPluginPackage),+ createPluginRegistration(SelectionPluginPackage, {+ menuHeight: SELECTION_MENU_HEIGHT,+ }),+ createPluginRegistration(SearchPluginPackage, { showAllResults: true }),+ createPluginRegistration(ThumbnailPluginPackage, {+ width: THUMBNAIL_WIDTH,+ gap: THUMBNAIL_GAP,+ imagePadding: THUMBNAIL_IMAGE_PADDING,+ labelHeight: THUMBNAIL_LABEL_HEIGHT,+ paddingY: THUMBNAIL_PANE_PADDING_Y,+ buffer: 3,+ autoScroll: true,+ scrollBehavior: "auto",+ }),+ createPluginRegistration(ZoomPluginPackage, {+ defaultZoomLevel: toZoomLevel(defaultZoom),+ minZoom: MIN_ZOOM,+ maxZoom: MAX_ZOOM,+ }),+ createPluginRegistration(RotatePluginPackage),+ createPluginRegistration(SpreadPluginPackage, {+ defaultSpreadMode: SpreadMode.None,+ }),+ createPluginRegistration(PanPluginPackage, { defaultMode: "never" }),+ createPluginRegistration(HistoryPluginPackage),+ createPluginRegistration(AnnotationPluginPackage, {+ annotationAuthor,+ colorPresets,+ autoCommit: true,+ selectAfterCreate: true,+ deactivateToolAfterCreate: false,+ locked: { type: LockModeType.Include, categories: ["form"] },+ }),+ createPluginRegistration(FormPluginPackage),+ createPluginRegistration(RedactionPluginPackage, {+ drawBlackBoxes: true,+ useAnnotationMode: true,+ }),+ createPluginRegistration(StampPluginPackage, {+ defaultLibrary: {+ id: "custom",+ name: "Custom stamps",+ categories: ["custom", "sidebar"],+ },+ ...(stampManifests && stampManifests.length > 0+ ? {+ manifests: [+ {+ url: PDF_EDITOR_DEFAULT_STAMP_MANIFEST_URL,+ fallbackLocale: "en",+ },+ ...stampManifests.map((url) => ({ url })),+ ],+ }+ : {}),+ }),+ createPluginRegistration(SignaturePluginPackage, {+ mode: SignatureMode.SignatureAndInitials,+ defaultSize: { width: 160, height: 56 },+ }),+ createPluginRegistration(ExportPluginPackage, {+ defaultFileName: "document.pdf",+ }),+ createPluginRegistration(PrintPluginPackage),+ createPluginRegistration(CapturePluginPackage, {+ scale: 2,+ imageType: "image/png",+ withAnnotations: true,+ }),+ createPluginRegistration(FullscreenPluginPackage),+ createPluginRegistration(BookmarkPluginPackage),+ createPluginRegistration(AttachmentPluginPackage),+ ])++ React.useImperativeHandle(+ ref,+ () => ({+ getDocumentBuffer: () =>+ handleRef.current?.getDocumentBuffer() ??+ Promise.reject(new Error("The document is not ready.")),+ download: (name) =>+ handleRef.current?.download(name) ?? Promise.resolve(),+ print: (options) =>+ handleRef.current?.print(options) ?? Promise.resolve(),+ exportAnnotations: () =>+ handleRef.current?.exportAnnotations() ?? Promise.resolve([]),+ importAnnotations: (items) =>+ handleRef.current?.importAnnotations(items),+ getFormValues: () => handleRef.current?.getFormValues() ?? {},+ setFormValues: (values) =>+ handleRef.current?.setFormValues(values) ?? Promise.resolve(),+ applyRedactions: () =>+ handleRef.current?.applyRedactions() ?? Promise.resolve(),+ setMode: (mode) => handleRef.current?.setMode(mode),+ setActiveTool: (toolId) => handleRef.current?.setActiveTool(toolId),+ scrollToPage: (pageNumber, options) =>+ handleRef.current?.scrollToPage(pageNumber, options),+ undo: () => handleRef.current?.undo(),+ redo: () => handleRef.current?.redo(),+ getViewportElement: () =>+ handleRef.current?.getViewportElement() ?? null,+ }),+ []+ )++ if (engineError) {+ return (+ <PdfEditorFallbackShell+ className={className}+ fileName={source?.name}+ showToolbar={showToolbar}+ showUpload={showUpload}+ state="error"+ errorMessage="The PDF engine could not be loaded."+ onUploadFile={handleUploadFile}+ />+ )+ }++ if (!engine) {+ return (+ <PdfEditorFallbackShell+ className={className}+ fileName={source?.name}+ showToolbar={showToolbar}+ showUpload={showUpload}+ state="loading"+ onUploadFile={handleUploadFile}+ />+ )+ }++ return (+ <PdfEditorScrollAreaResolverContext.Provider+ value={resolveScrollAreaViewport ?? resolveDefaultScrollAreaViewport}+ >+ <EmbedPDF engine={engine} plugins={plugins}>+ <PdfEditorDocumentLoader+ source={source}+ sourceLoading={sourceLoading}+ fileNameOverride={fileName}+ signatureStorageKey={signatureStorageKey}+ className={className}+ defaultZoom={defaultZoom}+ defaultMode={defaultMode}+ annotationAuthor={annotationAuthor}+ features={resolvedFeatures}+ showToolbar={showToolbar}+ showUpload={showUpload}+ showDownload={showDownload}+ toolbarActions={toolbarActions}+ selectionActions={resolvedSelectionActions}+ signatureFontsStylesheetUrl={signatureFontsStylesheetUrl}+ renderPageOverlay={renderPageOverlay}+ handleRef={handleRef}+ onReplaceDocument={replace}+ onUploadFile={handleUploadFile}+ onDocumentLoadSuccess={onDocumentLoadSuccess}+ onDocumentLoadError={onDocumentLoadError}+ onActivePageChange={onActivePageChange}+ onModeChange={onModeChange}+ onAnnotationEvent={onAnnotationEvent}+ onAnnotationsChange={onAnnotationsChange}+ onFormValuesChange={onFormValuesChange}+ onRedactionsApplied={onRedactionsApplied}+ onSave={onSave}+ onCapture={onCapture}+ onToast={onToast}+ onSelectionAction={onSelectionAction}+ />+ </EmbedPDF>+ </PdfEditorScrollAreaResolverContext.Provider>+ )+ }+)diff --git a/apps/v4/components/extend/pdf-viewer.tsx b/apps/v4/components/extend/pdf-viewer.tsxindex 2ed5aa6..a572db2 100644--- a/apps/v4/components/extend/pdf-viewer.tsx+++ b/apps/v4/components/extend/pdf-viewer.tsx@@ -529,6 +529,7 @@ function PDFViewerFallbackShell({</Button></ToolbarTooltip>}+ sidebarOpen={sidebarOpen}showDownload={showDownload}showRotateControls={showRotateControls}showUpload={showUpload}@@ -1036,6 +1037,7 @@ function PDFViewerToolbar({isPreparingDownload = false,numPages,searchControl,+ sidebarOpen,showDownload,showRotateControls,showUpload,@@ -1054,6 +1056,7 @@ function PDFViewerToolbar({isPreparingDownload?: booleannumPages: numbersearchControl: React.ReactNode+ sidebarOpen: booleanshowDownload: booleanshowRotateControls: booleanshowUpload: boolean@@ -1069,12 +1072,18 @@ function PDFViewerToolbar({<div className="flex min-h-12 flex-wrap items-center justify-between gap-2 border-b bg-background px-3 py-2"><div className="flex min-w-0 flex-wrap items-center gap-2"><TooltipProvider>- <ToolbarTooltip label="Toggle thumbnails">+ <ToolbarTooltip label="Pages sidebar"><Buttontype="button"variant="ghost"size="icon-sm"- aria-label="Toggle thumbnails"+ aria-label="Pages sidebar"+ aria-pressed={sidebarOpen}+ data-active={sidebarOpen ? "" : undefined}+ className={cn(+ sidebarOpen &&+ "bg-accent text-accent-foreground ring-1 ring-ring/40 ring-inset"+ )}disabled={controlsDisabled}onClick={onToggleSidebar}>@@ -2643,6 +2652,7 @@ function PDFViewerInner({controlsDisabled={controlsDisabled}/>}+ sidebarOpen={sidebarOpen}showDownload={showDownload}showRotateControls={showRotateControls}showUpload={showUpload}diff --git a/apps/v4/components/extend/xlsx-editor.tsx b/apps/v4/components/extend/xlsx-editor.tsxindex d66d963..f5c4c43 100644--- a/apps/v4/components/extend/xlsx-editor.tsx+++ b/apps/v4/components/extend/xlsx-editor.tsx@@ -1172,7 +1172,7 @@ function BorderMenu({/></DropdownMenuSubTrigger><DropdownMenuSubContent- className={cn("w-64 p-2", XLSX_DROPDOWN_Z_INDEX_CLASS)}+ className={cn("w-auto p-3", XLSX_DROPDOWN_Z_INDEX_CLASS)}><ColorPickerPanellabel="Border color"diff --git a/apps/v4/components/file-system-docs.tsx b/apps/v4/components/file-system-docs.tsxindex 0a24365..89250b4 100644--- a/apps/v4/components/file-system-docs.tsx+++ b/apps/v4/components/file-system-docs.tsx@@ -25,7 +25,7 @@ const PPTX_MIME_TYPE ="application/vnd.openxmlformats-officedocument.presentationml.presentation"const THUMBNAIL_WIDTH = 360-type DemoThumbnailKind = "docx" | "none" | "pdf" | "url" | "xlsx"+type DemoThumbnailKind = "docx" | "pdf" | "pptx" | "url" | "xlsx"type DemoSource = {contentType: string@@ -94,7 +94,7 @@ const DEMO_SOURCES: DemoSource[] = [path: "Consulting proposal.pptx",previewAspectRatio: 16 / 9,size: 8840652,- thumbnail: "none",+ thumbnail: "pptx",updatedAt: "2026-07-16T17:31:45Z",url: withUiBasePath("/samples/demo.pptx"),},@@ -242,6 +242,14 @@ const XlsxThumbnailUrlGenerator = dynamic({ ssr: false })+const PptxThumbnailUrlGenerator = dynamic(+ () =>+ import("@/components/file-system-pptx-thumbnails").then(+ (mod) => mod.PptxThumbnailUrlGenerator+ ),+ { ssr: false }+)+async function renderPdfPageThumbnail(url: string, pageIndex: number) {return renderPdfThumbnailUrl({pageIndex,@@ -297,57 +305,28 @@ type DemoThumbnails = {// a hidden DOCX import + pagination, XLSX sheet paints).const demoThumbnailCache = new Map<string, DemoThumbnails>()-// The hidden DOCX generator imports and paginates the whole 1.3MB demo.docx-// on the main thread — by far the heaviest job on the page. Its output is-// only gallery thumbnails, so hold it until the visible viewers have parsed.-const DOCX_GENERATOR_DELAY_MS = 1200--function useDeferredDocxGeneration() {- const [isReady, setIsReady] = React.useState(false)-- React.useEffect(() => {- let idleCallbackId: number | null = null- let timeoutId: number | null = window.setTimeout(() => {- timeoutId = null-- const markReady = () => setIsReady(true)-- if ("requestIdleCallback" in window) {- idleCallbackId = window.requestIdleCallback(markReady, {- timeout: 4000,- })- } else {- markReady()- }- }, DOCX_GENERATOR_DELAY_MS)-- return () => {- if (timeoutId !== null) window.clearTimeout(timeoutId)- if (idleCallbackId !== null && "cancelIdleCallback" in window) {- window.cancelIdleCallback(idleCallbackId)- }- }- }, [])-- return isReady-}-export function useFileSystemDemoItems() {const [thumbnails, setThumbnails] = React.useState<Record<string, DemoThumbnails>>(() => Object.fromEntries(demoThumbnailCache))- const canGenerateDocx = useDeferredDocxGeneration()const setPathThumbnails = React.useCallback((path: string, urls: string[], pageCount: number) => {- if (!demoThumbnailCache.has(path)) {- demoThumbnailCache.set(path, { pageCount, urls })- }+ const nextThumbnails = { pageCount, urls }++ demoThumbnailCache.set(path, nextThumbnails)React.startTransition(() => {- setThumbnails((previous) =>- previous[path]- ? previous- : { ...previous, [path]: { pageCount, urls } }- )+ setThumbnails((previous) => {+ const current = previous[path]++ if (+ current?.pageCount === pageCount &&+ current.urls.length >= urls.length+ ) {+ return previous+ }++ return { ...previous, [path]: nextThumbnails }+ })})},[]@@ -416,12 +395,14 @@ export function useFileSystemDemoItems() {}/>))}- {DEMO_SOURCES.filter(- (source) =>+ {DEMO_SOURCES.filter((source) => {+ const generated = thumbnails[source.path]++ return (source.thumbnail === "docx" &&- canGenerateDocx &&- !thumbnails[source.path]- ).map((source) => (+ (!generated || generated.urls.length < generated.pageCount)+ )+ }).map((source) => (<DocxThumbnailUrlGeneratorkey={source.path}fileName={source.path.split("/").pop() ?? source.path}@@ -443,6 +424,22 @@ export function useFileSystemDemoItems() {}/>))}+ {DEMO_SOURCES.filter((source) => {+ const generated = thumbnails[source.path]++ return (+ source.thumbnail === "pptx" &&+ (!generated || generated.urls.length < generated.pageCount)+ )+ }).map((source) => (+ <PptxThumbnailUrlGenerator+ key={source.path}+ url={source.url}+ onUrls={(dataUrls, pageCount) =>+ setPathThumbnails(source.path, dataUrls, pageCount)+ }+ />+ ))}</>)diff --git a/apps/v4/components/file-system-docx-thumbnails.tsx b/apps/v4/components/file-system-docx-thumbnails.tsxindex 6472a17..7b840fc 100644--- a/apps/v4/components/file-system-docx-thumbnails.tsx+++ b/apps/v4/components/file-system-docx-thumbnails.tsx@@ -11,9 +11,6 @@ import {const DOCX_MIME_TYPE ="application/vnd.openxmlformats-officedocument.wordprocessingml.document"const THUMBNAIL_WIDTH = 360-// Quiet period after the last reported page-count change before the DOCX-// page thumbnails are captured.-const DOCX_PAGINATION_SETTLE_MS = 600// The docx canvas reports "ready" once for the blank pre-import page; only// capture once actual content has been painted.@@ -58,14 +55,14 @@ export function DocxThumbnailUrlGenerator({})const { importDocxFile } = editorconst [isImported, setIsImported] = React.useState(false)- // Pagination reports the live page count through the viewer while pages- // are still being measured (1, 2, … final); mirror it so the thumbnails- // hook covers every page.const [reportedPageCount, setReportedPageCount] = React.useState(0)- // Capturing at the first reported count would snapshot a partially- // paginated document, so wait until the count stops changing.- const [settledPageCount, setSettledPageCount] = React.useState(0)- const settledPageCountRef = React.useRef(0)+ const reportedPageCountRef = React.useRef(0)+ const handlePageCountChange = React.useCallback((pageCount: number) => {+ const nextPageCount = Math.max(1, Math.round(pageCount || 1))++ reportedPageCountRef.current = nextPageCount+ setReportedPageCount(nextPageCount)+ }, [])const thumbnailEditor = React.useMemo<DocxEditorController>(() => ({...editor,@@ -86,6 +83,8 @@ export function DocxThumbnailUrlGenerator({[]))+ const isCoverCapturedRef = React.useRef(false)+ const isCoverCapturingRef = React.useRef(false)const isCapturedRef = React.useRef(false)const isCapturingRef = React.useRef(false)@@ -121,23 +120,40 @@ export function DocxThumbnailUrlGenerator({}, [fileName, importDocxFile, url])React.useEffect(() => {- if (!isImported || reportedPageCount === 0) return+ const coverThumbnail = thumbnails[0]++ if (!isImported || reportedPageCount === 0 || !coverThumbnail?.isMounted) {+ return+ }+ if (isCoverCapturedRef.current || isCoverCapturingRef.current) return++ isCoverCapturingRef.current = true- settledPageCountRef.current = 0- setSettledPageCount(0)+ const canvas = document.createElement("canvas")- const timeoutId = window.setTimeout(() => {- settledPageCountRef.current = reportedPageCount- setSettledPageCount(reportedPageCount)- }, DOCX_PAGINATION_SETTLE_MS)+ canvas.width = coverThumbnail.pixelWidthPx+ canvas.height = coverThumbnail.pixelHeightPx- return () => window.clearTimeout(timeoutId)- }, [isImported, reportedPageCount])+ void coverThumbnail+ .renderToCanvas(canvas)+ .then(() => {+ if (isCapturedRef.current || isCoverCapturedRef.current) return+ if (reportedPageCountRef.current !== reportedPageCount) return+ if (!canvasHasInk(canvas)) return++ isCoverCapturedRef.current = true+ onUrls([canvas.toDataURL("image/png")], reportedPageCount)+ })+ .catch(() => {})+ .finally(() => {+ isCoverCapturingRef.current = false+ })+ }, [isImported, onUrls, reportedPageCount, thumbnails])React.useEffect(() => {- if (settledPageCount === 0) return+ if (!isImported || reportedPageCount === 0) returnif (isCapturedRef.current || isCapturingRef.current) return- if (thumbnails.length < settledPageCount) return+ if (thumbnails.length < reportedPageCount) returnif (thumbnails.some((thumbnail) => !thumbnail.isMounted)) return// Guarded by a ref instead of effect cleanup: each render call updates@@ -160,8 +176,8 @@ export function DocxThumbnailUrlGenerator({if (isCapturedRef.current) return// Pagination moved on while the capture was in flight — drop the- // stale snapshot and let the next settled count retry.- if (settledPageCountRef.current !== settledPageCount) return+ // stale snapshot and let the next reported count retry.+ if (reportedPageCountRef.current !== reportedPageCount) return// The first paint can race the imported content; skip blank frames// so the next thumbnail state change retries.if (!canvases[0] || !canvasHasInk(canvases[0])) return@@ -175,7 +191,7 @@ export function DocxThumbnailUrlGenerator({.catch(() => {isCapturingRef.current = false})- }, [onUrls, settledPageCount, thumbnails])+ }, [isImported, onUrls, reportedPageCount, thumbnails])return (<div@@ -190,9 +206,7 @@ export function DocxThumbnailUrlGenerator({pageGapBackgroundColor="transparent"pageVirtualization={{ enabled: false }}deferInitialPaginationPaint={false}- onPageCountChange={(pageCount) =>- setReportedPageCount(Math.max(1, Math.round(pageCount || 1)))- }+ onPageCountChange={handlePageCountChange}/></div></div>diff --git a/apps/v4/components/file-system-pptx-thumbnails.tsx b/apps/v4/components/file-system-pptx-thumbnails.tsxnew file mode 100644index 0000000..5527641--- /dev/null+++ b/apps/v4/components/file-system-pptx-thumbnails.tsx@@ -0,0 +1,151 @@+"use client"++import * as React from "react"+import {+ ReactPptxViewer,+ usePptxViewer,+ usePptxViewerThumbnails,+} from "@extend-ai/react-pptx"+import { toPng } from "html-to-image"++import "@extend-ai/react-pptx/styles.css"++const THUMBNAIL_WIDTH = 360++function waitForPaint() {+ return new Promise<void>((resolve) => {+ window.requestAnimationFrame(() => {+ window.requestAnimationFrame(() => resolve())+ })+ })+}++async function waitForImages(element: HTMLElement) {+ await Promise.all(+ Array.from(element.querySelectorAll("img")).map(async (image) => {+ if (!image.complete) {+ await new Promise<void>((resolve) => {+ image.addEventListener("load", () => resolve(), { once: true })+ image.addEventListener("error", () => resolve(), { once: true })+ })+ }++ await image.decode().catch(() => {})+ })+ )+}++export function PptxThumbnailUrlGenerator({+ onUrls,+ url,+}: {+ onUrls: (dataUrls: string[], pageCount: number) => void+ url: string+}) {+ const viewer = usePptxViewer()+ const captureHostRef = React.useRef<HTMLDivElement>(null)+ const [isReady, setIsReady] = React.useState(false)+ const { thumbnails } = usePptxViewerThumbnails(+ viewer.controller,+ React.useMemo(+ () => ({+ resolution: {+ maxHeight: THUMBNAIL_WIDTH,+ maxWidth: THUMBNAIL_WIDTH,+ },+ }),+ []+ )+ )+ const isCapturedRef = React.useRef(false)+ const isCapturingRef = React.useRef(false)+ const isMountedRef = React.useRef(true)++ React.useEffect(() => {+ isMountedRef.current = true++ return () => {+ isMountedRef.current = false+ }+ }, [])++ React.useEffect(() => {+ if (!isReady || thumbnails.length === 0 || !captureHostRef.current) return+ if (isCapturedRef.current || isCapturingRef.current) return++ const captureHost = captureHostRef.current++ isCapturingRef.current = true++ void (async () => {+ const dataUrls: string[] = []++ for (const thumbnail of thumbnails) {+ if (!isMountedRef.current) return++ const element = document.createElement("div")++ element.style.width = `${thumbnail.width}px`+ element.style.height = `${thumbnail.height}px`+ element.style.overflow = "hidden"+ element.style.background = "white"+ captureHost.append(element)++ try {+ await thumbnail.renderToContainer(element)+ await document.fonts.ready+ await waitForImages(element)+ await waitForPaint()++ dataUrls.push(+ await toPng(element, {+ backgroundColor: "#ffffff",+ cacheBust: false,+ height: thumbnail.height,+ pixelRatio: 1,+ skipAutoScale: true,+ width: thumbnail.width,+ })+ )+ if (isMountedRef.current) {+ onUrls([...dataUrls], thumbnails.length)+ }+ } finally {+ thumbnail.containerRef(null)+ element.remove()+ }+ }++ if (!isMountedRef.current || dataUrls.length === 0) return++ isCapturedRef.current = true+ onUrls(dataUrls, thumbnails.length)+ })()+ .catch(() => {})+ .finally(() => {+ isCapturingRef.current = false+ })+ }, [isReady, onUrls, thumbnails])++ return (+ <div+ aria-hidden="true"+ className="pointer-events-none fixed top-0 -left-[10000px] h-[203px] w-[360px] overflow-hidden bg-white [contain:layout_paint]"+ >+ <ReactPptxViewer+ ref={viewer.ref}+ source={url}+ mode="slide"+ width={THUMBNAIL_WIDTH}+ height={203}+ showToolbar={false}+ showThumbnails={false}+ showNotes={false}+ showSlideLabels={false}+ virtualization={false}+ onReady={() => setIsReady(true)}+ />+ <div ref={captureHostRef} />+ </div>+ )+}diff --git a/apps/v4/components/icon-placeholder.tsx b/apps/v4/components/icon-placeholder.tsxindex a2494ec..d5696c8 100644--- a/apps/v4/components/icon-placeholder.tsx+++ b/apps/v4/components/icon-placeholder.tsx@@ -6,12 +6,18 @@ import {AlignBoxMiddleCenterIcon,AlignBoxTopCenterIcon,ArrowDown01Icon,+ ArrowDown02Icon,ArrowExpandDiagonal01Icon,ArrowExpandDiagonal02Icon,ArrowLeft01Icon,+ ArrowLeftRightIcon,ArrowRight01Icon,ArrowUp01Icon,+ ArrowUp02Icon,ArrowUpDownIcon,+ ArrowUpRight01Icon,+ Attachment01Icon,+ Book01Icon,BorderAll01Icon,BorderBottom01Icon,BorderHorizontalIcon,@@ -21,61 +27,108 @@ import {BorderRight01Icon,BorderTop01Icon,BorderVerticalIcon,+ BrushIcon,+ BubbleChatIcon,Calendar03Icon,+ Camera01Icon,Cancel01Icon,CancelCircleIcon,CellsIcon,CheckIcon,CheckmarkCircle01Icon,+ CheckmarkSquare01Icon,ChevronDown,ChevronDownIcon,ChevronUp,+ CircleIcon,+ ClipboardIcon,+ ColorPickerIcon,ColumnsThreeCogIcon,Comment01Icon,+ CommentAdd01Icon,+ Copy01Icon,+ Cursor01Icon,+ CursorRectangleSelection01Icon,+ CursorTextIcon,Delete02Icon,DollarCircleIcon,Download01Icon,DragDropVerticalIcon,DropletOffIcon,EditOffIcon,+ ExternalLinkIcon,File01Icon,+ FileAddIcon,FileDiffIcon,FileImageIcon,FilePenIcon,FileSpreadsheetIcon,FileUploadIcon,FilterIcon,+ Flag01Icon,+ FloppyDiskIcon,+ FullScreenIcon,GalleryThumbnailsIcon,+ GitMergeIcon,Grid2X2XIcon,GridViewIcon,+ GroupItemsIcon,+ HandIcon,Heading01Icon,HighlighterIcon,+ Image01Icon,ImageAdd01Icon,ImageCompositionIcon,InformationCircleIcon,InputNumericIcon,InputTextIcon,+ Key01Icon,+ KeyboardIcon,+ Layers01Icon,LayoutThreeColumnIcon,LeftToRightListBulletIcon,LeftToRightListNumberIcon,LineIcon,Link02Icon,+ ListTreeIcon,Loading03Icon,+ MinimizeScreenIcon,MinusSignCircleIcon,+ MinusSignIcon,Moon02Icon,MoreHorizontalIcon,+ MoveIcon,+ PaintBoardIcon,PaintBucketIcon,ParagraphIcon,PathfinderMergeIcon,Pen01Icon,+ PencilEdit01Icon,PercentIcon,PlusSignCircleIcon,+ PolygonIcon,+ PrinterIcon,+ RadioButtonIcon,Redo02Icon,+ RefreshIcon,+ ReplaceIcon,RotateClockwiseIcon,+ Scissor01Icon,Search01Icon,SecondBracketIcon,+ Shield01Icon,SidebarLeftIcon,+ SidebarRightIcon,+ SignatureIcon,+ SlidersHorizontalIcon,SourceCodeSquareIcon,+ SparklesIcon,+ SplinePointerIcon,+ SquareIcon,+ SquareLock02Icon,+ SquareUnlock02Icon,+ StampIcon,+ StickyNote01Icon,Sun03Icon,Table01Icon,TableIcon,@@ -88,6 +141,8 @@ import {TextCenterlineCenterTopIcon,TextCheckIcon,TextColorIcon,+ TextFontIcon,+ TextIcon,TextItalicIcon,TextNumberSignIcon,TextStrikethroughIcon,@@ -97,7 +152,13 @@ import {TextWrapIcon,Tick02Icon,Undo02Icon,+ UnfoldMoreIcon,+ UngroupItemsIcon,Upload01Icon,+ ViewIcon,+ ViewOffIcon,+ WaveIcon,+ ZoomInAreaIcon,} from "@hugeicons/core-free-icons"import { HugeiconsIcon } from "@hugeicons/react"@@ -117,12 +178,18 @@ const hugeicons = {AlignBoxMiddleCenterIcon,AlignBoxTopCenterIcon,ArrowDown01Icon,+ ArrowDown02Icon,ArrowExpandDiagonal01Icon,ArrowExpandDiagonal02Icon,ArrowLeft01Icon,+ ArrowLeftRightIcon,ArrowRight01Icon,ArrowUp01Icon,+ ArrowUp02Icon,ArrowUpDownIcon,+ ArrowUpRight01Icon,+ Attachment01Icon,+ Book01Icon,BorderAll01Icon,BorderBottom01Icon,BorderHorizontalIcon,@@ -132,61 +199,108 @@ const hugeicons = {BorderRight01Icon,BorderTop01Icon,BorderVerticalIcon,+ BrushIcon,+ BubbleChatIcon,Calendar03Icon,+ Camera01Icon,Cancel01Icon,CancelCircleIcon,CellsIcon,CheckIcon,CheckmarkCircle01Icon,+ CheckmarkSquare01Icon,ChevronDown,ChevronDownIcon,ChevronUp,+ CircleIcon,+ ClipboardIcon,ColumnsThreeCogIcon,Comment01Icon,+ CommentAdd01Icon,+ ColorPickerIcon,+ Copy01Icon,+ Cursor01Icon,+ CursorRectangleSelection01Icon,+ CursorTextIcon,Delete02Icon,DollarCircleIcon,Download01Icon,DragDropVerticalIcon,DropletOffIcon,EditOffIcon,+ ExternalLinkIcon,File01Icon,+ FileAddIcon,FileDiffIcon,FileImageIcon,FilePenIcon,FileSpreadsheetIcon,FileUploadIcon,FilterIcon,+ Flag01Icon,+ FloppyDiskIcon,+ FullScreenIcon,GalleryThumbnailsIcon,+ GitMergeIcon,Grid2X2XIcon,GridViewIcon,+ GroupItemsIcon,+ HandIcon,Heading01Icon,HighlighterIcon,+ Image01Icon,ImageAdd01Icon,ImageCompositionIcon,InformationCircleIcon,InputNumericIcon,InputTextIcon,+ Key01Icon,+ KeyboardIcon,+ Layers01Icon,LayoutThreeColumnIcon,LeftToRightListBulletIcon,LeftToRightListNumberIcon,LineIcon,Link02Icon,+ ListTreeIcon,Loading03Icon,+ MinimizeScreenIcon,MinusSignCircleIcon,+ MinusSignIcon,Moon02Icon,MoreHorizontalIcon,+ MoveIcon,+ PaintBoardIcon,PaintBucketIcon,ParagraphIcon,PathfinderMergeIcon,Pen01Icon,+ PencilEdit01Icon,PercentIcon,PlusSignCircleIcon,+ PolygonIcon,+ PrinterIcon,+ RadioButtonIcon,Redo02Icon,+ RefreshIcon,+ ReplaceIcon,RotateClockwiseIcon,+ Scissor01Icon,Search01Icon,SecondBracketIcon,+ Shield01Icon,SidebarLeftIcon,+ SidebarRightIcon,+ SignatureIcon,+ SlidersHorizontalIcon,SourceCodeSquareIcon,+ SparklesIcon,+ SplinePointerIcon,+ SquareIcon,+ SquareLock02Icon,+ SquareUnlock02Icon,+ StampIcon,+ StickyNote01Icon,Sun03Icon,Table01Icon,TableIcon,@@ -199,6 +313,8 @@ const hugeicons = {TextCenterlineCenterTopIcon,TextCheckIcon,TextColorIcon,+ TextFontIcon,+ TextIcon,TextItalicIcon,TextNumberSignIcon,TextStrikethroughIcon,@@ -208,7 +324,13 @@ const hugeicons = {TextWrapIcon,Tick02Icon,Undo02Icon,+ UnfoldMoreIcon,+ UngroupItemsIcon,Upload01Icon,+ ViewIcon,+ ViewOffIcon,+ WaveIcon,+ ZoomInAreaIcon,}export type IconPlaceholderProps = {diff --git a/apps/v4/components/pdf-editor-docs.tsx b/apps/v4/components/pdf-editor-docs.tsxnew file mode 100644index 0000000..5f733ef--- /dev/null+++ b/apps/v4/components/pdf-editor-docs.tsx@@ -0,0 +1,139 @@+"use client"++import * as React from "react"+import dynamic from "next/dynamic"++import { cn } from "@/lib/utils"+import { Spinner } from "@/components/ui/spinner"+import { DocsViewCodeBlock } from "@/components/docs-code-block"++function PdfEditorLoadingShell({+ heightClassName = "h-[720px]",+}: {+ heightClassName?: string+}) {+ return (+ <div+ data-slot="pdf-editor"+ data-loading+ className={cn(+ "flex w-full flex-col overflow-hidden bg-background",+ heightClassName+ )}+ >+ <div className="flex min-h-12 items-center border-b px-3" />+ <div className="flex min-h-10 items-center border-b bg-muted/30 px-3" />+ <div className="grid min-h-0 flex-1 place-items-center bg-muted/30">+ <Spinner className="size-4" />+ </div>+ </div>+ )+}++const PdfEditorPreview = dynamic(+ () =>+ import("@/components/pdf-editor-preview-client").then(+ (mod) => mod.PdfEditorPreviewClient+ ),+ {+ ssr: false,+ loading: () => <PdfEditorLoadingShell />,+ }+)++const PdfEditorSourceCode = dynamic(+ () =>+ import("@/components/pdf-editor-source-code").then(+ (mod) => mod.PdfEditorSourceCode+ ),+ {+ ssr: false,+ loading: () => <PdfEditorSourceShell />,+ }+)++function PdfEditorSourceShell() {+ return (+ <div+ data-slot="pdf-editor-source-shell"+ className="h-72 rounded-lg border bg-code"+ />+ )+}++const pdfEditorUsageCode = `"use client";++import { PDFEditor } from "@/components/extend/pdf-editor";++export function PdfEditorExample() {+ return (+ <PDFEditor+ src="/path/to/document.pdf"+ className="h-[720px]"+ defaultMode="annotate"+ annotationAuthor="Jane Doe"+ onAnnotationsChange={(annotations) => {+ // Persist the annotation JSON however you like.+ }}+ onSave={({ buffer, fileName }) => {+ // Upload the edited PDF bytes to your backend.+ }}+ />+ );+}`++export function PdfEditorDemo() {+ return (+ <div+ data-slot="component-preview"+ className="group relative mt-4 mb-12 flex flex-col overflow-hidden rounded-xl border"+ >+ <PdfEditorPreview />+ <DocsViewCodeBlock code={pdfEditorUsageCode} />+ </div>+ )+}++export function PdfEditorBlock({+ heightClassName = "h-full",+}: {+ defaultViewerZoom?: number+ heightClassName?: string+}) {+ return <PdfEditorPreview heightClassName={heightClassName} />+}++export function PdfEditorSource() {+ const [shouldLoadSource, setShouldLoadSource] = React.useState(false)+ const containerRef = React.useRef<HTMLDivElement | null>(null)++ React.useEffect(() => {+ const container = containerRef.current+ if (!container) return++ if (!("IntersectionObserver" in window)) {+ setShouldLoadSource(true)+ return+ }++ const observer = new IntersectionObserver(+ ([entry]) => {+ if (!entry?.isIntersecting) return++ setShouldLoadSource(true)+ observer.disconnect()+ },+ { rootMargin: "700px 0px" }+ )++ observer.observe(container)++ return () => observer.disconnect()+ }, [])++ return (+ <div ref={containerRef}>+ {shouldLoadSource ? <PdfEditorSourceCode /> : <PdfEditorSourceShell />}+ </div>+ )+}diff --git a/apps/v4/components/pdf-editor-preview-client.tsx b/apps/v4/components/pdf-editor-preview-client.tsxnew file mode 100644index 0000000..2948c5e--- /dev/null+++ b/apps/v4/components/pdf-editor-preview-client.tsx@@ -0,0 +1,25 @@+"use client"++import * as React from "react"++import { withUiBasePath } from "@/lib/zone-path"+import { PDFEditor, type PdfEditorMode } from "@/components/extend/pdf-editor"++export function PdfEditorPreviewClient({+ heightClassName = "h-[720px]",+ defaultMode,+}: {+ heightClassName?: string+ defaultMode?: PdfEditorMode+}) {+ return (+ <PDFEditor+ src={withUiBasePath("/samples/attention.pdf")}+ fileName="attention-is-all-you-need.pdf"+ className={heightClassName}+ defaultZoom="fit-width"+ defaultMode={defaultMode ?? "annotate"}+ annotationAuthor="Extend"+ />+ )+}diff --git a/apps/v4/components/pdf-editor-source-code.tsx b/apps/v4/components/pdf-editor-source-code.tsxnew file mode 100644index 0000000..5cecc4f--- /dev/null+++ b/apps/v4/components/pdf-editor-source-code.tsx@@ -0,0 +1,41 @@+"use client"++import { DocsSourceCodeBlock } from "@/components/docs-code-block"++// Generated source snapshot. Regenerate when the component changes.+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',+ },+ {+ fileName: "components/extend/pdf-editor-shared.tsx",+ code: '"use client"\n\nimport * as React from "react"\nimport type { DocumentPermissions } from "@embedpdf/core/react"\nimport type {\n PdfAnnotationObject,\n PdfDocumentObject,\n Rect,\n Size,\n} from "@embedpdf/models"\nimport { PdfAnnotationSubtype } from "@embedpdf/models"\nimport type { CaptureAreaEvent } from "@embedpdf/plugin-capture/react"\n\nimport { cn } from "@/lib/utils"\nimport { Button, type ButtonProps } from "@/components/ui/button"\nimport { Kbd } from "@/components/ui/kbd"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Tooltip,\n TooltipContent,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\n/* -------------------------------------------------------------------------- */\n/* Types */\n/* -------------------------------------------------------------------------- */\n\nexport type PdfEditorMode = "view" | "annotate" | "sign" | "forms" | "redact"\n\nexport type PdfEditorLeftPanel =\n | "thumbnails"\n | "outline"\n | "attachments"\n | "pages"\n\nexport type PdfEditorRightPanel =\n | "properties"\n | "comments"\n | "redactions"\n | "stamps"\n | "signatures"\n | "forms"\n\nexport type PdfEditorFeatureFlags = {\n /** Text markup, drawing, shapes, text boxes, notes, links, and image stamps. */\n annotate?: boolean\n /** Mark text or areas for redaction and permanently apply them. */\n redact?: boolean\n /** Fill AcroForm fields and design new form widgets. */\n forms?: boolean\n /** Draw, type, or upload signatures and initials, then place them. */\n sign?: boolean\n /** Rubber stamp libraries and custom stamps. */\n stamps?: boolean\n /** Rotate, reorder, delete, insert, extract, and merge pages. */\n pages?: boolean\n /** Password protection and permission restrictions. */\n security?: boolean\n print?: boolean\n /** Area screenshot capture. */\n capture?: boolean\n /** Bookmark outline sidebar. */\n outline?: boolean\n /** Embedded file attachments sidebar. */\n attachments?: boolean\n /** Comment threads sidebar. */\n comments?: boolean\n fullscreen?: boolean\n}\n\nexport type PdfEditorResolvedFeatures = Required<PdfEditorFeatureFlags>\n\nexport const PDF_EDITOR_DEFAULT_FEATURES: PdfEditorResolvedFeatures = {\n annotate: true,\n redact: true,\n forms: true,\n sign: true,\n stamps: true,\n pages: true,\n security: true,\n print: true,\n capture: true,\n outline: true,\n attachments: true,\n comments: true,\n fullscreen: true,\n}\n\n/** A rectangle expressed as percentages (0-100) of the page size. */\nexport type PdfEditorNormalizedRect = {\n top: number\n left: number\n width: number\n height: number\n}\n\nexport type PdfEditorSelectionPage = {\n pageIndex: number\n pageNumber: number\n pageSize: Size\n /** Bounding box in PDF points (origin top-left). */\n rect: Rect\n /** Per-line rectangles in PDF points. */\n rects: Rect[]\n normalizedRect: PdfEditorNormalizedRect\n normalizedRects: PdfEditorNormalizedRect[]\n}\n\n/** Emitted for custom text-selection actions. Coordinates are page-relative. */\nexport type PdfEditorSelectionPayload = PdfEditorSelectionPage & {\n documentId: string\n /** The selected text across all pages, joined with newlines. */\n text: string\n /** Every page that the selection spans (usually one). */\n pages: PdfEditorSelectionPage[]\n}\n\nexport type PdfEditorSelectionAction = {\n id: string\n label: string\n icon?: React.ReactNode\n /** Called with page coordinates and the selected text. */\n onSelect?: (payload: PdfEditorSelectionPayload) => void\n /** Keep the text selected after the action runs. Defaults to false. */\n keepSelection?: boolean\n}\n\nexport type PdfEditorDialogRequest =\n | { type: "print" }\n | { type: "security" }\n | { type: "properties" }\n | { type: "shortcuts" }\n | { type: "signature" }\n | { type: "link"; source: "annotation" | "selection" }\n | {\n type: "confirm"\n title: string\n description?: string\n confirmLabel?: string\n destructive?: boolean\n onConfirm: () => void\n }\n\nexport type PdfEditorNoticeTone = "info" | "success" | "error"\n\nexport type PdfEditorContextValue = {\n documentId: string\n document: PdfDocumentObject | null\n fileName: string\n mode: PdfEditorMode\n setMode: (mode: PdfEditorMode) => void\n leftPanel: PdfEditorLeftPanel | null\n setLeftPanel: (panel: PdfEditorLeftPanel | null) => void\n toggleLeftPanel: (panel: PdfEditorLeftPanel) => void\n rightPanel: PdfEditorRightPanel | null\n setRightPanel: (panel: PdfEditorRightPanel | null) => void\n toggleRightPanel: (panel: PdfEditorRightPanel) => void\n openDialog: (request: PdfEditorDialogRequest) => void\n notify: (message: string, tone?: PdfEditorNoticeTone) => void\n features: PdfEditorResolvedFeatures\n permissions: DocumentPermissions\n annotationAuthor: string\n selectionActions: PdfEditorSelectionAction[]\n formDesignMode: boolean\n setFormDesignMode: React.Dispatch<React.SetStateAction<boolean>>\n /** Replaces the open document with new PDF bytes (page operations, flattening). */\n replaceDocument: (buffer: ArrayBuffer, fileName?: string) => void\n /** Downloads the current document, including pending edits. */\n downloadDocument: (fileName?: string) => Promise<void>\n /** Returns the current document bytes, including pending edits. */\n getDocumentBuffer: () => Promise<ArrayBuffer>\n scrollToPage: (pageNumber: number, options?: { smooth?: boolean }) => void\n scrollToAnnotation: (annotation: PdfAnnotationObject) => void\n onCapture?: (event: CaptureAreaEvent) => void\n onSelectionAction?: (\n actionId: string,\n payload: PdfEditorSelectionPayload\n ) => void\n signatureFontsStylesheetUrl: string | null\n}\n\nconst PdfEditorContext = React.createContext<PdfEditorContextValue | null>(null)\n\nexport const PdfEditorContextProvider = PdfEditorContext.Provider\n\nexport function usePdfEditor() {\n const context = React.useContext(PdfEditorContext)\n\n if (!context) {\n throw new Error("usePdfEditor must be used inside a PDFEditor.")\n }\n\n return context\n}\n\n/* -------------------------------------------------------------------------- */\n/* Constants */\n/* -------------------------------------------------------------------------- */\n\nexport const PDF_EDITOR_DEFAULT_COLOR_PRESETS = [\n "#111827",\n "#e11d48",\n "#f97316",\n "#facc15",\n "#22c55e",\n "#0ea5e9",\n "#2563eb",\n "#8b5cf6",\n "#ec4899",\n "#64748b",\n "#ffffff",\n]\n\nexport const PDF_EDITOR_SELECTION_COLOR = "#2563eb"\n\nexport const PDF_EDITOR_DEFAULT_STAMP_MANIFEST_URL =\n "https://cdn.jsdelivr.net/npm/@embedpdf/default-stamps/{locale}/manifest.json"\n\nexport const PDF_EDITOR_DEFAULT_SIGNATURE_FONTS_URL =\n "https://fonts.googleapis.com/css2?family=Caveat&family=Dancing+Script&family=Great+Vibes&family=Pacifico&display=swap"\n\nexport const PDF_EDITOR_SIGNATURE_FONTS: ReadonlyArray<{\n name: string\n family: string\n}> = [\n { name: "Dancing Script", family: "\'Dancing Script\', cursive" },\n { name: "Great Vibes", family: "\'Great Vibes\', cursive" },\n { name: "Pacifico", family: "\'Pacifico\', cursive" },\n { name: "Caveat", family: "\'Caveat\', cursive" },\n]\n\n/* -------------------------------------------------------------------------- */\n/* Icons */\n/* */\n/* Icons that end up in value position (tool catalogs, switch statements) are */\n/* wrapped in small `*Glyph` components so the shadcn CLI can still swap the */\n/* placeholder for the consumer\'s icon library at install time. */\n/* -------------------------------------------------------------------------- */\n\nexport type PdfEditorGlyphProps = {\n className?: string\n style?: React.CSSProperties\n}\n\nexport type PdfEditorGlyph = React.ComponentType<PdfEditorGlyphProps>\n\nexport function PanelLeftGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="PanelLeft"\n tabler="IconLayoutSidebar"\n hugeicons="SidebarLeftIcon"\n phosphor="SidebarIcon"\n remixicon="RiLayoutLeftLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function PanelRightGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="PanelRight"\n tabler="IconLayoutSidebarRight"\n hugeicons="SidebarRightIcon"\n phosphor="SidebarSimpleIcon"\n remixicon="RiLayoutRightLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function UndoGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Undo2"\n tabler="IconArrowBackUp"\n hugeicons="Undo02Icon"\n phosphor="ArrowUUpLeftIcon"\n remixicon="RiArrowGoBackLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function RedoGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Redo2"\n tabler="IconArrowForwardUp"\n hugeicons="Redo02Icon"\n phosphor="ArrowUUpRightIcon"\n remixicon="RiArrowGoForwardLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ZoomOutGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="CircleMinus"\n tabler="IconCircleMinus"\n hugeicons="MinusSignCircleIcon"\n phosphor="MinusCircleIcon"\n remixicon="RiIndeterminateCircleLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ZoomInGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="CirclePlus"\n tabler="IconCirclePlus"\n hugeicons="PlusSignCircleIcon"\n phosphor="PlusCircleIcon"\n remixicon="RiAddCircleLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function RotateGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="RotateCw"\n tabler="IconRotateClockwise"\n hugeicons="RotateClockwiseIcon"\n phosphor="ArrowClockwiseIcon"\n remixicon="RiClockwiseLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function SearchGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Search"\n tabler="IconSearch"\n hugeicons="Search01Icon"\n phosphor="MagnifyingGlassIcon"\n remixicon="RiSearchLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function MoreGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Ellipsis"\n tabler="IconDots"\n hugeicons="MoreHorizontalIcon"\n phosphor="DotsThreeIcon"\n remixicon="RiMoreLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function DownloadGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Download"\n tabler="IconDownload"\n hugeicons="Download01Icon"\n phosphor="DownloadSimpleIcon"\n remixicon="RiDownload2Line"\n className={className}\n style={style}\n />\n )\n}\n\nexport function UploadGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className={className}\n style={style}\n />\n )\n}\n\nexport function PrintGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Printer"\n tabler="IconPrinter"\n hugeicons="PrinterIcon"\n phosphor="PrinterIcon"\n remixicon="RiPrinterLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function FullscreenGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Maximize"\n tabler="IconMaximize"\n hugeicons="FullScreenIcon"\n phosphor="CornersOutIcon"\n remixicon="RiFullscreenLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ExitFullscreenGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Minimize"\n tabler="IconMinimize"\n hugeicons="MinimizeScreenIcon"\n phosphor="CornersInIcon"\n remixicon="RiFullscreenExitLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function HandGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Hand"\n tabler="IconHandStop"\n hugeicons="HandIcon"\n phosphor="HandIcon"\n remixicon="RiHand"\n className={className}\n style={style}\n />\n )\n}\n\nexport function CursorGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="MousePointer2"\n tabler="IconPointer"\n hugeicons="Cursor01Icon"\n phosphor="CursorIcon"\n remixicon="RiCursorLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function CameraGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Camera"\n tabler="IconCamera"\n hugeicons="Camera01Icon"\n phosphor="CameraIcon"\n remixicon="RiScreenshotLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function MarqueeZoomGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="ScanSearch"\n tabler="IconZoomInArea"\n hugeicons="ZoomInAreaIcon"\n phosphor="MagnifyingGlassPlusIcon"\n remixicon="RiZoomInLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function BookOpenGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="BookOpen"\n tabler="IconBook"\n hugeicons="Book01Icon"\n phosphor="BookOpenIcon"\n remixicon="RiBookOpenLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function FileGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="File"\n tabler="IconFile"\n hugeicons="File01Icon"\n phosphor="FileIcon"\n remixicon="RiFileLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ArrowsHorizontalGlyph({\n className,\n style,\n}: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="MoveHorizontal"\n tabler="IconArrowsHorizontal"\n hugeicons="ArrowLeftRightIcon"\n phosphor="ArrowsHorizontalIcon"\n remixicon="RiArrowLeftRightLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ArrowsVerticalGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="MoveVertical"\n tabler="IconArrowsVertical"\n hugeicons="ArrowUpDownIcon"\n phosphor="ArrowsVerticalIcon"\n remixicon="RiArrowUpDownLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function HighlighterGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Highlighter"\n tabler="IconHighlight"\n hugeicons="HighlighterIcon"\n phosphor="HighlighterIcon"\n remixicon="RiMarkPenLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function UnderlineGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Underline"\n tabler="IconUnderline"\n hugeicons="TextUnderlineIcon"\n phosphor="TextUnderlineIcon"\n remixicon="RiUnderline"\n className={className}\n style={style}\n />\n )\n}\n\nexport function StrikethroughGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Strikethrough"\n tabler="IconStrikethrough"\n hugeicons="TextStrikethroughIcon"\n phosphor="TextStrikethroughIcon"\n remixicon="RiStrikethrough"\n className={className}\n style={style}\n />\n )\n}\n\nexport function SquigglyGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="LineSquiggle"\n tabler="IconWaveSine"\n hugeicons="WaveIcon"\n phosphor="WaveSineIcon"\n remixicon="RiPulseLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function PenGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Pen"\n tabler="IconPencil"\n hugeicons="Pen01Icon"\n phosphor="PenIcon"\n remixicon="RiPencilLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function BrushGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Brush"\n tabler="IconBrush"\n hugeicons="BrushIcon"\n phosphor="PaintBrushIcon"\n remixicon="RiBrushLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function TextGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Type"\n tabler="IconTypography"\n hugeicons="TextIcon"\n phosphor="TextTIcon"\n remixicon="RiText"\n className={className}\n style={style}\n />\n )\n}\n\nexport function TextFontGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Type"\n tabler="IconTypography"\n hugeicons="TextFontIcon"\n phosphor="TextAaIcon"\n remixicon="RiFontSize"\n className={className}\n style={style}\n />\n )\n}\n\nexport function CalloutGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="MessageSquareText"\n tabler="IconMessage2"\n hugeicons="BubbleChatIcon"\n phosphor="ChatTextIcon"\n remixicon="RiChat3Line"\n className={className}\n style={style}\n />\n )\n}\n\nexport function StickyNoteGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="StickyNote"\n tabler="IconNote"\n hugeicons="StickyNote01Icon"\n phosphor="NoteIcon"\n remixicon="RiStickyNoteLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function SquareGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Square"\n tabler="IconSquare"\n hugeicons="SquareIcon"\n phosphor="SquareIcon"\n remixicon="RiCheckboxBlankLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function CircleGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Circle"\n tabler="IconCircle"\n hugeicons="CircleIcon"\n phosphor="CircleIcon"\n remixicon="RiCircleLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function LineGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Minus"\n tabler="IconLine"\n hugeicons="LineIcon"\n phosphor="LineSegmentIcon"\n remixicon="RiSubtractLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ArrowGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="MoveUpRight"\n tabler="IconArrowUpRight"\n hugeicons="ArrowUpRight01Icon"\n phosphor="ArrowUpRightIcon"\n remixicon="RiArrowRightUpLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function PolylineGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Spline"\n tabler="IconVectorSpline"\n hugeicons="SplinePointerIcon"\n phosphor="VectorTwoIcon"\n remixicon="RiRouteLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function PolygonGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Pentagon"\n tabler="IconPolygon"\n hugeicons="PolygonIcon"\n phosphor="PolygonIcon"\n remixicon="RiPentagonLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ImageGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Image"\n tabler="IconPhoto"\n hugeicons="Image01Icon"\n phosphor="ImageIcon"\n remixicon="RiImageLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function StampGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Stamp"\n tabler="IconRubberStamp"\n hugeicons="StampIcon"\n phosphor="StampIcon"\n remixicon="RiVerifiedBadgeLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function LinkGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Link"\n tabler="IconLink"\n hugeicons="Link02Icon"\n phosphor="LinkIcon"\n remixicon="RiLink"\n className={className}\n style={style}\n />\n )\n}\n\nexport function InsertTextGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="TextCursorInput"\n tabler="IconCursorText"\n hugeicons="CursorTextIcon"\n phosphor="CursorTextIcon"\n remixicon="RiInputCursorMove"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ReplaceTextGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Replace"\n tabler="IconReplace"\n hugeicons="ReplaceIcon"\n phosphor="ArrowsLeftRightIcon"\n remixicon="RiFindReplaceLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function TrashGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Trash2"\n tabler="IconTrash"\n hugeicons="Delete02Icon"\n phosphor="TrashIcon"\n remixicon="RiDeleteBinLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function GroupGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Group"\n tabler="IconLayersUnion"\n hugeicons="GroupItemsIcon"\n phosphor="StackIcon"\n remixicon="RiStackLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function UngroupGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Ungroup"\n tabler="IconLayersSubtract"\n hugeicons="UngroupItemsIcon"\n phosphor="StackSimpleIcon"\n remixicon="RiStackLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function LockGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Lock"\n tabler="IconLock"\n hugeicons="SquareLock02Icon"\n phosphor="LockIcon"\n remixicon="RiLockLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function UnlockGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="LockOpen"\n tabler="IconLockOpen"\n hugeicons="SquareUnlock02Icon"\n phosphor="LockOpenIcon"\n remixicon="RiLockUnlockLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function CommentGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="MessageCircle"\n tabler="IconMessageCircle"\n hugeicons="Comment01Icon"\n phosphor="ChatCircleIcon"\n remixicon="RiChat1Line"\n className={className}\n style={style}\n />\n )\n}\n\nexport function CommentsGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="MessagesSquare"\n tabler="IconMessages"\n hugeicons="CommentAdd01Icon"\n phosphor="ChatsIcon"\n remixicon="RiChat3Line"\n className={className}\n style={style}\n />\n )\n}\n\nexport function CheckGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Check"\n tabler="IconCheck"\n hugeicons="Tick02Icon"\n phosphor="CheckIcon"\n remixicon="RiCheckLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function CloseGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="X"\n tabler="IconX"\n hugeicons="Cancel01Icon"\n phosphor="XIcon"\n remixicon="RiCloseLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function PlusGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Plus"\n tabler="IconPlus"\n hugeicons="Add01Icon"\n phosphor="PlusIcon"\n remixicon="RiAddLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function MinusGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Minus"\n tabler="IconMinus"\n hugeicons="MinusSignIcon"\n phosphor="MinusIcon"\n remixicon="RiSubtractLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function CopyGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Copy"\n tabler="IconCopy"\n hugeicons="Copy01Icon"\n phosphor="CopyIcon"\n remixicon="RiFileCopyLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function EyeOffGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="EyeOff"\n tabler="IconEyeOff"\n hugeicons="ViewOffIcon"\n phosphor="EyeSlashIcon"\n remixicon="RiEyeOffLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function EyeGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Eye"\n tabler="IconEye"\n hugeicons="ViewIcon"\n phosphor="EyeIcon"\n remixicon="RiEyeLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function RedactAreaGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="SquareDashed"\n tabler="IconSquareDashed"\n hugeicons="CursorRectangleSelection01Icon"\n phosphor="SelectionIcon"\n remixicon="RiCropLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function SignatureGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Signature"\n tabler="IconSignature"\n hugeicons="SignatureIcon"\n phosphor="SignatureIcon"\n remixicon="RiQuillPenLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function TextFieldGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="RectangleEllipsis"\n tabler="IconForms"\n hugeicons="InputTextIcon"\n phosphor="TextboxIcon"\n remixicon="RiInputField"\n className={className}\n style={style}\n />\n )\n}\n\nexport function CheckboxGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="SquareCheck"\n tabler="IconSquareCheck"\n hugeicons="CheckmarkSquare01Icon"\n phosphor="CheckSquareIcon"\n remixicon="RiCheckboxLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function RadioGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="CircleDot"\n tabler="IconCircleDot"\n hugeicons="RadioButtonIcon"\n phosphor="RadioButtonIcon"\n remixicon="RiRadioButtonLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ComboboxGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="ChevronsUpDown"\n tabler="IconSelect"\n hugeicons="UnfoldMoreIcon"\n phosphor="CaretUpDownIcon"\n remixicon="RiArrowUpDownLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ListboxGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="List"\n tabler="IconList"\n hugeicons="LeftToRightListBulletIcon"\n phosphor="ListIcon"\n remixicon="RiListUnordered"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ListTreeGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="ListTree"\n tabler="IconListTree"\n hugeicons="ListTreeIcon"\n phosphor="TreeStructureIcon"\n remixicon="RiNodeTree"\n className={className}\n style={style}\n />\n )\n}\n\nexport function PaperclipGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Paperclip"\n tabler="IconPaperclip"\n hugeicons="Attachment01Icon"\n phosphor="PaperclipIcon"\n remixicon="RiAttachment2"\n className={className}\n style={style}\n />\n )\n}\n\nexport function GridGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="LayoutGrid"\n tabler="IconLayoutGrid"\n hugeicons="GridViewIcon"\n phosphor="SquaresFourIcon"\n remixicon="RiLayoutGridLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function SlidersGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="SlidersHorizontal"\n tabler="IconAdjustmentsHorizontal"\n hugeicons="SlidersHorizontalIcon"\n phosphor="SlidersHorizontalIcon"\n remixicon="RiEqualizerLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function InfoGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Info"\n tabler="IconInfoCircle"\n hugeicons="InformationCircleIcon"\n phosphor="InfoIcon"\n remixicon="RiInformationLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ShieldGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="ShieldCheck"\n tabler="IconShieldLock"\n hugeicons="Shield01Icon"\n phosphor="ShieldCheckIcon"\n remixicon="RiShieldKeyholeLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function FileTextGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="FileText"\n tabler="IconFileText"\n hugeicons="File01Icon"\n phosphor="FileTextIcon"\n remixicon="RiFileTextLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ChevronDownGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="ChevronDown"\n tabler="IconChevronDown"\n hugeicons="ArrowDown01Icon"\n phosphor="CaretDownIcon"\n remixicon="RiArrowDownSLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ChevronUpGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="ChevronUp"\n tabler="IconChevronUp"\n hugeicons="ArrowUp01Icon"\n phosphor="CaretUpIcon"\n remixicon="RiArrowUpSLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ChevronLeftGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="ChevronLeft"\n tabler="IconChevronLeft"\n hugeicons="ArrowLeft01Icon"\n phosphor="CaretLeftIcon"\n remixicon="RiArrowLeftSLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ChevronRightGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="ChevronRight"\n tabler="IconChevronRight"\n hugeicons="ArrowRight01Icon"\n phosphor="CaretRightIcon"\n remixicon="RiArrowRightSLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function LayersGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Layers"\n tabler="IconStack2"\n hugeicons="Layers01Icon"\n phosphor="StackIcon"\n remixicon="RiStackLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function FilePlusGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="FilePlus"\n tabler="IconFilePlus"\n hugeicons="FileAddIcon"\n phosphor="FilePlusIcon"\n remixicon="RiFileAddLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ScissorsGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Scissors"\n tabler="IconScissors"\n hugeicons="Scissor01Icon"\n phosphor="ScissorsIcon"\n remixicon="RiScissorsLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function MergeGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Merge"\n tabler="IconArrowMerge"\n hugeicons="GitMergeIcon"\n phosphor="GitMergeIcon"\n remixicon="RiGitMergeLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function RefreshGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="RefreshCw"\n tabler="IconRefresh"\n hugeicons="RefreshIcon"\n phosphor="ArrowsClockwiseIcon"\n remixicon="RiRefreshLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function SaveGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Save"\n tabler="IconDeviceFloppy"\n hugeicons="FloppyDiskIcon"\n phosphor="FloppyDiskIcon"\n remixicon="RiSaveLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function KeyboardGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Keyboard"\n tabler="IconKeyboard"\n hugeicons="KeyboardIcon"\n phosphor="KeyboardIcon"\n remixicon="RiKeyboardLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function PaletteGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Palette"\n tabler="IconPalette"\n hugeicons="PaintBoardIcon"\n phosphor="PaletteIcon"\n remixicon="RiPaletteLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function BoldGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Bold"\n tabler="IconBold"\n hugeicons="TextBoldIcon"\n phosphor="TextBIcon"\n remixicon="RiBold"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ItalicGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Italic"\n tabler="IconItalic"\n hugeicons="TextItalicIcon"\n phosphor="TextItalicIcon"\n remixicon="RiItalic"\n className={className}\n style={style}\n />\n )\n}\n\nexport function AlignLeftGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="TextAlignStart"\n tabler="IconAlignLeft"\n hugeicons="TextAlignLeft01Icon"\n phosphor="TextAlignLeftIcon"\n remixicon="RiAlignLeft"\n className={className}\n style={style}\n />\n )\n}\n\nexport function AlignCenterGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="TextAlignCenter"\n tabler="IconAlignCenter"\n hugeicons="TextAlignCenterIcon"\n phosphor="TextAlignCenterIcon"\n remixicon="RiAlignCenter"\n className={className}\n style={style}\n />\n )\n}\n\nexport function AlignRightGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="TextAlignEnd"\n tabler="IconAlignRight"\n hugeicons="TextAlignRight01Icon"\n phosphor="TextAlignRightIcon"\n remixicon="RiAlignRight"\n className={className}\n style={style}\n />\n )\n}\n\nexport function AlignTopGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="ArrowUpToLine"\n tabler="IconAlignBoxTopCenter"\n hugeicons="AlignBoxTopCenterIcon"\n phosphor="AlignTopIcon"\n remixicon="RiAlignTop"\n className={className}\n style={style}\n />\n )\n}\n\nexport function AlignMiddleGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="AlignVerticalJustifyCenter"\n tabler="IconAlignBoxCenterMiddle"\n hugeicons="AlignBoxMiddleCenterIcon"\n phosphor="AlignCenterVerticalIcon"\n remixicon="RiAlignVertically"\n className={className}\n style={style}\n />\n )\n}\n\nexport function AlignBottomGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="ArrowDownToLine"\n tabler="IconAlignBoxBottomCenter"\n hugeicons="AlignBoxBottomCenterIcon"\n phosphor="AlignBottomIcon"\n remixicon="RiAlignBottom"\n className={className}\n style={style}\n />\n )\n}\n\nexport function FlagGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Flag"\n tabler="IconFlag"\n hugeicons="Flag01Icon"\n phosphor="FlagIcon"\n remixicon="RiFlagLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ClipboardGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Clipboard"\n tabler="IconClipboard"\n hugeicons="ClipboardIcon"\n phosphor="ClipboardIcon"\n remixicon="RiClipboardLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function KeyGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Key"\n tabler="IconKey"\n hugeicons="Key01Icon"\n phosphor="KeyIcon"\n remixicon="RiKey2Line"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ExternalLinkGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="ExternalLink"\n tabler="IconExternalLink"\n hugeicons="ExternalLinkIcon"\n phosphor="ArrowSquareOutIcon"\n remixicon="RiExternalLinkLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function MoveGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Move"\n tabler="IconArrowsMove"\n hugeicons="MoveIcon"\n phosphor="ArrowsOutCardinalIcon"\n remixicon="RiDragMove2Line"\n className={className}\n style={style}\n />\n )\n}\n\nexport function AlertGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="TriangleAlert"\n tabler="IconAlertTriangle"\n hugeicons="Alert01Icon"\n phosphor="WarningIcon"\n remixicon="RiAlertLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ArrowUpGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="ArrowUp"\n tabler="IconArrowUp"\n hugeicons="ArrowUp02Icon"\n phosphor="ArrowUpIcon"\n remixicon="RiArrowUpLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function ArrowDownGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="ArrowDown"\n tabler="IconArrowDown"\n hugeicons="ArrowDown02Icon"\n phosphor="ArrowDownIcon"\n remixicon="RiArrowDownLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function EditGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Pencil"\n tabler="IconEdit"\n hugeicons="PencilEdit01Icon"\n phosphor="PencilSimpleIcon"\n remixicon="RiEditLine"\n className={className}\n style={style}\n />\n )\n}\n\nexport function SparklesGlyph({ className, style }: PdfEditorGlyphProps) {\n return (\n <IconPlaceholder\n lucide="Sparkles"\n tabler="IconSparkles"\n hugeicons="SparklesIcon"\n phosphor="SparkleIcon"\n remixicon="RiSparklingLine"\n className={className}\n style={style}\n />\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Tool catalogs */\n/* -------------------------------------------------------------------------- */\n\nexport type PdfEditorToolDefinition = {\n /** EmbedPDF annotation tool id. */\n id: string\n label: string\n glyph: PdfEditorGlyph\n /** Short hint shown in the tooltip. */\n hint?: string\n}\n\nexport type PdfEditorToolGroup = {\n id: string\n label: string\n tools: PdfEditorToolDefinition[]\n}\n\nexport const PDF_EDITOR_ANNOTATION_TOOL_GROUPS: PdfEditorToolGroup[] = [\n {\n id: "markup",\n label: "Text markup",\n tools: [\n {\n id: "highlight",\n label: "Highlight",\n glyph: HighlighterGlyph,\n hint: "Select text to highlight",\n },\n {\n id: "underline",\n label: "Underline",\n glyph: UnderlineGlyph,\n hint: "Select text to underline",\n },\n {\n id: "strikeout",\n label: "Strikethrough",\n glyph: StrikethroughGlyph,\n hint: "Select text to strike through",\n },\n {\n id: "squiggly",\n label: "Squiggly",\n glyph: SquigglyGlyph,\n hint: "Select text for a squiggly underline",\n },\n ],\n },\n {\n id: "draw",\n label: "Draw",\n tools: [\n {\n id: "ink",\n label: "Pen",\n glyph: PenGlyph,\n hint: "Draw freehand",\n },\n {\n id: "inkHighlighter",\n label: "Highlighter pen",\n glyph: BrushGlyph,\n hint: "Draw a translucent highlighter stroke",\n },\n ],\n },\n {\n id: "text",\n label: "Text",\n tools: [\n {\n id: "freeText",\n label: "Text box",\n glyph: TextGlyph,\n hint: "Click or drag to add text",\n },\n {\n id: "freeTextCallout",\n label: "Callout",\n glyph: CalloutGlyph,\n hint: "Drag to add a callout with a leader line",\n },\n {\n id: "textComment",\n label: "Sticky note",\n glyph: StickyNoteGlyph,\n hint: "Click to add a note",\n },\n ],\n },\n {\n id: "shapes",\n label: "Shapes",\n tools: [\n { id: "square", label: "Rectangle", glyph: SquareGlyph },\n { id: "circle", label: "Ellipse", glyph: CircleGlyph },\n { id: "line", label: "Line", glyph: LineGlyph },\n { id: "lineArrow", label: "Arrow", glyph: ArrowGlyph },\n {\n id: "polyline",\n label: "Polyline",\n glyph: PolylineGlyph,\n hint: "Click to add points, double-click to finish",\n },\n {\n id: "polygon",\n label: "Polygon",\n glyph: PolygonGlyph,\n hint: "Click to add points, double-click to finish",\n },\n ],\n },\n {\n id: "insert",\n label: "Insert",\n tools: [\n {\n id: "stamp",\n label: "Image",\n glyph: ImageGlyph,\n hint: "Click the page to place an image",\n },\n {\n id: "link",\n label: "Link area",\n glyph: LinkGlyph,\n hint: "Drag to add a link rectangle",\n },\n {\n id: "insertText",\n label: "Insert text mark",\n glyph: InsertTextGlyph,\n hint: "Select text to mark an insertion point",\n },\n {\n id: "replaceText",\n label: "Replace text mark",\n glyph: ReplaceTextGlyph,\n hint: "Select text to mark it for replacement",\n },\n ],\n },\n]\n\nexport const PDF_EDITOR_ANNOTATION_TOOLS: PdfEditorToolDefinition[] =\n PDF_EDITOR_ANNOTATION_TOOL_GROUPS.flatMap((group) => group.tools)\n\nexport const PDF_EDITOR_FORM_TOOLS: PdfEditorToolDefinition[] = [\n {\n id: "formTextField",\n label: "Text field",\n glyph: TextFieldGlyph,\n hint: "Click or drag to add a text field",\n },\n {\n id: "formCheckbox",\n label: "Checkbox",\n glyph: CheckboxGlyph,\n hint: "Click to add a checkbox",\n },\n {\n id: "formRadioButton",\n label: "Radio button",\n glyph: RadioGlyph,\n hint: "Click to add a radio button",\n },\n {\n id: "formCombobox",\n label: "Dropdown",\n glyph: ComboboxGlyph,\n hint: "Click or drag to add a dropdown",\n },\n {\n id: "formListbox",\n label: "List box",\n glyph: ListboxGlyph,\n hint: "Click or drag to add a list box",\n },\n]\n\nexport const PDF_EDITOR_MODE_OPTIONS: Array<{\n id: PdfEditorMode\n label: string\n glyph: PdfEditorGlyph\n feature: keyof PdfEditorFeatureFlags | null\n}> = [\n { id: "view", label: "View", glyph: EyeGlyph, feature: null },\n { id: "annotate", label: "Annotate", glyph: PenGlyph, feature: "annotate" },\n { id: "sign", label: "Sign", glyph: SignatureGlyph, feature: "sign" },\n { id: "forms", label: "Forms", glyph: TextFieldGlyph, feature: "forms" },\n { id: "redact", label: "Redact", glyph: EyeOffGlyph, feature: "redact" },\n]\n\nexport type PdfEditorAnnotationMeta = {\n label: string\n glyph: PdfEditorGlyph\n /** The most representative color of the annotation, if any. */\n color?: string\n}\n\nexport function getAnnotationColor(\n annotation: PdfAnnotationObject\n): string | undefined {\n const record = annotation as unknown as Record<string, unknown>\n const candidates = [record.strokeColor, record.fontColor, record.color]\n\n for (const candidate of candidates) {\n if (typeof candidate === "string" && candidate.trim()) return candidate\n }\n\n return undefined\n}\n\nexport function getAnnotationMeta(\n annotation: PdfAnnotationObject\n): PdfEditorAnnotationMeta {\n const color = getAnnotationColor(annotation)\n const intent = annotation.intent ?? ""\n\n switch (annotation.type) {\n case PdfAnnotationSubtype.HIGHLIGHT:\n return { label: "Highlight", glyph: HighlighterGlyph, color }\n case PdfAnnotationSubtype.UNDERLINE:\n return { label: "Underline", glyph: UnderlineGlyph, color }\n case PdfAnnotationSubtype.STRIKEOUT:\n return intent === "StrikeOutTextReplace"\n ? { label: "Replace text", glyph: ReplaceTextGlyph, color }\n : { label: "Strikethrough", glyph: StrikethroughGlyph, color }\n case PdfAnnotationSubtype.SQUIGGLY:\n return { label: "Squiggly", glyph: SquigglyGlyph, color }\n case PdfAnnotationSubtype.INK:\n return intent === "InkHighlight"\n ? { label: "Highlighter pen", glyph: BrushGlyph, color }\n : { label: "Ink", glyph: PenGlyph, color }\n case PdfAnnotationSubtype.SQUARE:\n return { label: "Rectangle", glyph: SquareGlyph, color }\n case PdfAnnotationSubtype.CIRCLE:\n return { label: "Ellipse", glyph: CircleGlyph, color }\n case PdfAnnotationSubtype.LINE:\n return intent === "LineArrow"\n ? { label: "Arrow", glyph: ArrowGlyph, color }\n : { label: "Line", glyph: LineGlyph, color }\n case PdfAnnotationSubtype.POLYLINE:\n return { label: "Polyline", glyph: PolylineGlyph, color }\n case PdfAnnotationSubtype.POLYGON:\n return { label: "Polygon", glyph: PolygonGlyph, color }\n case PdfAnnotationSubtype.FREETEXT:\n return intent === "FreeTextCallout"\n ? { label: "Callout", glyph: CalloutGlyph, color }\n : { label: "Text box", glyph: TextGlyph, color }\n case PdfAnnotationSubtype.TEXT:\n return { label: "Note", glyph: StickyNoteGlyph, color }\n case PdfAnnotationSubtype.STAMP:\n return { label: "Stamp", glyph: StampGlyph, color }\n case PdfAnnotationSubtype.LINK:\n return { label: "Link", glyph: LinkGlyph, color }\n case PdfAnnotationSubtype.CARET:\n return { label: "Insert text", glyph: InsertTextGlyph, color }\n case PdfAnnotationSubtype.REDACT:\n return { label: "Redaction", glyph: EyeOffGlyph, color }\n case PdfAnnotationSubtype.WIDGET:\n return { label: "Form field", glyph: TextFieldGlyph, color }\n case PdfAnnotationSubtype.FILEATTACHMENT:\n return { label: "Attachment", glyph: PaperclipGlyph, color }\n default:\n return { label: "Annotation", glyph: FlagGlyph, color }\n }\n}\n\n/* -------------------------------------------------------------------------- */\n/* Helpers */\n/* -------------------------------------------------------------------------- */\n\nexport function clamp(value: number, min: number, max: number) {\n return Math.min(max, Math.max(min, value))\n}\n\nexport function ensurePdfExtension(fileName: string) {\n return fileName.toLowerCase().endsWith(".pdf") ? fileName : `${fileName}.pdf`\n}\n\nexport function getPdfFileName(fileName: string | undefined, src?: string) {\n if (fileName?.trim()) return ensurePdfExtension(fileName.trim())\n\n if (src && !src.startsWith("blob:") && !src.startsWith("data:")) {\n const pathname = src.split(/[?#]/)[0] ?? ""\n const rawName = pathname.split("/").pop() || ""\n\n if (rawName) {\n try {\n return ensurePdfExtension(decodeURIComponent(rawName))\n } catch {\n return ensurePdfExtension(rawName)\n }\n }\n }\n\n return "document.pdf"\n}\n\nexport function withFileNameSuffix(fileName: string, suffix: string) {\n return ensurePdfExtension(fileName.replace(/\\.pdf$/i, "") + suffix)\n}\n\nexport function downloadBlob(blob: Blob, fileName: string) {\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n\n anchor.href = url\n anchor.download = fileName\n anchor.rel = "noopener"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nexport function downloadArrayBuffer(\n buffer: ArrayBuffer | Uint8Array,\n fileName: string,\n type = "application/pdf"\n) {\n const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer)\n const copy = new ArrayBuffer(bytes.byteLength)\n new Uint8Array(copy).set(bytes)\n\n downloadBlob(new Blob([copy], { type }), fileName)\n}\n\nexport function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {\n const copy = new ArrayBuffer(bytes.byteLength)\n new Uint8Array(copy).set(bytes)\n return copy\n}\n\nexport function readFileAsArrayBuffer(file: Blob) {\n return file.arrayBuffer()\n}\n\nexport function formatBytes(bytes: number | undefined) {\n if (bytes === undefined || Number.isNaN(bytes)) return "—"\n if (bytes < 1024) return `${bytes} B`\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`\n}\n\nexport function formatDateTime(date: Date | undefined | null) {\n if (!date) return "—"\n\n const value = date instanceof Date ? date : new Date(date)\n\n if (Number.isNaN(value.getTime())) return "—"\n\n return value.toLocaleString(undefined, {\n dateStyle: "medium",\n timeStyle: "short",\n })\n}\n\nexport function formatRelativeDate(date: Date | undefined | null) {\n if (!date) return ""\n\n const value = date instanceof Date ? date : new Date(date)\n\n if (Number.isNaN(value.getTime())) return ""\n\n const diff = Date.now() - value.getTime()\n const minutes = Math.round(diff / 60000)\n\n if (minutes < 1) return "just now"\n if (minutes < 60) return `${minutes}m ago`\n\n const hours = Math.round(minutes / 60)\n\n if (hours < 24) return `${hours}h ago`\n\n return value.toLocaleDateString(undefined, {\n month: "short",\n day: "numeric",\n })\n}\n\nexport function toNormalizedRect(\n rect: Rect,\n pageSize: Size\n): PdfEditorNormalizedRect {\n const width = pageSize.width || 1\n const height = pageSize.height || 1\n\n return {\n top: (rect.origin.y / height) * 100,\n left: (rect.origin.x / width) * 100,\n width: (rect.size.width / width) * 100,\n height: (rect.size.height / height) * 100,\n }\n}\n\nexport function isTypingTarget(target: EventTarget | null) {\n if (!(target instanceof HTMLElement)) return false\n if (target.isContentEditable) return true\n\n return Boolean(\n target.closest(\n "input, textarea, select, [contenteditable=\'true\'], [contenteditable=\'\']"\n )\n )\n}\n\nexport function isMacPlatform() {\n if (typeof navigator === "undefined") return false\n\n return /mac|iphone|ipad|ipod/i.test(navigator.platform)\n}\n\nexport function formatShortcut(shortcut: string) {\n const mac = isMacPlatform()\n\n return shortcut\n .replace(/mod/gi, mac ? "⌘" : "Ctrl")\n .replace(/shift/gi, mac ? "⇧" : "Shift")\n .replace(/alt/gi, mac ? "⌥" : "Alt")\n}\n\nexport function uniqueName(base: string, existing: Iterable<string>) {\n const taken = new Set(existing)\n\n if (!taken.has(base)) return base\n\n let index = 2\n\n while (taken.has(`${base} ${index}`)) index += 1\n\n return `${base} ${index}`\n}\n\nexport function noop() {}\n\n/* -------------------------------------------------------------------------- */\n/* Small UI primitives shared by the editor files */\n/* -------------------------------------------------------------------------- */\n\nexport function PdfEditorTooltip({\n label,\n shortcut,\n children,\n}: {\n label: React.ReactNode\n shortcut?: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">\n <span className="inline-flex items-center gap-2">\n {label}\n {shortcut ? (\n <Kbd className="h-4 min-w-4 px-1 text-[10px]">\n {formatShortcut(shortcut)}\n </Kbd>\n ) : null}\n </span>\n </TooltipContent>\n </Tooltip>\n )\n}\n\nexport function PdfEditorToolButton({\n label,\n shortcut,\n active = false,\n className,\n children,\n size = "icon-sm",\n variant = "ghost",\n ...props\n}: Omit<ButtonProps, "variant" | "size" | "children"> & {\n label: string\n shortcut?: string\n active?: boolean\n size?: ButtonProps["size"]\n variant?: ButtonProps["variant"]\n children: React.ReactNode\n}) {\n return (\n <PdfEditorTooltip label={label} shortcut={shortcut}>\n <Button\n type="button"\n variant={variant}\n size={size}\n aria-label={label}\n aria-pressed={active}\n data-active={active ? "" : undefined}\n className={cn(\n active &&\n "bg-accent text-accent-foreground ring-1 ring-ring/40 ring-inset",\n className\n )}\n {...props}\n >\n {children}\n </Button>\n </PdfEditorTooltip>\n )\n}\n\nexport function PdfEditorToolbarSeparator({\n className,\n}: {\n className?: string\n}) {\n return (\n <div\n aria-hidden="true"\n className={cn("mx-1 h-4 w-px shrink-0 self-center bg-border", className)}\n />\n )\n}\n\nexport function PdfEditorPanelHeader({\n title,\n description,\n actions,\n onClose,\n}: {\n title: React.ReactNode\n description?: React.ReactNode\n actions?: React.ReactNode\n onClose?: () => void\n}) {\n return (\n <div className="flex shrink-0 items-start justify-between gap-2 border-b px-3 py-2.5">\n <div className="min-w-0">\n <div className="truncate text-sm font-medium text-foreground">\n {title}\n </div>\n {description ? (\n <div className="mt-0.5 text-xs text-muted-foreground">\n {description}\n </div>\n ) : null}\n </div>\n <div className="flex shrink-0 items-center gap-1">\n {actions}\n {onClose ? (\n <PdfEditorToolButton\n label="Close panel"\n size="icon-xs"\n onClick={onClose}\n >\n <CloseGlyph className="size-3.5" />\n </PdfEditorToolButton>\n ) : null}\n </div>\n </div>\n )\n}\n\nexport function PdfEditorEmptyState({\n glyph: Glyph,\n title,\n description,\n action,\n className,\n}: {\n glyph?: PdfEditorGlyph\n title: React.ReactNode\n description?: React.ReactNode\n action?: React.ReactNode\n className?: string\n}) {\n return (\n <div\n className={cn(\n "flex flex-col items-center gap-2 px-4 py-10 text-center",\n className\n )}\n >\n {Glyph ? (\n <div className="grid size-10 place-items-center rounded-full bg-muted text-muted-foreground">\n <Glyph className="size-5" />\n </div>\n ) : null}\n <div className="text-sm font-medium text-foreground">{title}</div>\n {description ? (\n <div className="max-w-56 text-xs text-muted-foreground">\n {description}\n </div>\n ) : null}\n {action ? <div className="mt-2">{action}</div> : null}\n </div>\n )\n}\n\nexport function PdfEditorSection({\n title,\n actions,\n children,\n className,\n}: {\n title?: React.ReactNode\n actions?: React.ReactNode\n children: React.ReactNode\n className?: string\n}) {\n return (\n <section className={cn("space-y-2", className)}>\n {title || actions ? (\n <div className="flex items-center justify-between gap-2">\n {title ? (\n <div className="text-xs font-medium text-muted-foreground">\n {title}\n </div>\n ) : (\n <span />\n )}\n {actions}\n </div>\n ) : null}\n {children}\n </section>\n )\n}\n\nexport function PdfEditorFieldLabel({\n children,\n htmlFor,\n className,\n}: {\n children: React.ReactNode\n htmlFor?: string\n className?: string\n}) {\n return (\n <label\n htmlFor={htmlFor}\n className={cn("block text-xs font-medium text-foreground", className)}\n >\n {children}\n </label>\n )\n}\n\nexport function PdfEditorCheckbox({\n checked,\n disabled,\n label,\n description,\n onCheckedChange,\n className,\n}: {\n checked: boolean\n disabled?: boolean\n label: React.ReactNode\n description?: React.ReactNode\n onCheckedChange: (checked: boolean) => void\n className?: string\n}) {\n return (\n <button\n type="button"\n role="checkbox"\n aria-checked={checked}\n disabled={disabled}\n onClick={() => onCheckedChange(!checked)}\n className={cn(\n "flex w-full items-start gap-2 rounded-md px-1 py-1 text-left text-sm outline-none hover:bg-accent/60 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",\n className\n )}\n >\n <span\n aria-hidden="true"\n className={cn(\n "mt-0.5 grid size-4 shrink-0 place-items-center rounded border transition-colors",\n checked\n ? "border-primary bg-primary text-primary-foreground"\n : "border-input bg-background"\n )}\n >\n {checked ? <CheckGlyph className="size-3" /> : null}\n </span>\n <span className="min-w-0">\n <span className="block leading-4">{label}</span>\n {description ? (\n <span className="block text-xs text-muted-foreground">\n {description}\n </span>\n ) : null}\n </span>\n </button>\n )\n}\n\nexport function PdfEditorSwatch({\n color,\n active,\n label,\n onClick,\n size = "md",\n}: {\n color: string\n active?: boolean\n label?: string\n onClick?: () => void\n size?: "sm" | "md"\n}) {\n const isTransparent = color === "transparent"\n\n return (\n <PdfEditorTooltip label={label ?? (isTransparent ? "No fill" : color)}>\n <button\n type="button"\n aria-label={label ?? (isTransparent ? "No fill" : color)}\n aria-pressed={active}\n onClick={onClick}\n className={cn(\n "relative shrink-0 rounded-full border border-black/10 transition-transform outline-none focus-visible:ring-2 focus-visible:ring-ring dark:border-white/15",\n size === "sm" ? "size-4" : "size-5",\n active && "ring-2 ring-ring ring-offset-2 ring-offset-background"\n )}\n style={\n isTransparent\n ? {\n backgroundImage:\n "linear-gradient(45deg, transparent 45%, #ef4444 45%, #ef4444 55%, transparent 55%)",\n backgroundColor: "#fff",\n }\n : { backgroundColor: color }\n }\n />\n </PdfEditorTooltip>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Scroll area with a resolvable viewport (mirrors the PDF viewer) */\n/* -------------------------------------------------------------------------- */\n\nexport type PdfEditorScrollAreaViewportResolver = (\n container: HTMLDivElement\n) => HTMLDivElement | null\n\nconst DEFAULT_SCROLL_AREA_VIEWPORT_SELECTOR =\n \'[data-slot="scroll-area-viewport"]\'\n\nexport function resolveDefaultScrollAreaViewport(container: HTMLDivElement) {\n return container.querySelector<HTMLDivElement>(\n DEFAULT_SCROLL_AREA_VIEWPORT_SELECTOR\n )\n}\n\nexport const PdfEditorScrollAreaResolverContext =\n React.createContext<PdfEditorScrollAreaViewportResolver>(\n resolveDefaultScrollAreaViewport\n )\n\nfunction setRefValue<T>(ref: React.Ref<T> | undefined, value: T | null) {\n if (!ref) return\n\n if (typeof ref === "function") {\n ref(value)\n } else {\n ref.current = value\n }\n}\n\nexport function PdfEditorScrollArea({\n children,\n className,\n orientation = "vertical",\n scrollbarGutter = true,\n viewportClassName,\n viewportProps,\n viewportRef,\n}: {\n children: React.ReactNode\n className?: string\n orientation?: "vertical" | "horizontal" | "both"\n scrollbarGutter?: boolean\n viewportClassName?: string\n viewportProps?: React.HTMLAttributes<HTMLDivElement>\n viewportRef?: React.Ref<HTMLDivElement>\n}) {\n const resolveViewport = React.useContext(PdfEditorScrollAreaResolverContext)\n const containerRef = React.useRef<HTMLDivElement | null>(null)\n const { className: viewportPropsClassName, ...resolvedViewportProps } =\n viewportProps ?? {}\n\n const setViewportRef = React.useCallback(\n (viewport: HTMLDivElement | null) => {\n setRefValue(viewportRef, viewport)\n },\n [viewportRef]\n )\n\n React.useLayoutEffect(() => {\n const container = containerRef.current\n if (!container) return\n\n const viewport = resolveViewport(container)\n\n if (!viewport) {\n console.error(\n `PDFEditor could not resolve the scroll viewport. Add ${DEFAULT_SCROLL_AREA_VIEWPORT_SELECTOR} to your ScrollArea viewport or pass resolveScrollAreaViewport.`\n )\n return\n }\n\n setViewportRef(viewport)\n\n return () => setViewportRef(null)\n }, [resolveViewport, setViewportRef])\n\n return (\n <div\n ref={containerRef}\n data-slot="pdf-editor-scroll-area"\n className={cn("size-full min-h-0", className)}\n >\n <ScrollArea\n className="size-full min-h-0"\n orientation={orientation}\n scrollbarGutter={scrollbarGutter}\n >\n <div\n {...resolvedViewportProps}\n data-slot="pdf-editor-scroll-content"\n className={cn(\n "min-h-full",\n viewportPropsClassName,\n viewportClassName\n )}\n >\n {children}\n </div>\n </ScrollArea>\n </div>\n )\n}\n',+ },+ {+ fileName: "components/extend/pdf-editor-dialogs.tsx",+ code: '"use client"\n\nimport * as React from "react"\nimport type { DocumentState } from "@embedpdf/core"\nimport {\n useDocumentPermissions,\n useDocumentState,\n useRegistry,\n} from "@embedpdf/core/react"\nimport {\n ignore,\n PdfActionType,\n PdfAnnotationBorderStyle,\n PdfAnnotationReplyType,\n PdfAnnotationSubtype,\n PdfBlendMode,\n PdfErrorCode,\n PdfPermissionFlag,\n PdfZoomMode,\n uuidV4,\n type PdfLinkAnnoObject,\n type PdfLinkTarget,\n type PdfMetadataObject,\n type PdfPrintOptions,\n} from "@embedpdf/models"\nimport { useAnnotationCapability } from "@embedpdf/plugin-annotation/react"\nimport { useCapture } from "@embedpdf/plugin-capture/react"\nimport { useDocumentManagerCapability } from "@embedpdf/plugin-document-manager/react"\nimport { usePrint } from "@embedpdf/plugin-print/react"\nimport { useScroll } from "@embedpdf/plugin-scroll/react"\nimport { useSelectionCapability } from "@embedpdf/plugin-selection/react"\nimport {\n SignatureDrawPad,\n SignatureMode,\n SignatureTypePad,\n useSignatureCapability,\n useSignatureUpload,\n type SignatureDrawPadHandle,\n type SignatureFieldDefinition,\n type SignatureTypePadHandle,\n} from "@embedpdf/plugin-signature/react"\n\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 Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogPanel,\n DialogTitle,\n} from "@/components/ui/dialog"\nimport { Input } from "@/components/ui/input"\nimport { Kbd } from "@/components/ui/kbd"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n CloseGlyph,\n CopyGlyph,\n downloadBlob,\n DownloadGlyph,\n formatBytes,\n formatDateTime,\n formatShortcut,\n KeyGlyph,\n LockGlyph,\n PDF_EDITOR_SIGNATURE_FONTS,\n PdfEditorCheckbox,\n PdfEditorFieldLabel,\n PdfEditorSection,\n PdfEditorSwatch,\n PdfEditorToolButton,\n ShieldGlyph,\n UnlockGlyph,\n usePdfEditor,\n} from "@/components/extend/pdf-editor-shared"\n\n/* -------------------------------------------------------------------------- */\n/* Confirm */\n/* -------------------------------------------------------------------------- */\n\nexport function PdfEditorConfirmDialog({\n open,\n onOpenChange,\n title,\n description,\n confirmLabel = "Confirm",\n destructive = false,\n onConfirm,\n}: {\n open: boolean\n onOpenChange: (open: boolean) => void\n title: string\n description?: string\n confirmLabel?: string\n destructive?: boolean\n onConfirm: () => void\n}) {\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className="max-w-md">\n <DialogHeader>\n <DialogTitle>{title}</DialogTitle>\n {description ? (\n <DialogDescription>{description}</DialogDescription>\n ) : null}\n </DialogHeader>\n <DialogFooter variant="bare">\n <Button\n type="button"\n variant="outline"\n onClick={() => onOpenChange(false)}\n >\n Cancel\n </Button>\n <Button\n type="button"\n variant={destructive ? "destructive" : "default"}\n onClick={() => {\n onConfirm()\n onOpenChange(false)\n }}\n >\n {confirmLabel}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Print */\n/* -------------------------------------------------------------------------- */\n\ntype PrintPageSelection = "all" | "current" | "custom"\n\nexport function PdfEditorPrintDialog({\n documentId,\n open,\n onOpenChange,\n}: {\n documentId: string\n open: boolean\n onOpenChange: (open: boolean) => void\n}) {\n const { provides: print } = usePrint(documentId)\n const { state: scrollState } = useScroll(documentId)\n const { notify } = usePdfEditor()\n const [selection, setSelection] = React.useState<PrintPageSelection>("all")\n const [customPages, setCustomPages] = React.useState("")\n const [includeAnnotations, setIncludeAnnotations] = React.useState(true)\n const [isPrinting, setIsPrinting] = React.useState(false)\n const [error, setError] = React.useState<string | null>(null)\n\n React.useEffect(() => {\n if (open) return\n\n setSelection("all")\n setCustomPages("")\n setIncludeAnnotations(true)\n setIsPrinting(false)\n setError(null)\n }, [open])\n\n const canSubmit =\n !isPrinting && (selection !== "custom" || customPages.trim().length > 0)\n\n const handlePrint = () => {\n if (!print || !canSubmit) return\n\n const options: PdfPrintOptions = {\n includeAnnotations,\n pageRange:\n selection === "current"\n ? String(scrollState.currentPage)\n : selection === "custom"\n ? customPages.trim()\n : undefined,\n }\n\n setIsPrinting(true)\n setError(null)\n\n print.print(options).wait(\n () => {\n setIsPrinting(false)\n onOpenChange(false)\n },\n (failure) => {\n setIsPrinting(false)\n const message =\n failure?.reason?.message ?? "The document could not be printed."\n setError(message)\n notify(message, "error")\n }\n )\n }\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className="max-w-md">\n <DialogHeader>\n <DialogTitle>Print</DialogTitle>\n <DialogDescription>\n Prepares a print-ready copy and opens the browser print dialog.\n </DialogDescription>\n </DialogHeader>\n <DialogPanel className="space-y-5">\n <PdfEditorSection title="Pages">\n <div className="space-y-1">\n <PdfEditorCheckbox\n checked={selection === "all"}\n onCheckedChange={() => setSelection("all")}\n label="All pages"\n />\n <PdfEditorCheckbox\n checked={selection === "current"}\n onCheckedChange={() => setSelection("current")}\n label={`Current page (${scrollState.currentPage || 1})`}\n />\n <PdfEditorCheckbox\n checked={selection === "custom"}\n onCheckedChange={() => setSelection("custom")}\n label="Page range"\n />\n </div>\n <Input\n placeholder="e.g. 1-3, 5, 8-10"\n value={customPages}\n disabled={selection !== "custom"}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) =>\n setCustomPages(event.target.value)\n }\n onFocus={() => setSelection("custom")}\n />\n <div className="text-xs text-muted-foreground">\n {scrollState.totalPages} pages in this document.\n </div>\n </PdfEditorSection>\n <PdfEditorSection title="Options">\n <PdfEditorCheckbox\n checked={includeAnnotations}\n onCheckedChange={setIncludeAnnotations}\n label="Include annotations and form values"\n />\n </PdfEditorSection>\n {error ? (\n <div className="text-xs text-destructive">{error}</div>\n ) : null}\n </DialogPanel>\n <DialogFooter>\n <Button\n type="button"\n variant="outline"\n disabled={isPrinting}\n onClick={() => onOpenChange(false)}\n >\n Cancel\n </Button>\n <Button\n type="button"\n loading={isPrinting}\n disabled={!canSubmit || !print}\n onClick={handlePrint}\n >\n Print\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Capture */\n/* -------------------------------------------------------------------------- */\n\ntype CaptureResult = {\n pageIndex: number\n blob: Blob\n imageType: string\n url: string\n}\n\nexport function PdfEditorCaptureDialog({ documentId }: { documentId: string }) {\n const { provides: capture } = useCapture(documentId)\n const { fileName, notify, onCapture } = usePdfEditor()\n const [result, setResult] = React.useState<CaptureResult | null>(null)\n const onCaptureRef = React.useRef(onCapture)\n\n React.useEffect(() => {\n onCaptureRef.current = onCapture\n })\n\n React.useEffect(() => {\n if (!capture) return\n\n return capture.onCaptureArea((event) => {\n onCaptureRef.current?.(event)\n setResult((previous) => {\n if (previous) URL.revokeObjectURL(previous.url)\n\n return {\n pageIndex: event.pageIndex,\n blob: event.blob,\n imageType: event.imageType,\n url: URL.createObjectURL(event.blob),\n }\n })\n })\n }, [capture])\n\n React.useEffect(\n () => () => {\n if (result) URL.revokeObjectURL(result.url)\n },\n [result]\n )\n\n const close = () => setResult(null)\n const extension = result?.imageType.split("/")[1] ?? "png"\n const captureFileName = `${fileName.replace(/\\.pdf$/i, "")}-page-${(result?.pageIndex ?? 0) + 1}.${extension}`\n const canCopy =\n typeof navigator !== "undefined" &&\n typeof window !== "undefined" &&\n "ClipboardItem" in window &&\n Boolean(navigator.clipboard?.write)\n\n return (\n <Dialog\n open={result !== null}\n onOpenChange={(open) => {\n if (!open) close()\n }}\n >\n <DialogContent className="max-w-2xl">\n <DialogHeader>\n <DialogTitle>Captured area</DialogTitle>\n <DialogDescription>\n Page {(result?.pageIndex ?? 0) + 1} ·{" "}\n {formatBytes(result?.blob.size)}\n </DialogDescription>\n </DialogHeader>\n <DialogPanel>\n <div className="grid place-items-center rounded-lg border bg-muted/40 p-3">\n {result ? (\n <img\n src={result.url}\n alt={`Captured area from page ${result.pageIndex + 1}`}\n className="max-h-[52vh] max-w-full rounded-md shadow-sm"\n />\n ) : null}\n </div>\n </DialogPanel>\n <DialogFooter>\n {canCopy ? (\n <Button\n type="button"\n variant="outline"\n onClick={async () => {\n if (!result) return\n\n try {\n await navigator.clipboard.write([\n new ClipboardItem({ [result.imageType]: result.blob }),\n ])\n notify("Image copied to the clipboard.", "success")\n } catch {\n notify("The image could not be copied.", "error")\n }\n }}\n >\n <CopyGlyph className="size-4" />\n Copy image\n </Button>\n ) : null}\n <Button\n type="button"\n onClick={() => {\n if (!result) return\n\n downloadBlob(result.blob, captureFileName)\n close()\n }}\n >\n <DownloadGlyph className="size-4" />\n Download\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Security */\n/* -------------------------------------------------------------------------- */\n\nconst PERMISSION_OPTIONS: Array<{\n flag: PdfPermissionFlag\n label: string\n description: string\n}> = [\n {\n flag: PdfPermissionFlag.Print,\n label: "Print",\n description: "Allow printing, possibly at reduced quality.",\n },\n {\n flag: PdfPermissionFlag.PrintHighQuality,\n label: "Print in high quality",\n description: "Allow full-resolution printing.",\n },\n {\n flag: PdfPermissionFlag.ModifyContents,\n label: "Modify contents",\n description: "Allow editing the page content.",\n },\n {\n flag: PdfPermissionFlag.CopyContents,\n label: "Copy text and images",\n description: "Allow copying and extracting content.",\n },\n {\n flag: PdfPermissionFlag.ModifyAnnotations,\n label: "Annotate",\n description: "Allow adding and changing annotations.",\n },\n {\n flag: PdfPermissionFlag.FillForms,\n label: "Fill forms",\n description: "Allow filling in existing form fields.",\n },\n {\n flag: PdfPermissionFlag.ExtractForAccessibility,\n label: "Extract for accessibility",\n description: "Allow assistive technologies to read the content.",\n },\n {\n flag: PdfPermissionFlag.AssembleDocument,\n label: "Assemble pages",\n description: "Allow inserting, rotating, and deleting pages.",\n },\n]\n\nfunction PasswordInput({\n id,\n value,\n onChange,\n placeholder,\n autoFocus,\n onEnter,\n}: {\n id?: string\n value: string\n onChange: (value: string) => void\n placeholder?: string\n autoFocus?: boolean\n onEnter?: () => void\n}) {\n return (\n <Input\n id={id}\n type="password"\n autoComplete="off"\n value={value}\n placeholder={placeholder}\n autoFocus={autoFocus}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) =>\n onChange(event.target.value)\n }\n onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key === "Enter") onEnter?.()\n }}\n />\n )\n}\n\nexport function PdfEditorSecurityDialog({\n documentId,\n open,\n onOpenChange,\n}: {\n documentId: string\n open: boolean\n onOpenChange: (open: boolean) => void\n}) {\n const { provides: documentManager } = useDocumentManagerCapability()\n const documentState = useDocumentState(documentId)\n const permissions = useDocumentPermissions(documentId)\n const { notify } = usePdfEditor()\n const document = documentState?.document ?? null\n const isEncrypted = document?.isEncrypted ?? false\n const isOwnerUnlocked = document?.isOwnerUnlocked ?? false\n const needsOwnerUnlock = isEncrypted && !isOwnerUnlocked\n\n const [unlockPassword, setUnlockPassword] = React.useState("")\n const [isUnlocking, setIsUnlocking] = React.useState(false)\n const [requireOpenPassword, setRequireOpenPassword] = React.useState(false)\n const [openPassword, setOpenPassword] = React.useState("")\n const [confirmOpenPassword, setConfirmOpenPassword] = React.useState("")\n const [restrictPermissions, setRestrictPermissions] = React.useState(false)\n const [ownerPassword, setOwnerPassword] = React.useState("")\n const [confirmOwnerPassword, setConfirmOwnerPassword] = React.useState("")\n const [allowedFlags, setAllowedFlags] = React.useState<\n Set<PdfPermissionFlag>\n >(() => new Set(PERMISSION_OPTIONS.map((option) => option.flag)))\n const [isApplying, setIsApplying] = React.useState(false)\n const [error, setError] = React.useState<string | null>(null)\n\n React.useEffect(() => {\n if (!open) return\n\n setUnlockPassword("")\n setIsUnlocking(false)\n setRequireOpenPassword(false)\n setOpenPassword("")\n setConfirmOpenPassword("")\n setRestrictPermissions(false)\n setOwnerPassword("")\n setConfirmOwnerPassword("")\n setAllowedFlags(new Set(PERMISSION_OPTIONS.map((option) => option.flag)))\n setIsApplying(false)\n setError(null)\n }, [open])\n\n const openPasswordValid =\n !requireOpenPassword ||\n (openPassword.length > 0 && openPassword === confirmOpenPassword)\n const ownerPasswordValid =\n !restrictPermissions ||\n (ownerPassword.length > 0 && ownerPassword === confirmOwnerPassword)\n const canApply =\n !isApplying &&\n (requireOpenPassword || restrictPermissions) &&\n openPasswordValid &&\n ownerPasswordValid\n\n const handleUnlock = () => {\n if (!documentManager || !unlockPassword.trim()) return\n\n setIsUnlocking(true)\n setError(null)\n documentManager.unlockOwnerPermissions(documentId, unlockPassword).wait(\n (success) => {\n setIsUnlocking(false)\n\n if (success) {\n setUnlockPassword("")\n notify("Owner permissions unlocked.", "success")\n } else {\n setError("The owner password is incorrect.")\n }\n },\n (failure) => {\n setIsUnlocking(false)\n setError(\n failure?.reason?.message ?? "The document could not be unlocked."\n )\n }\n )\n }\n\n const handleApply = () => {\n if (!documentManager || !canApply) return\n\n let flags = PdfPermissionFlag.AllowAll as number\n\n if (restrictPermissions) {\n flags = 0\n for (const flag of allowedFlags) flags |= flag\n }\n\n const userPassword = requireOpenPassword ? openPassword : ""\n const resolvedOwnerPassword = restrictPermissions\n ? ownerPassword\n : requireOpenPassword\n ? openPassword\n : ""\n\n setIsApplying(true)\n setError(null)\n documentManager\n .setDocumentEncryption(documentId, {\n userPassword,\n ownerPassword: resolvedOwnerPassword,\n allowedFlags: flags,\n })\n .wait(\n (success) => {\n setIsApplying(false)\n\n if (success) {\n notify(\n "Protection is applied the next time you download the document.",\n "success"\n )\n onOpenChange(false)\n } else {\n setError("The protection settings could not be applied.")\n }\n },\n (failure) => {\n setIsApplying(false)\n setError(\n failure?.reason?.message ??\n "The protection settings could not be applied."\n )\n }\n )\n }\n\n const handleRemove = () => {\n if (!documentManager) return\n\n setIsApplying(true)\n setError(null)\n documentManager.removeEncryption(documentId).wait(\n (success) => {\n setIsApplying(false)\n\n if (success) {\n notify(\n "Protection is removed the next time you download the document.",\n "success"\n )\n onOpenChange(false)\n } else {\n setError("The protection could not be removed.")\n }\n },\n (failure) => {\n setIsApplying(false)\n setError(\n failure?.reason?.message ?? "The protection could not be removed."\n )\n }\n )\n }\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className="max-w-lg">\n <DialogHeader>\n <DialogTitle>Security</DialogTitle>\n <DialogDescription>\n Passwords and permissions are written into the PDF when you download\n it.\n </DialogDescription>\n </DialogHeader>\n <DialogPanel className="space-y-5">\n <PdfEditorSection title="Current status">\n <div className="flex flex-wrap items-center gap-2 text-sm">\n {isEncrypted ? (\n <Badge variant="secondary">\n <LockGlyph className="size-3" />\n Encrypted\n </Badge>\n ) : (\n <Badge variant="outline">\n <UnlockGlyph className="size-3" />\n Not encrypted\n </Badge>\n )}\n {isEncrypted ? (\n <Badge variant={isOwnerUnlocked ? "secondary" : "outline"}>\n <KeyGlyph className="size-3" />\n {isOwnerUnlocked ? "Owner unlocked" : "Owner locked"}\n </Badge>\n ) : null}\n </div>\n <div className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs text-muted-foreground">\n {PERMISSION_OPTIONS.map((option) => {\n const allowed = permissions.hasPermission(option.flag)\n\n return (\n <div key={option.flag} className="flex items-center gap-1.5">\n <span\n aria-hidden="true"\n className={cn(\n "size-1.5 rounded-full",\n allowed ? "bg-emerald-500" : "bg-destructive"\n )}\n />\n <span className={cn(!allowed && "line-through")}>\n {option.label}\n </span>\n </div>\n )\n })}\n </div>\n </PdfEditorSection>\n\n {needsOwnerUnlock ? (\n <PdfEditorSection title="Unlock owner permissions">\n <div className="text-xs text-muted-foreground">\n Enter the owner password to change protection settings.\n </div>\n <div className="flex gap-2">\n <PasswordInput\n value={unlockPassword}\n placeholder="Owner password"\n onChange={setUnlockPassword}\n onEnter={handleUnlock}\n />\n <Button\n type="button"\n variant="outline"\n loading={isUnlocking}\n disabled={!unlockPassword.trim()}\n onClick={handleUnlock}\n >\n Unlock\n </Button>\n </div>\n </PdfEditorSection>\n ) : null}\n\n <PdfEditorSection title="Open password">\n <PdfEditorCheckbox\n checked={requireOpenPassword}\n disabled={needsOwnerUnlock}\n onCheckedChange={setRequireOpenPassword}\n label="Require a password to open the document"\n />\n {requireOpenPassword ? (\n <div className="grid gap-2 sm:grid-cols-2">\n <PasswordInput\n value={openPassword}\n placeholder="Password"\n onChange={setOpenPassword}\n />\n <PasswordInput\n value={confirmOpenPassword}\n placeholder="Confirm password"\n onChange={setConfirmOpenPassword}\n />\n {!openPasswordValid && confirmOpenPassword ? (\n <div className="text-xs text-destructive sm:col-span-2">\n The passwords do not match.\n </div>\n ) : null}\n </div>\n ) : null}\n </PdfEditorSection>\n\n <PdfEditorSection title="Permissions">\n <PdfEditorCheckbox\n checked={restrictPermissions}\n disabled={needsOwnerUnlock}\n onCheckedChange={setRestrictPermissions}\n label="Restrict what readers can do"\n description="Requires an owner password to lift the restrictions later."\n />\n {restrictPermissions ? (\n <div className="space-y-3">\n <div className="grid gap-2 sm:grid-cols-2">\n <PasswordInput\n value={ownerPassword}\n placeholder="Owner password"\n onChange={setOwnerPassword}\n />\n <PasswordInput\n value={confirmOwnerPassword}\n placeholder="Confirm owner password"\n onChange={setConfirmOwnerPassword}\n />\n {!ownerPasswordValid && confirmOwnerPassword ? (\n <div className="text-xs text-destructive sm:col-span-2">\n The passwords do not match.\n </div>\n ) : null}\n </div>\n <div className="grid gap-1 sm:grid-cols-2">\n {PERMISSION_OPTIONS.map((option) => (\n <PdfEditorCheckbox\n key={option.flag}\n checked={allowedFlags.has(option.flag)}\n onCheckedChange={(checked) =>\n setAllowedFlags((previous) => {\n const next = new Set(previous)\n\n if (checked) {\n next.add(option.flag)\n } else {\n next.delete(option.flag)\n }\n\n return next\n })\n }\n label={option.label}\n description={option.description}\n />\n ))}\n </div>\n </div>\n ) : null}\n </PdfEditorSection>\n\n {error ? (\n <div className="text-xs text-destructive">{error}</div>\n ) : null}\n </DialogPanel>\n <DialogFooter>\n {isEncrypted && !needsOwnerUnlock ? (\n <Button\n type="button"\n variant="destructive-outline"\n disabled={isApplying}\n onClick={handleRemove}\n className="sm:mr-auto"\n >\n Remove protection\n </Button>\n ) : null}\n <Button\n type="button"\n variant="outline"\n disabled={isApplying}\n onClick={() => onOpenChange(false)}\n >\n Cancel\n </Button>\n <Button\n type="button"\n loading={isApplying}\n disabled={!canApply || needsOwnerUnlock}\n onClick={handleApply}\n >\n <ShieldGlyph className="size-4" />\n Apply protection\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Document properties (metadata) */\n/* -------------------------------------------------------------------------- */\n\ntype EditableMetadata = {\n title: string\n author: string\n subject: string\n keywords: string\n creator: string\n producer: string\n}\n\nconst EMPTY_METADATA: EditableMetadata = {\n title: "",\n author: "",\n subject: "",\n keywords: "",\n creator: "",\n producer: "",\n}\n\nexport function PdfEditorPropertiesDialog({\n documentId,\n open,\n onOpenChange,\n}: {\n documentId: string\n open: boolean\n onOpenChange: (open: boolean) => void\n}) {\n const { registry } = useRegistry()\n const documentState = useDocumentState(documentId)\n const permissions = useDocumentPermissions(documentId)\n const { fileName, notify } = usePdfEditor()\n const document = documentState?.document ?? null\n const [metadata, setMetadata] =\n React.useState<EditableMetadata>(EMPTY_METADATA)\n const [dates, setDates] = React.useState<{\n creationDate: Date | null\n modificationDate: Date | null\n }>({ creationDate: null, modificationDate: null })\n const [isLoading, setIsLoading] = React.useState(false)\n const [isSaving, setIsSaving] = React.useState(false)\n const [error, setError] = React.useState<string | null>(null)\n\n React.useEffect(() => {\n if (!open || !registry || !document) return\n\n let cancelled = false\n setIsLoading(true)\n setError(null)\n\n registry\n .getEngine()\n .getMetadata(document)\n .wait(\n (result: PdfMetadataObject) => {\n if (cancelled) return\n\n setMetadata({\n title: result.title ?? "",\n author: result.author ?? "",\n subject: result.subject ?? "",\n keywords: result.keywords ?? "",\n creator: result.creator ?? "",\n producer: result.producer ?? "",\n })\n setDates({\n creationDate: result.creationDate ?? null,\n modificationDate: result.modificationDate ?? null,\n })\n setIsLoading(false)\n },\n (failure) => {\n if (cancelled) return\n\n setError(\n failure?.reason?.message ??\n "The document metadata could not be read."\n )\n setIsLoading(false)\n }\n )\n\n return () => {\n cancelled = true\n }\n }, [document, open, registry])\n\n const updateField = (key: keyof EditableMetadata, value: string) =>\n setMetadata((previous) => ({ ...previous, [key]: value }))\n\n const handleSave = () => {\n if (!registry || !document) return\n\n setIsSaving(true)\n setError(null)\n registry\n .getEngine()\n .setMetadata(document, {\n title: metadata.title,\n author: metadata.author,\n subject: metadata.subject,\n keywords: metadata.keywords,\n creator: metadata.creator,\n producer: metadata.producer,\n modificationDate: new Date(),\n })\n .wait(\n () => {\n setIsSaving(false)\n notify("Document properties saved.", "success")\n onOpenChange(false)\n },\n (failure) => {\n setIsSaving(false)\n setError(\n failure?.reason?.message ??\n "The document metadata could not be saved."\n )\n }\n )\n }\n\n const firstPage = document?.pages[0]\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className="max-w-lg">\n <DialogHeader>\n <DialogTitle>Document properties</DialogTitle>\n <DialogDescription>{fileName}</DialogDescription>\n </DialogHeader>\n <DialogPanel className="space-y-5">\n {isLoading ? (\n <div className="grid place-items-center py-8">\n <Spinner className="size-4" />\n </div>\n ) : (\n <>\n <PdfEditorSection title="Description">\n <div className="grid gap-3">\n {(\n [\n ["title", "Title"],\n ["author", "Author"],\n ["subject", "Subject"],\n ["keywords", "Keywords"],\n ["creator", "Creator"],\n ["producer", "Producer"],\n ] as Array<[keyof EditableMetadata, string]>\n ).map(([key, label]) => (\n <div key={key} className="grid gap-1">\n <PdfEditorFieldLabel htmlFor={`pdf-editor-meta-${key}`}>\n {label}\n </PdfEditorFieldLabel>\n <Input\n id={`pdf-editor-meta-${key}`}\n size="sm"\n value={metadata[key]}\n disabled={!permissions.canModifyContents}\n onChange={(\n event: React.ChangeEvent<HTMLInputElement>\n ) => updateField(key, event.target.value)}\n />\n </div>\n ))}\n </div>\n </PdfEditorSection>\n <PdfEditorSection title="Details">\n <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5 text-xs">\n <dt className="text-muted-foreground">Pages</dt>\n <dd>{document?.pageCount ?? "—"}</dd>\n <dt className="text-muted-foreground">Page size</dt>\n <dd>\n {firstPage\n ? `${Math.round(firstPage.size.width)} × ${Math.round(firstPage.size.height)} pt`\n : "—"}\n </dd>\n <dt className="text-muted-foreground">Created</dt>\n <dd>{formatDateTime(dates.creationDate)}</dd>\n <dt className="text-muted-foreground">Modified</dt>\n <dd>{formatDateTime(dates.modificationDate)}</dd>\n <dt className="text-muted-foreground">Security</dt>\n <dd>\n {document?.isEncrypted\n ? "Password protected"\n : "No protection"}\n </dd>\n </dl>\n </PdfEditorSection>\n {error ? (\n <div className="text-xs text-destructive">{error}</div>\n ) : null}\n </>\n )}\n </DialogPanel>\n <DialogFooter>\n <Button\n type="button"\n variant="outline"\n disabled={isSaving}\n onClick={() => onOpenChange(false)}\n >\n Cancel\n </Button>\n <Button\n type="button"\n loading={isSaving}\n disabled={isLoading || !permissions.canModifyContents}\n onClick={handleSave}\n >\n Save\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Signature creation */\n/* -------------------------------------------------------------------------- */\n\ntype SignatureCreationTab = "draw" | "type" | "upload"\ntype SignatureTarget = "signature" | "initials"\n\nconst SIGNATURE_COLORS = [\n { name: "Black", value: "#111827" },\n { name: "Blue", value: "#1d4ed8" },\n { name: "Red", value: "#dc2626" },\n]\n\nfunction useSignatureFontsStylesheet(url: string | null, enabled: boolean) {\n React.useEffect(() => {\n if (!enabled || !url || typeof document === "undefined") return\n\n const existing = document.querySelector<HTMLLinkElement>(\n `link[data-pdf-editor-signature-fonts="${CSS.escape(url)}"]`\n )\n\n if (existing) return\n\n const link = document.createElement("link")\n link.rel = "stylesheet"\n link.href = url\n link.dataset.pdfEditorSignatureFonts = url\n document.head.append(link)\n }, [enabled, url])\n}\n\ntype SignatureUploadZoneProps = {\n inputRef: ReturnType<typeof useSignatureUpload>["inputRef"]\n accept: string\n isDragging: boolean\n previewUrl: string | null\n placeholder: string\n onOpen: () => void\n onFileInputChange: (event: Event) => void\n onDrop: (event: DragEvent) => void\n onDragOver: (event: DragEvent) => void\n onDragLeave: () => void\n}\n\nfunction SignatureUploadZone({\n inputRef,\n accept,\n isDragging,\n previewUrl,\n placeholder,\n onOpen,\n onFileInputChange,\n onDrop,\n onDragOver,\n onDragLeave,\n}: SignatureUploadZoneProps) {\n return (\n <>\n <input\n ref={inputRef}\n type="file"\n accept={accept}\n className="sr-only"\n tabIndex={-1}\n onChange={(event) => onFileInputChange(event.nativeEvent)}\n />\n <button\n type="button"\n onClick={onOpen}\n onDrop={(event) => {\n event.preventDefault()\n onDrop(event.nativeEvent)\n }}\n onDragOver={(event) => {\n event.preventDefault()\n onDragOver(event.nativeEvent)\n }}\n onDragLeave={() => onDragLeave()}\n className={cn(\n "flex h-full w-full items-center justify-center rounded-md border-2 border-dashed transition-colors",\n isDragging\n ? "border-primary bg-primary/5"\n : "border-input hover:border-muted-foreground/60"\n )}\n >\n {previewUrl ? (\n <img\n src={previewUrl}\n alt="Uploaded signature"\n className="max-h-[90%] max-w-[90%] object-contain"\n />\n ) : (\n <span className="px-4 text-center text-xs text-muted-foreground">\n {placeholder}\n </span>\n )}\n </button>\n </>\n )\n}\n\nfunction SignaturePad({\n tab,\n color,\n fontFamily,\n placeholder,\n uploadPlaceholder,\n drawRef,\n typeRef,\n upload,\n onResult,\n}: {\n tab: SignatureCreationTab\n color: string\n fontFamily: string\n placeholder: string\n uploadPlaceholder: string\n drawRef: React.MutableRefObject<SignatureDrawPadHandle | null>\n typeRef: React.MutableRefObject<SignatureTypePadHandle | null>\n upload: ReturnType<typeof useSignatureUpload>\n onResult: (result: SignatureFieldDefinition | null) => void\n}) {\n return (\n <div className="h-full w-full">\n {tab === "draw" ? (\n <SignatureDrawPad\n onResult={onResult}\n padRef={(handle) => {\n drawRef.current = handle\n }}\n strokeColor={color}\n strokeWidth={3}\n className="h-full w-full rounded-md border border-input bg-white"\n />\n ) : null}\n {tab === "type" ? (\n <SignatureTypePad\n onResult={onResult}\n padRef={(handle) => {\n typeRef.current = handle\n }}\n fontFamily={fontFamily}\n fontSize={40}\n color={color}\n placeholder={placeholder}\n className="h-full w-full rounded-md border border-input bg-white px-3 py-2 text-3xl text-slate-950 outline-none dark:bg-white dark:text-slate-950"\n />\n ) : null}\n {tab === "upload" ? (\n <SignatureUploadZone\n inputRef={upload.inputRef}\n accept={upload.accept}\n isDragging={upload.isDragging}\n previewUrl={upload.previewUrl}\n placeholder={uploadPlaceholder}\n onOpen={upload.openFilePicker}\n onFileInputChange={upload.handleFileInputChange}\n onDrop={upload.handleDrop}\n onDragOver={upload.handleDragOver}\n onDragLeave={upload.handleDragLeave}\n />\n ) : null}\n </div>\n )\n}\n\nexport function PdfEditorSignatureDialog({\n open,\n onOpenChange,\n}: {\n open: boolean\n onOpenChange: (open: boolean) => void\n}) {\n const { provides: signatureCapability } = useSignatureCapability()\n const { notify, signatureFontsStylesheetUrl } = usePdfEditor()\n const supportsInitials =\n (signatureCapability?.mode ?? SignatureMode.SignatureOnly) ===\n SignatureMode.SignatureAndInitials\n const [tab, setTab] = React.useState<SignatureCreationTab>("draw")\n const [color, setColor] = React.useState(SIGNATURE_COLORS[0].value)\n const [fontFamily, setFontFamily] = React.useState(\n PDF_EDITOR_SIGNATURE_FONTS[0].family\n )\n const [signature, setSignature] =\n React.useState<SignatureFieldDefinition | null>(null)\n const [initials, setInitials] =\n React.useState<SignatureFieldDefinition | null>(null)\n const [activeTarget, setActiveTarget] =\n React.useState<SignatureTarget>("signature")\n const signatureDrawRef = React.useRef<SignatureDrawPadHandle | null>(null)\n const initialsDrawRef = React.useRef<SignatureDrawPadHandle | null>(null)\n const signatureTypeRef = React.useRef<SignatureTypePadHandle | null>(null)\n const initialsTypeRef = React.useRef<SignatureTypePadHandle | null>(null)\n\n useSignatureFontsStylesheet(signatureFontsStylesheetUrl, open)\n\n const signatureUpload = useSignatureUpload({ onResult: setSignature })\n const initialsUpload = useSignatureUpload({ onResult: setInitials })\n const clearSignatureUpload = signatureUpload.clear\n const clearInitialsUpload = initialsUpload.clear\n\n const clearAll = React.useCallback(() => {\n signatureDrawRef.current?.clear()\n initialsDrawRef.current?.clear()\n signatureTypeRef.current?.clear()\n initialsTypeRef.current?.clear()\n clearSignatureUpload()\n clearInitialsUpload()\n setSignature(null)\n setInitials(null)\n }, [clearInitialsUpload, clearSignatureUpload])\n\n React.useEffect(() => {\n if (open) return\n\n setTab("draw")\n setColor(SIGNATURE_COLORS[0].value)\n setFontFamily(PDF_EDITOR_SIGNATURE_FONTS[0].family)\n setActiveTarget("signature")\n setSignature(null)\n setInitials(null)\n }, [open])\n\n const handleTabChange = (nextTab: SignatureCreationTab) => {\n clearAll()\n setTab(nextTab)\n }\n\n const canSave = Boolean(signature || initials)\n\n const handleSave = () => {\n const entrySignature = signature ?? initials\n if (!entrySignature || !signatureCapability) return\n\n signatureCapability.addEntry({\n signature: entrySignature,\n ...(initials ? { initials } : {}),\n })\n notify(signature ? "Signature saved." : "Initials saved.", "success")\n onOpenChange(false)\n }\n\n const tabs: Array<{ id: SignatureCreationTab; label: string }> = [\n { id: "draw", label: "Draw" },\n { id: "type", label: "Type" },\n { id: "upload", label: "Upload" },\n ]\n const fontOptions = PDF_EDITOR_SIGNATURE_FONTS.map((font) => ({\n label: font.name,\n value: font.family,\n }))\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className="max-w-2xl">\n <DialogHeader>\n <DialogTitle>Create signature</DialogTitle>\n <DialogDescription>\n Saved signatures can be placed anywhere in the document.\n </DialogDescription>\n </DialogHeader>\n <DialogPanel className="space-y-4">\n <div className="flex items-center gap-1 rounded-lg bg-muted p-0.5">\n {tabs.map((item) => (\n <button\n key={item.id}\n type="button"\n onClick={() => handleTabChange(item.id)}\n className={cn(\n "flex-1 rounded-md px-3 py-1.5 text-sm font-medium transition-colors",\n tab === item.id\n ? "bg-background text-foreground shadow-sm"\n : "text-muted-foreground hover:text-foreground"\n )}\n >\n {item.label}\n </button>\n ))}\n </div>\n\n <div className="space-y-2">\n <div className="flex items-center justify-between gap-3">\n {supportsInitials ? (\n <div className="flex items-center gap-1 rounded-lg bg-muted p-0.5">\n {(["signature", "initials"] as const).map((target) => (\n <button\n key={target}\n type="button"\n aria-pressed={activeTarget === target}\n onClick={() => setActiveTarget(target)}\n className={cn(\n "rounded-md px-3 py-1 text-xs font-medium transition-colors",\n activeTarget === target\n ? "bg-background text-foreground shadow-sm"\n : "text-muted-foreground hover:text-foreground"\n )}\n >\n {target === "signature" ? "Signature" : "Initials"}\n </button>\n ))}\n </div>\n ) : (\n <PdfEditorFieldLabel>Signature</PdfEditorFieldLabel>\n )}\n <Button\n type="button"\n variant="ghost"\n size="xs"\n onClick={() => {\n if (activeTarget === "signature") {\n if (tab === "draw") signatureDrawRef.current?.clear()\n else if (tab === "type") signatureTypeRef.current?.clear()\n else clearSignatureUpload()\n setSignature(null)\n } else {\n if (tab === "draw") initialsDrawRef.current?.clear()\n else if (tab === "type") initialsTypeRef.current?.clear()\n else clearInitialsUpload()\n setInitials(null)\n }\n }}\n >\n Clear\n </Button>\n </div>\n <div\n className={cn(\n "h-36 w-full",\n activeTarget !== "signature" && "hidden"\n )}\n >\n <SignaturePad\n tab={tab}\n color={color}\n fontFamily={fontFamily}\n placeholder="Type your name"\n uploadPlaceholder="Click or drop an image of your signature"\n drawRef={signatureDrawRef}\n typeRef={signatureTypeRef}\n upload={signatureUpload}\n onResult={setSignature}\n />\n </div>\n {supportsInitials ? (\n <div\n className={cn(\n "w-full",\n activeTarget !== "initials" && "hidden"\n )}\n >\n <div className="aspect-[20/7] h-36 max-w-full">\n <SignaturePad\n tab={tab}\n color={color}\n fontFamily={fontFamily}\n placeholder="Initials"\n uploadPlaceholder="Click or drop an image"\n drawRef={initialsDrawRef}\n typeRef={initialsTypeRef}\n upload={initialsUpload}\n onResult={setInitials}\n />\n </div>\n </div>\n ) : null}\n </div>\n\n <div className="flex flex-wrap items-center gap-4">\n {tab !== "upload" ? (\n <div className="flex items-center gap-2">\n <span className="text-xs text-muted-foreground">Color</span>\n <div className="flex items-center gap-1.5">\n {SIGNATURE_COLORS.map((option) => (\n <PdfEditorSwatch\n key={option.value}\n color={option.value}\n label={option.name}\n active={color === option.value}\n onClick={() => setColor(option.value)}\n />\n ))}\n <ColorPicker\n label="Custom signature color"\n rainbowTrigger\n color={color}\n onChange={setColor}\n />\n </div>\n </div>\n ) : null}\n {tab === "type" ? (\n <div className="flex items-center gap-2">\n <span className="text-xs text-muted-foreground">Font</span>\n <Select\n items={fontOptions}\n value={fontFamily}\n onValueChange={(value) => setFontFamily(String(value))}\n >\n <SelectTrigger size="sm" className="w-40">\n <SelectValue placeholder="Font" />\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {fontOptions.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n <span style={{ fontFamily: option.value }}>\n {option.label}\n </span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n ) : null}\n </div>\n </DialogPanel>\n <DialogFooter>\n <Button\n type="button"\n variant="outline"\n onClick={() => onOpenChange(false)}\n >\n Cancel\n </Button>\n <Button type="button" disabled={!canSave} onClick={handleSave}>\n Save\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Links */\n/* -------------------------------------------------------------------------- */\n\ntype LinkTab = "url" | "page"\n\nfunction readLinkTarget(target: PdfLinkTarget | undefined): {\n tab: LinkTab\n url: string\n pageNumber: number | null\n} {\n if (!target) return { tab: "url", url: "", pageNumber: null }\n\n if (target.type === "action") {\n if (target.action.type === PdfActionType.URI) {\n return { tab: "url", url: target.action.uri, pageNumber: null }\n }\n\n if (\n target.action.type === PdfActionType.Goto ||\n target.action.type === PdfActionType.RemoteGoto\n ) {\n return {\n tab: "page",\n url: "",\n pageNumber: target.action.destination.pageIndex + 1,\n }\n }\n\n return { tab: "url", url: "", pageNumber: null }\n }\n\n return {\n tab: "page",\n url: "",\n pageNumber: target.destination.pageIndex + 1,\n }\n}\n\nexport function PdfEditorLinkDialog({\n documentId,\n open,\n onOpenChange,\n source,\n}: {\n documentId: string\n open: boolean\n onOpenChange: (open: boolean) => void\n source: "annotation" | "selection"\n}) {\n const { provides: annotationCapability } = useAnnotationCapability()\n const { provides: selectionCapability } = useSelectionCapability()\n const { state: scrollState } = useScroll(documentId)\n const { notify } = usePdfEditor()\n const [tab, setTab] = React.useState<LinkTab>("url")\n const [url, setUrl] = React.useState("")\n const [pageNumber, setPageNumber] = React.useState(1)\n const totalPages = Math.max(scrollState.totalPages, 1)\n\n const annotationScope = React.useMemo(\n () => annotationCapability?.forDocument(documentId) ?? null,\n [annotationCapability, documentId]\n )\n const selectionScope = React.useMemo(\n () => selectionCapability?.forDocument(documentId) ?? null,\n [documentId, selectionCapability]\n )\n\n React.useEffect(() => {\n if (!open) return\n\n const selected =\n source === "annotation" ? annotationScope?.getSelectedAnnotation() : null\n\n if (selected && selected.object.type === PdfAnnotationSubtype.LINK) {\n const existing = readLinkTarget(\n (selected.object as PdfLinkAnnoObject).target\n )\n setTab(existing.tab)\n setUrl(existing.url)\n setPageNumber(existing.pageNumber ?? 1)\n return\n }\n\n setTab("url")\n setUrl("")\n setPageNumber(1)\n }, [annotationScope, open, source])\n\n const buildTarget = (): PdfLinkTarget | null => {\n if (tab === "url") {\n const trimmed = url.trim()\n\n if (!trimmed) return null\n\n const normalized = /^[a-z][a-z0-9+.-]*:/i.test(trimmed)\n ? trimmed\n : `https://${trimmed}`\n\n return {\n type: "action",\n action: { type: PdfActionType.URI, uri: normalized },\n }\n }\n\n return {\n type: "destination",\n destination: {\n pageIndex: Math.min(Math.max(pageNumber, 1), totalPages) - 1,\n zoom: { mode: PdfZoomMode.FitPage },\n view: [],\n },\n }\n }\n\n const handleSubmit = () => {\n const target = buildTarget()\n\n if (!target || !annotationScope) return\n\n const selected =\n source === "annotation" ? annotationScope.getSelectedAnnotation() : null\n\n if (selected && selected.object.type === PdfAnnotationSubtype.LINK) {\n annotationScope.updateAnnotation(\n selected.object.pageIndex,\n selected.object.id,\n {\n target,\n } as Partial<PdfLinkAnnoObject>\n )\n notify("Link updated.", "success")\n onOpenChange(false)\n return\n }\n\n if (selected) {\n const rects =\n "segmentRects" in selected.object &&\n Array.isArray(selected.object.segmentRects) &&\n selected.object.segmentRects.length > 0\n ? selected.object.segmentRects\n : [selected.object.rect]\n\n for (const rect of rects) {\n annotationScope.createAnnotation<PdfLinkAnnoObject>(\n selected.object.pageIndex,\n {\n id: uuidV4(),\n type: PdfAnnotationSubtype.LINK,\n pageIndex: selected.object.pageIndex,\n rect,\n inReplyToId: selected.object.id,\n replyType: PdfAnnotationReplyType.Group,\n target,\n strokeStyle: PdfAnnotationBorderStyle.UNDERLINE,\n strokeColor: "#2563eb",\n strokeWidth: 2,\n created: new Date(),\n }\n )\n }\n\n notify("Link added.", "success")\n onOpenChange(false)\n return\n }\n\n const formattedSelection = selectionScope?.getFormattedSelection() ?? []\n\n if (formattedSelection.length === 0) {\n notify("Select text or an annotation first.", "error")\n return\n }\n\n const applyLinks = (text: string[]) => {\n for (const page of formattedSelection) {\n const highlightId = uuidV4()\n\n annotationScope.createAnnotation(page.pageIndex, {\n id: highlightId,\n created: new Date(),\n flags: ["print"],\n type: PdfAnnotationSubtype.HIGHLIGHT,\n blendMode: PdfBlendMode.Multiply,\n pageIndex: page.pageIndex,\n rect: page.rect,\n segmentRects: page.segmentRects,\n strokeColor: "#ffffff",\n opacity: 0,\n custom: { text: text.join("\\n") },\n })\n\n for (const rect of page.segmentRects) {\n annotationScope.createAnnotation<PdfLinkAnnoObject>(page.pageIndex, {\n id: uuidV4(),\n type: PdfAnnotationSubtype.LINK,\n pageIndex: page.pageIndex,\n rect,\n inReplyToId: highlightId,\n replyType: PdfAnnotationReplyType.Group,\n target,\n strokeStyle: PdfAnnotationBorderStyle.UNDERLINE,\n strokeColor: "#2563eb",\n strokeWidth: 2,\n created: new Date(),\n })\n }\n }\n\n selectionScope?.clear()\n notify("Link added.", "success")\n onOpenChange(false)\n }\n\n const textTask = selectionScope?.getSelectedText()\n\n if (textTask) {\n textTask.wait(applyLinks, () => applyLinks([]))\n } else {\n applyLinks([])\n }\n }\n\n const canSubmit = tab === "url" ? url.trim().length > 0 : pageNumber >= 1\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className="max-w-md">\n <DialogHeader>\n <DialogTitle>Add link</DialogTitle>\n <DialogDescription>\n {source === "selection"\n ? "The selected text becomes a clickable link."\n : "The selected annotation becomes a clickable link."}\n </DialogDescription>\n </DialogHeader>\n <DialogPanel className="space-y-4">\n <div className="flex items-center gap-1 rounded-lg bg-muted p-0.5">\n {(\n [\n ["url", "Web address"],\n ["page", "Page in document"],\n ] as Array<[LinkTab, string]>\n ).map(([id, label]) => (\n <button\n key={id}\n type="button"\n onClick={() => setTab(id)}\n className={cn(\n "flex-1 rounded-md px-3 py-1.5 text-sm font-medium transition-colors",\n tab === id\n ? "bg-background text-foreground shadow-sm"\n : "text-muted-foreground hover:text-foreground"\n )}\n >\n {label}\n </button>\n ))}\n </div>\n {tab === "url" ? (\n <div className="grid gap-1">\n <PdfEditorFieldLabel htmlFor="pdf-editor-link-url">\n URL\n </PdfEditorFieldLabel>\n <Input\n id="pdf-editor-link-url"\n autoFocus\n placeholder="https://example.com"\n value={url}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) =>\n setUrl(event.target.value)\n }\n onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key === "Enter" && canSubmit) handleSubmit()\n }}\n />\n </div>\n ) : (\n <div className="grid gap-1">\n <PdfEditorFieldLabel htmlFor="pdf-editor-link-page">\n Page number (1–{totalPages})\n </PdfEditorFieldLabel>\n <Input\n id="pdf-editor-link-page"\n type="number"\n min={1}\n max={totalPages}\n value={pageNumber}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) =>\n setPageNumber(Number(event.target.value) || 1)\n }\n />\n </div>\n )}\n </DialogPanel>\n <DialogFooter>\n <Button\n type="button"\n variant="outline"\n onClick={() => onOpenChange(false)}\n >\n Cancel\n </Button>\n <Button type="button" disabled={!canSubmit} onClick={handleSubmit}>\n Save link\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Keyboard shortcuts */\n/* -------------------------------------------------------------------------- */\n\nexport const PDF_EDITOR_SHORTCUTS: Array<{\n group: string\n items: Array<{ keys: string[]; label: string }>\n}> = [\n {\n group: "Document",\n items: [\n { keys: ["mod+S"], label: "Download" },\n { keys: ["mod+P"], label: "Print" },\n { keys: ["mod+F"], label: "Search" },\n { keys: ["mod+Z"], label: "Undo" },\n { keys: ["mod+shift+Z"], label: "Redo" },\n ],\n },\n {\n group: "View",\n items: [\n { keys: ["mod+="], label: "Zoom in" },\n { keys: ["mod+-"], label: "Zoom out" },\n { keys: ["mod+0"], label: "Fit page" },\n { keys: ["H"], label: "Hand tool" },\n { keys: ["V"], label: "Select tool" },\n ],\n },\n {\n group: "Editing",\n items: [\n { keys: ["Esc"], label: "Cancel tool / clear selection" },\n { keys: ["Delete"], label: "Delete selected annotations" },\n { keys: ["mod+A"], label: "Select all annotations on the page" },\n ],\n },\n]\n\nexport function PdfEditorShortcutsDialog({\n open,\n onOpenChange,\n}: {\n open: boolean\n onOpenChange: (open: boolean) => void\n}) {\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className="max-w-md">\n <DialogHeader>\n <DialogTitle>Keyboard shortcuts</DialogTitle>\n </DialogHeader>\n <DialogPanel className="space-y-4">\n {PDF_EDITOR_SHORTCUTS.map((group) => (\n <PdfEditorSection key={group.group} title={group.group}>\n <div className="divide-y rounded-lg border">\n {group.items.map((item) => (\n <div\n key={item.label}\n className="flex items-center justify-between gap-3 px-3 py-1.5 text-sm"\n >\n <span>{item.label}</span>\n <span className="flex items-center gap-1">\n {item.keys.map((key) => (\n <Kbd key={key}>{formatShortcut(key)}</Kbd>\n ))}\n </span>\n </div>\n ))}\n </div>\n </PdfEditorSection>\n ))}\n </DialogPanel>\n <DialogFooter variant="bare">\n <Button type="button" onClick={() => onOpenChange(false)}>\n Done\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Password prompt (inline) */\n/* -------------------------------------------------------------------------- */\n\nexport function PdfEditorPasswordPrompt({\n documentState,\n}: {\n documentState: DocumentState\n}) {\n const { provides: documentManager } = useDocumentManagerCapability()\n const [password, setPassword] = React.useState("")\n const [isRetrying, setIsRetrying] = React.useState(false)\n const isPasswordError = documentState.errorCode === PdfErrorCode.Password\n const isIncorrect = isPasswordError && documentState.passwordProvided\n\n const handleRetry = () => {\n if (!documentManager || !password.trim()) return\n\n setIsRetrying(true)\n documentManager.retryDocument(documentState.id, { password }).wait(\n () => {\n setPassword("")\n setIsRetrying(false)\n },\n () => setIsRetrying(false)\n )\n }\n\n if (!isPasswordError) {\n return (\n <div className="grid h-full place-items-center p-6">\n <div className="max-w-sm space-y-2 text-center">\n <div className="text-sm font-medium text-foreground">\n The document could not be opened\n </div>\n <div className="text-sm text-muted-foreground">\n {documentState.error ?? "An unknown error occurred."}\n </div>\n </div>\n </div>\n )\n }\n\n return (\n <div className="grid h-full place-items-center p-6">\n <div className="w-full max-w-sm space-y-4 rounded-xl border bg-background p-5 shadow-sm">\n <div className="flex items-start gap-3">\n <div className="grid size-9 shrink-0 place-items-center rounded-full bg-muted text-muted-foreground">\n <LockGlyph className="size-4" />\n </div>\n <div className="space-y-1">\n <div className="text-sm font-medium text-foreground">\n Password required\n </div>\n <div className="text-xs text-muted-foreground">\n {isIncorrect\n ? "The password was incorrect. Try again."\n : "This document is protected. Enter the password to open it."}\n </div>\n </div>\n </div>\n <PasswordInput\n value={password}\n autoFocus\n placeholder="Document password"\n onChange={setPassword}\n onEnter={handleRetry}\n />\n <div className="flex justify-end">\n <Button\n type="button"\n loading={isRetrying}\n disabled={!password.trim()}\n onClick={handleRetry}\n >\n Open document\n </Button>\n </div>\n </div>\n </div>\n )\n}\n\nexport { ignore as ignorePdfTask }\n',+ },+ {+ fileName: "components/extend/pdf-editor-properties.tsx",+ code: '"use client"\n\nimport * as React from "react"\nimport {\n blendModeLabel,\n blendModeValues,\n makeStandardFont,\n PDF_FORM_FIELD_FLAG,\n PDF_FORM_FIELD_TYPE,\n PdfAnnotationBorderStyle,\n PdfAnnotationLineEnding,\n PdfAnnotationSubtype,\n PdfStandardFont,\n PdfStandardFontFamily,\n PdfTextAlignment,\n PdfVerticalAlignment,\n STANDARD_FONT_FAMILIES,\n standardFontFamily,\n standardFontIsBold,\n standardFontIsItalic,\n type LineEndings,\n type PdfAnnotationFlagName,\n type PdfAnnotationObject,\n type PdfTextWidgetAnnoField,\n type PdfWidgetAnnoField,\n type PdfWidgetAnnoObject,\n type PdfWidgetAnnoOption,\n} from "@embedpdf/models"\nimport {\n getSelectedAnnotations,\n useAnnotation,\n useAnnotationCapability,\n type AnnotationTool,\n type TrackedAnnotation,\n} from "@embedpdf/plugin-annotation/react"\nimport { useFormCapability } from "@embedpdf/plugin-form/react"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport { ColorPicker } from "@/components/ui/color-picker"\nimport { Input } from "@/components/ui/input"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle"\nimport {\n AlignBottomGlyph,\n AlignCenterGlyph,\n AlignLeftGlyph,\n AlignMiddleGlyph,\n AlignRightGlyph,\n AlignTopGlyph,\n BoldGlyph,\n formatDateTime,\n getAnnotationMeta,\n ItalicGlyph,\n PdfEditorCheckbox,\n PdfEditorEmptyState,\n PdfEditorFieldLabel,\n PdfEditorSection,\n PdfEditorSwatch,\n SlidersGlyph,\n TrashGlyph,\n usePdfEditor,\n} from "@/components/extend/pdf-editor-shared"\n\n/* -------------------------------------------------------------------------- */\n/* Property schema */\n/* -------------------------------------------------------------------------- */\n\ntype PropertyKind =\n | "color"\n | "colorWithTransparent"\n | "opacity"\n | "strokeWidth"\n | "strokeStyle"\n | "strokeStyleWithCloudy"\n | "linkStrokeStyle"\n | "lineEnding"\n | "lineEndings"\n | "fontFamily"\n | "fontSize"\n | "fontColor"\n | "textAlign"\n | "verticalAlign"\n | "blendMode"\n | "overlayText"\n | "rotation"\n\ntype PropertyConfig = {\n key: string\n kind: PropertyKind\n label: string\n /** Only shown while editing an existing annotation, never for tool defaults. */\n editOnly?: boolean\n}\n\nconst PROPERTY_CONFIGS: Record<string, PropertyConfig> = {\n color: { key: "color", kind: "colorWithTransparent", label: "Fill" },\n strokeColor: {\n key: "strokeColor",\n kind: "colorWithTransparent",\n label: "Stroke",\n },\n markupColor: { key: "strokeColor", kind: "color", label: "Color" },\n opacity: { key: "opacity", kind: "opacity", label: "Opacity" },\n strokeWidth: {\n key: "strokeWidth",\n kind: "strokeWidth",\n label: "Stroke width",\n },\n strokeStyle: {\n key: "strokeStyle",\n kind: "strokeStyle",\n label: "Border style",\n },\n strokeStyleWithCloudy: {\n key: "strokeStyle",\n kind: "strokeStyleWithCloudy",\n label: "Border style",\n },\n linkStrokeStyle: {\n key: "strokeStyle",\n kind: "linkStrokeStyle",\n label: "Border style",\n },\n lineEnding: {\n key: "lineEnding",\n kind: "lineEnding",\n label: "Line ending",\n },\n lineEndings: {\n key: "lineEndings",\n kind: "lineEndings",\n label: "Line endings",\n },\n fontFamily: { key: "fontFamily", kind: "fontFamily", label: "Font" },\n fontSize: { key: "fontSize", kind: "fontSize", label: "Font size" },\n fontColor: { key: "fontColor", kind: "fontColor", label: "Text color" },\n textAlign: { key: "textAlign", kind: "textAlign", label: "Alignment" },\n verticalAlign: {\n key: "verticalAlign",\n kind: "verticalAlign",\n label: "Vertical alignment",\n },\n blendMode: { key: "blendMode", kind: "blendMode", label: "Blend mode" },\n overlayText: {\n key: "overlayText",\n kind: "overlayText",\n label: "Overlay text",\n },\n rotation: {\n key: "rotation",\n kind: "rotation",\n label: "Rotation",\n editOnly: true,\n },\n}\n\n/** Ordered property lists keyed by EmbedPDF tool id. */\nconst TOOL_PROPERTIES: Record<string, string[]> = {\n highlight: ["markupColor", "opacity", "blendMode"],\n underline: ["markupColor", "opacity", "blendMode"],\n strikeout: ["markupColor", "opacity", "blendMode"],\n squiggly: ["markupColor", "opacity", "blendMode"],\n ink: ["markupColor", "opacity", "strokeWidth", "rotation"],\n inkHighlighter: [\n "markupColor",\n "opacity",\n "strokeWidth",\n "blendMode",\n "rotation",\n ],\n signatureInk: ["markupColor", "opacity", "strokeWidth", "rotation"],\n circle: [\n "color",\n "opacity",\n "strokeColor",\n "strokeStyleWithCloudy",\n "strokeWidth",\n "rotation",\n ],\n square: [\n "color",\n "opacity",\n "strokeColor",\n "strokeStyleWithCloudy",\n "strokeWidth",\n "rotation",\n ],\n polygon: [\n "strokeColor",\n "opacity",\n "strokeStyleWithCloudy",\n "strokeWidth",\n "color",\n "rotation",\n ],\n line: [\n "strokeColor",\n "opacity",\n "strokeStyle",\n "strokeWidth",\n "lineEndings",\n "color",\n "rotation",\n ],\n lineArrow: [\n "strokeColor",\n "opacity",\n "strokeStyle",\n "strokeWidth",\n "lineEndings",\n "color",\n "rotation",\n ],\n polyline: [\n "strokeColor",\n "opacity",\n "strokeStyle",\n "strokeWidth",\n "lineEndings",\n "color",\n "rotation",\n ],\n textComment: ["markupColor", "opacity"],\n insertText: ["markupColor", "opacity"],\n replaceText: ["markupColor", "opacity"],\n freeText: [\n "fontFamily",\n "fontSize",\n "fontColor",\n "textAlign",\n "verticalAlign",\n "opacity",\n "color",\n "rotation",\n ],\n freeTextCallout: [\n "fontFamily",\n "fontSize",\n "fontColor",\n "textAlign",\n "verticalAlign",\n "opacity",\n "color",\n "markupColor",\n "strokeWidth",\n "lineEnding",\n ],\n stamp: ["rotation"],\n rubberStamp: ["rotation"],\n signatureStamp: ["rotation"],\n redact: ["strokeColor", "color", "opacity", "overlayText"],\n link: ["strokeColor", "strokeWidth", "linkStrokeStyle"],\n formTextField: [\n "fontSize",\n "fontColor",\n "strokeColor",\n "strokeWidth",\n "color",\n ],\n formCheckbox: ["strokeColor", "color", "strokeWidth"],\n formCombobox: [\n "fontSize",\n "fontColor",\n "strokeColor",\n "strokeWidth",\n "color",\n ],\n formListbox: [\n "fontFamily",\n "fontSize",\n "fontColor",\n "strokeColor",\n "strokeWidth",\n "color",\n ],\n formRadioButton: ["strokeColor", "color", "strokeWidth"],\n}\n\nfunction getSharedProperties(toolIds: string[]) {\n const unique = [...new Set(toolIds)]\n\n if (unique.length === 0) return []\n\n const first = new Set(TOOL_PROPERTIES[unique[0]] ?? [])\n\n for (const id of unique.slice(1)) {\n const own = new Set(TOOL_PROPERTIES[id] ?? [])\n for (const property of first) {\n if (!own.has(property)) first.delete(property)\n }\n }\n\n return (TOOL_PROPERTIES[unique[0]] ?? []).filter((property) =>\n first.has(property)\n )\n}\n\nconst FONT_SIZE_PRESETS = [\n 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48, 72,\n]\n\nconst LINE_ENDING_OPTIONS: Array<{\n value: PdfAnnotationLineEnding\n label: string\n}> = [\n { value: PdfAnnotationLineEnding.None, label: "None" },\n { value: PdfAnnotationLineEnding.OpenArrow, label: "Open arrow" },\n { value: PdfAnnotationLineEnding.ClosedArrow, label: "Closed arrow" },\n { value: PdfAnnotationLineEnding.ROpenArrow, label: "Reverse open arrow" },\n {\n value: PdfAnnotationLineEnding.RClosedArrow,\n label: "Reverse closed arrow",\n },\n { value: PdfAnnotationLineEnding.Square, label: "Square" },\n { value: PdfAnnotationLineEnding.Circle, label: "Circle" },\n { value: PdfAnnotationLineEnding.Diamond, label: "Diamond" },\n { value: PdfAnnotationLineEnding.Butt, label: "Butt" },\n { value: PdfAnnotationLineEnding.Slash, label: "Slash" },\n]\n\nconst FLAG_OPTIONS: Array<{\n flag: PdfAnnotationFlagName\n label: string\n description: string\n}> = [\n {\n flag: "locked",\n label: "Lock position",\n description: "Prevents moving, resizing, and deleting.",\n },\n {\n flag: "lockedContents",\n label: "Lock contents",\n description: "Prevents editing the text.",\n },\n {\n flag: "print",\n label: "Print",\n description: "Include when printing.",\n },\n]\n\n/* -------------------------------------------------------------------------- */\n/* Controls */\n/* -------------------------------------------------------------------------- */\n\nfunction useDebouncedCommit<T>(\n value: T,\n onCommit: (value: T) => void,\n delay = 150\n) {\n const [draft, setDraft] = React.useState(value)\n const timeoutRef = React.useRef<number | null>(null)\n const onCommitRef = React.useRef(onCommit)\n\n React.useEffect(() => {\n onCommitRef.current = onCommit\n })\n\n React.useEffect(() => {\n setDraft(value)\n }, [value])\n\n React.useEffect(\n () => () => {\n if (timeoutRef.current !== null) window.clearTimeout(timeoutRef.current)\n },\n []\n )\n\n const update = React.useCallback(\n (next: T) => {\n setDraft(next)\n\n if (timeoutRef.current !== null) window.clearTimeout(timeoutRef.current)\n\n timeoutRef.current = window.setTimeout(() => {\n timeoutRef.current = null\n onCommitRef.current(next)\n }, delay)\n },\n [delay]\n )\n\n return [draft, update] as const\n}\n\nfunction ColorControl({\n label,\n value,\n presets,\n allowTransparent,\n onChange,\n}: {\n label: string\n value: string | undefined\n presets: string[]\n allowTransparent: boolean\n onChange: (value: string) => void\n}) {\n const current = (value ?? "").toLowerCase()\n const isTransparent = !value || current === "transparent"\n\n return (\n <div className="space-y-1.5">\n <div className="flex items-center justify-between">\n <PdfEditorFieldLabel>{label}</PdfEditorFieldLabel>\n <span className="text-[11px] text-muted-foreground tabular-nums">\n {isTransparent ? "None" : current}\n </span>\n </div>\n <div className="flex flex-wrap items-center gap-1.5">\n {presets.map((preset) => (\n <PdfEditorSwatch\n key={preset}\n color={preset}\n active={!isTransparent && current === preset.toLowerCase()}\n onClick={() => onChange(preset)}\n />\n ))}\n {allowTransparent ? (\n <PdfEditorSwatch\n color="transparent"\n label="No fill"\n active={isTransparent}\n onClick={() => onChange("transparent")}\n />\n ) : null}\n <ColorPicker\n label={`Custom ${label.toLowerCase()}`}\n rainbowTrigger\n color={isTransparent ? "#111827" : (value ?? "#111827")}\n onChange={onChange}\n />\n </div>\n </div>\n )\n}\n\nfunction SliderControl({\n label,\n value,\n min,\n max,\n step,\n format,\n onChange,\n}: {\n label: string\n value: number\n min: number\n max: number\n step: number\n format: (value: number) => string\n onChange: (value: number) => void\n}) {\n const [draft, update] = useDebouncedCommit(value, onChange)\n\n return (\n <div className="space-y-1.5">\n <div className="flex items-center justify-between">\n <PdfEditorFieldLabel>{label}</PdfEditorFieldLabel>\n <span className="text-[11px] text-muted-foreground tabular-nums">\n {format(draft)}\n </span>\n </div>\n <input\n type="range"\n min={min}\n max={max}\n step={step}\n value={draft}\n aria-label={label}\n onChange={(event) => update(Number(event.target.value))}\n className="h-1.5 w-full cursor-pointer appearance-none rounded-full bg-muted accent-primary"\n />\n </div>\n )\n}\n\ntype StrokeStyleValue =\n | "solid"\n | "dotted"\n | "short-dashed"\n | "dashed"\n | "long-dashed"\n | "dash-dot"\n | "long-dash-dot"\n | "dash-dot-dot"\n | "cloudy-1"\n | "cloudy-2"\n | "underline"\n | "custom"\n\nconst STROKE_STYLE_PRESETS: Array<{\n value: Exclude<\n StrokeStyleValue,\n "cloudy-1" | "cloudy-2" | "underline" | "custom"\n >\n label: string\n dashArray?: number[]\n}> = [\n { value: "solid", label: "Solid" },\n { value: "dotted", label: "Dotted", dashArray: [1, 2] },\n { value: "short-dashed", label: "Short dashed", dashArray: [2, 2] },\n { value: "dashed", label: "Dashed", dashArray: [4, 3] },\n { value: "long-dashed", label: "Long dashed", dashArray: [8, 4] },\n { value: "dash-dot", label: "Dash dot", dashArray: [6, 3, 1, 3] },\n {\n value: "long-dash-dot",\n label: "Long dash dot",\n dashArray: [10, 4, 1, 4],\n },\n {\n value: "dash-dot-dot",\n label: "Dash dot dot",\n dashArray: [6, 3, 1, 3, 1, 3],\n },\n]\n\nfunction getStrokeDashArray(value: StrokeStyleValue) {\n return STROKE_STYLE_PRESETS.find((preset) => preset.value === value)\n ?.dashArray\n}\n\nfunction StrokeStylePreview({\n value,\n dashArray,\n}: {\n value: StrokeStyleValue\n dashArray?: number[]\n}) {\n const path =\n value === "cloudy-2"\n ? "M1 8 Q3 2 5 8 Q7 2 9 8 Q11 2 13 8 Q15 2 17 8 Q19 2 21 8 Q23 2 25 8 Q27 2 29 8 Q31 2 33 8 Q35 2 37 8 Q39 2 41 8 Q43 2 45 8 Q47 2 49 8 Q51 2 55 8"\n : "M1 8 Q5 1 9 8 Q13 1 17 8 Q21 1 25 8 Q29 1 33 8 Q37 1 41 8 Q45 1 49 8 Q53 1 55 8"\n const resolvedDashArray = dashArray ?? getStrokeDashArray(value)\n\n return (\n <svg\n aria-hidden="true"\n viewBox="0 0 56 12"\n className="h-6! w-24! shrink-0 text-foreground"\n >\n <path\n d={value.startsWith("cloudy") ? path : "M1 6H55"}\n fill="none"\n stroke="currentColor"\n strokeDasharray={resolvedDashArray?.join(" ")}\n strokeLinecap="round"\n strokeWidth="2.25"\n />\n </svg>\n )\n}\n\nfunction SelectControl({\n label,\n value,\n options,\n onChange,\n}: {\n label: string\n value: string\n options: Array<{\n value: string\n label: string\n preview?: React.ReactNode\n }>\n onChange: (value: string) => void\n}) {\n const selectedOption =\n options.find((option) => option.value === value) ?? null\n\n return (\n <div className="space-y-1.5">\n <PdfEditorFieldLabel>{label}</PdfEditorFieldLabel>\n <Select\n items={options}\n value={value}\n onValueChange={(next) => {\n if (next) onChange(String(next))\n }}\n >\n <SelectTrigger size="sm" className="w-full">\n <SelectValue placeholder={label}>\n {selectedOption ? (\n <span className="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-3">\n <span className="truncate">{selectedOption.label}</span>\n {selectedOption.preview}\n </span>\n ) : (\n label\n )}\n </SelectValue>\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {options.map((option) => (\n <SelectItem\n key={option.value}\n value={option.value}\n className={cn(option.preview && "py-0.5 pe-2")}\n >\n <span className="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-3">\n <span className="truncate">{option.label}</span>\n {option.preview}\n </span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n )\n}\n\nfunction getStrokeStyleValue(\n strokeStyle: PdfAnnotationBorderStyle | undefined,\n cloudyBorderIntensity: number | undefined,\n strokeDashArray: number[] | undefined\n): StrokeStyleValue {\n if (\n strokeStyle === PdfAnnotationBorderStyle.CLOUDY ||\n (cloudyBorderIntensity ?? 0) > 0\n ) {\n return (cloudyBorderIntensity ?? 1) >= 2 ? "cloudy-2" : "cloudy-1"\n }\n\n if (strokeStyle === PdfAnnotationBorderStyle.UNDERLINE) return "underline"\n\n if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {\n const preset = STROKE_STYLE_PRESETS.find((item) => {\n if (!item.dashArray || !strokeDashArray) return false\n if (item.dashArray.length !== strokeDashArray.length) return false\n\n return item.dashArray.every(\n (part, index) => part === strokeDashArray[index]\n )\n })\n\n return preset?.value ?? "custom"\n }\n\n return "solid"\n}\n\nfunction getStrokeStylePatch(\n value: StrokeStyleValue,\n customDashArray?: number[]\n) {\n const dashArray = getStrokeDashArray(value)\n\n if (dashArray || value === "custom") {\n return {\n strokeStyle: PdfAnnotationBorderStyle.DASHED,\n strokeDashArray: dashArray ?? customDashArray ?? [4, 3],\n cloudyBorderIntensity: 0,\n }\n }\n\n switch (value) {\n case "underline":\n return {\n strokeStyle: PdfAnnotationBorderStyle.UNDERLINE,\n strokeDashArray: undefined,\n cloudyBorderIntensity: 0,\n }\n case "cloudy-1":\n return {\n strokeStyle: PdfAnnotationBorderStyle.CLOUDY,\n strokeDashArray: undefined,\n cloudyBorderIntensity: 1,\n }\n case "cloudy-2":\n return {\n strokeStyle: PdfAnnotationBorderStyle.CLOUDY,\n strokeDashArray: undefined,\n cloudyBorderIntensity: 2,\n }\n default:\n return {\n strokeStyle: PdfAnnotationBorderStyle.SOLID,\n strokeDashArray: undefined,\n cloudyBorderIntensity: 0,\n }\n }\n}\n\nfunction FontControl({\n value,\n onChange,\n}: {\n value: PdfStandardFont | undefined\n onChange: (value: PdfStandardFont) => void\n}) {\n const font = value ?? PdfStandardFont.Helvetica\n const family = standardFontFamily(font)\n const bold = standardFontIsBold(font)\n const italic = standardFontIsItalic(font)\n const supportsStyles =\n family !== PdfStandardFontFamily.Symbol &&\n family !== PdfStandardFontFamily.ZapfDingbats\n const familyOptions = STANDARD_FONT_FAMILIES.filter(\n (item) => item !== PdfStandardFontFamily.Unknown\n ).map((item) => ({ label: item, value: item }))\n\n const apply = (\n nextFamily: PdfStandardFontFamily,\n nextBold: boolean,\n nextItalic: boolean\n ) => {\n const next =\n makeStandardFont(nextFamily, { bold: nextBold, italic: nextItalic }) ??\n makeStandardFont(nextFamily, { bold: false, italic: false })\n\n if (next !== undefined && next !== PdfStandardFont.Unknown) onChange(next)\n }\n\n return (\n <div className="space-y-1.5">\n <PdfEditorFieldLabel>Font</PdfEditorFieldLabel>\n <div className="flex items-center gap-1.5">\n <Select\n items={familyOptions}\n value={family}\n onValueChange={(next) =>\n apply(String(next) as PdfStandardFontFamily, bold, italic)\n }\n >\n <SelectTrigger size="sm" className="min-w-0 flex-1">\n <SelectValue placeholder="Font" />\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {familyOptions.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToggleGroup\n multiple\n value={[bold ? "bold" : "", italic ? "italic" : ""].filter(Boolean)}\n onValueChange={(next: string[]) =>\n apply(family, next.includes("bold"), next.includes("italic"))\n }\n spacing="none"\n className="shrink-0"\n >\n <ToggleGroupItem\n value="bold"\n size="sm"\n variant="outline"\n aria-label="Bold"\n disabled={!supportsStyles}\n >\n <BoldGlyph className="size-3.5" />\n </ToggleGroupItem>\n <ToggleGroupItem\n value="italic"\n size="sm"\n variant="outline"\n aria-label="Italic"\n disabled={!supportsStyles}\n >\n <ItalicGlyph className="size-3.5" />\n </ToggleGroupItem>\n </ToggleGroup>\n </div>\n </div>\n )\n}\n\nfunction FontSizeControl({\n value,\n onChange,\n}: {\n value: number | undefined\n onChange: (value: number) => void\n}) {\n const [draft, update] = useDebouncedCommit(value ?? 12, onChange, 250)\n const sizeOptions = (\n FONT_SIZE_PRESETS.includes(draft)\n ? FONT_SIZE_PRESETS\n : [...FONT_SIZE_PRESETS, draft].sort((a, b) => a - b)\n ).map((size) => ({ label: `${size} pt`, value: String(size) }))\n\n return (\n <div className="space-y-1.5">\n <PdfEditorFieldLabel>Font size</PdfEditorFieldLabel>\n <div className="flex items-center gap-1.5">\n <Input\n type="number"\n size="sm"\n min={4}\n max={200}\n value={draft}\n className="w-20"\n onChange={(event: React.ChangeEvent<HTMLInputElement>) => {\n const next = Number(event.target.value)\n if (Number.isFinite(next) && next > 0) update(next)\n }}\n />\n <Select\n items={sizeOptions}\n value={String(draft)}\n onValueChange={(next) => onChange(Number(next))}\n >\n <SelectTrigger size="sm" className="min-w-0 flex-1">\n <SelectValue placeholder="Size" />\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {sizeOptions.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n </div>\n )\n}\n\nfunction AlignControl({\n label,\n value,\n onChange,\n options,\n}: {\n label: string\n value: string\n onChange: (value: string) => void\n options: Array<{ value: string; label: string; glyph: React.ReactNode }>\n}) {\n return (\n <div className="space-y-1.5">\n <PdfEditorFieldLabel>{label}</PdfEditorFieldLabel>\n <ToggleGroup\n value={[value]}\n onValueChange={(next: string[]) => {\n const selected = next[0]\n if (selected !== undefined) onChange(selected)\n }}\n spacing="none"\n >\n {options.map((option) => (\n <ToggleGroupItem\n key={option.value}\n value={option.value}\n size="sm"\n variant="outline"\n aria-label={option.label}\n >\n {option.glyph}\n </ToggleGroupItem>\n ))}\n </ToggleGroup>\n </div>\n )\n}\n\nfunction LineEndingPreview({ value }: { value: PdfAnnotationLineEnding }) {\n const isOpenArrow =\n value === PdfAnnotationLineEnding.OpenArrow ||\n value === PdfAnnotationLineEnding.ROpenArrow\n const isClosedArrow =\n value === PdfAnnotationLineEnding.ClosedArrow ||\n value === PdfAnnotationLineEnding.RClosedArrow\n const isReverse =\n value === PdfAnnotationLineEnding.ROpenArrow ||\n value === PdfAnnotationLineEnding.RClosedArrow\n const lineEndX = isReverse\n ? isClosedArrow\n ? 58\n : 56\n : isClosedArrow\n ? 68\n : 66\n\n return (\n <svg\n aria-hidden="true"\n viewBox="0 0 72 16"\n className="h-6! w-24! shrink-0 text-foreground"\n >\n <path\n d={`M2 8H${lineEndX}`}\n fill="none"\n stroke="currentColor"\n strokeLinecap="round"\n strokeWidth="2.5"\n />\n {isOpenArrow ? (\n <path\n d={isReverse ? "M56 8 66 2M56 8l10 6" : "M66 8 56 2M66 8l-10 6"}\n fill="none"\n stroke="currentColor"\n strokeLinecap="round"\n strokeLinejoin="round"\n strokeWidth="2.5"\n />\n ) : null}\n {isClosedArrow ? (\n <path\n d={isReverse ? "m58 8 10-6v12Z" : "m68 8-10-6v12Z"}\n fill="currentColor"\n />\n ) : null}\n {value === PdfAnnotationLineEnding.Square ? (\n <rect x="60" y="2" width="12" height="12" fill="currentColor" />\n ) : null}\n {value === PdfAnnotationLineEnding.Circle ? (\n <circle cx="66" cy="8" r="6" fill="currentColor" />\n ) : null}\n {value === PdfAnnotationLineEnding.Diamond ? (\n <path d="m66 2 6 6-6 6-6-6Z" fill="currentColor" />\n ) : null}\n {value === PdfAnnotationLineEnding.Butt ? (\n <path d="M66 2v12" stroke="currentColor" strokeWidth="2.5" />\n ) : null}\n {value === PdfAnnotationLineEnding.Slash ? (\n <path d="m60 14 12-12" stroke="currentColor" strokeWidth="2.5" />\n ) : null}\n </svg>\n )\n}\n\nfunction LineEndingsControl({\n value,\n onChange,\n}: {\n value: LineEndings | undefined\n onChange: (value: LineEndings) => void\n}) {\n const start = value?.start ?? PdfAnnotationLineEnding.None\n const end = value?.end ?? PdfAnnotationLineEnding.None\n const options = LINE_ENDING_OPTIONS.map((option) => ({\n value: String(option.value),\n label: option.label,\n preview: <LineEndingPreview value={option.value} />,\n }))\n\n return (\n <div className="space-y-2">\n <SelectControl\n label="Line start"\n value={String(start)}\n options={options}\n onChange={(next) =>\n onChange({ start: Number(next) as PdfAnnotationLineEnding, end })\n }\n />\n <SelectControl\n label="Line end"\n value={String(end)}\n options={options}\n onChange={(next) =>\n onChange({ start, end: Number(next) as PdfAnnotationLineEnding })\n }\n />\n </div>\n )\n}\n\nfunction LineEndingControl({\n label,\n value,\n onChange,\n}: {\n label: string\n value: PdfAnnotationLineEnding | undefined\n onChange: (value: PdfAnnotationLineEnding) => void\n}) {\n const options = LINE_ENDING_OPTIONS.map((option) => ({\n value: String(option.value),\n label: option.label,\n preview: <LineEndingPreview value={option.value} />,\n }))\n\n return (\n <SelectControl\n label={label}\n value={String(value ?? PdfAnnotationLineEnding.None)}\n options={options}\n onChange={(next) => onChange(Number(next) as PdfAnnotationLineEnding)}\n />\n )\n}\n\nfunction TextControl({\n label,\n value,\n placeholder,\n onChange,\n}: {\n label: string\n value: string\n placeholder?: string\n onChange: (value: string) => void\n}) {\n const [draft, update] = useDebouncedCommit(value, onChange, 400)\n\n return (\n <div className="space-y-1.5">\n <PdfEditorFieldLabel>{label}</PdfEditorFieldLabel>\n <Input\n size="sm"\n value={draft}\n placeholder={placeholder}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) =>\n update(event.target.value)\n }\n />\n </div>\n )\n}\n\nfunction RotationControl({\n value,\n onChange,\n}: {\n value: number\n onChange: (value: number) => void\n}) {\n const [draft, update] = useDebouncedCommit(value, onChange, 250)\n\n return (\n <div className="space-y-1.5">\n <PdfEditorFieldLabel>Rotation</PdfEditorFieldLabel>\n <div className="flex items-center gap-1.5">\n <Input\n type="number"\n size="sm"\n min={0}\n max={359}\n value={Math.round(draft)}\n className="w-20"\n onChange={(event: React.ChangeEvent<HTMLInputElement>) =>\n update(((Number(event.target.value) % 360) + 360) % 360)\n }\n />\n <span className="text-xs text-muted-foreground">degrees</span>\n {[0, 90, 180, 270].map((preset) => (\n <Button\n key={preset}\n type="button"\n size="xs"\n variant={draft === preset ? "secondary" : "ghost"}\n onClick={() => {\n update(preset)\n }}\n >\n {preset}°\n </Button>\n ))}\n </div>\n </div>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Property list */\n/* -------------------------------------------------------------------------- */\n\nfunction PropertyControl({\n config,\n values,\n colorPresets,\n onPatch,\n onRotate,\n}: {\n config: PropertyConfig\n values: Record<string, unknown>\n colorPresets: string[]\n onPatch: (patch: Record<string, unknown>) => void\n onRotate?: (rotation: number) => void\n}) {\n const value = values[config.key]\n\n switch (config.kind) {\n case "color":\n case "colorWithTransparent":\n case "fontColor":\n return (\n <ColorControl\n label={config.label}\n value={typeof value === "string" ? value : undefined}\n presets={colorPresets}\n allowTransparent={config.kind === "colorWithTransparent"}\n onChange={(next) => onPatch({ [config.key]: next })}\n />\n )\n case "opacity":\n return (\n <SliderControl\n label={config.label}\n value={typeof value === "number" ? value : 1}\n min={0.1}\n max={1}\n step={0.05}\n format={(item) => `${Math.round(item * 100)}%`}\n onChange={(next) => onPatch({ [config.key]: next })}\n />\n )\n case "strokeWidth":\n return (\n <SliderControl\n label={config.label}\n value={typeof value === "number" ? value : 1}\n min={1}\n max={30}\n step={1}\n format={(item) => `${item} pt`}\n onChange={(next) => onPatch({ [config.key]: next })}\n />\n )\n case "strokeStyle":\n case "strokeStyleWithCloudy":\n case "linkStrokeStyle": {\n const strokeDashArray = values.strokeDashArray as number[] | undefined\n const selectedValue = getStrokeStyleValue(\n value as PdfAnnotationBorderStyle | undefined,\n values.cloudyBorderIntensity as number | undefined,\n strokeDashArray\n )\n const options: Array<{\n value: string\n label: string\n preview: React.ReactNode\n }> = STROKE_STYLE_PRESETS.map((preset) => ({\n value: preset.value,\n label: preset.label,\n preview: (\n <StrokeStylePreview\n value={preset.value}\n dashArray={preset.dashArray}\n />\n ),\n }))\n\n if (config.kind === "linkStrokeStyle") {\n options.splice(1, 0, {\n value: "underline",\n label: "Underline",\n preview: <StrokeStylePreview value="underline" />,\n })\n }\n\n if (config.kind === "strokeStyleWithCloudy") {\n options.push(\n {\n value: "cloudy-1",\n label: "Cloudy",\n preview: <StrokeStylePreview value="cloudy-1" />,\n },\n {\n value: "cloudy-2",\n label: "Cloudy (dense)",\n preview: <StrokeStylePreview value="cloudy-2" />,\n }\n )\n }\n\n if (selectedValue === "custom") {\n options.push({\n value: "custom",\n label: "Custom dashed",\n preview: (\n <StrokeStylePreview value="custom" dashArray={strokeDashArray} />\n ),\n })\n }\n\n return (\n <SelectControl\n label={config.label}\n value={selectedValue}\n options={options}\n onChange={(next) =>\n onPatch(\n getStrokeStylePatch(next as StrokeStyleValue, strokeDashArray)\n )\n }\n />\n )\n }\n case "lineEnding":\n return (\n <LineEndingControl\n label={config.label}\n value={value as PdfAnnotationLineEnding | undefined}\n onChange={(next) => onPatch({ [config.key]: next })}\n />\n )\n case "lineEndings":\n return (\n <LineEndingsControl\n value={value as LineEndings | undefined}\n onChange={(next) => onPatch({ lineEndings: next })}\n />\n )\n case "fontFamily":\n return (\n <FontControl\n value={value as PdfStandardFont | undefined}\n onChange={(next) => onPatch({ fontFamily: next })}\n />\n )\n case "fontSize":\n return (\n <FontSizeControl\n value={typeof value === "number" ? value : undefined}\n onChange={(next) => onPatch({ fontSize: next })}\n />\n )\n case "textAlign":\n return (\n <AlignControl\n label={config.label}\n value={String(value ?? PdfTextAlignment.Left)}\n onChange={(next) => onPatch({ textAlign: Number(next) })}\n options={[\n {\n value: String(PdfTextAlignment.Left),\n label: "Align left",\n glyph: <AlignLeftGlyph className="size-3.5" />,\n },\n {\n value: String(PdfTextAlignment.Center),\n label: "Align center",\n glyph: <AlignCenterGlyph className="size-3.5" />,\n },\n {\n value: String(PdfTextAlignment.Right),\n label: "Align right",\n glyph: <AlignRightGlyph className="size-3.5" />,\n },\n ]}\n />\n )\n case "verticalAlign":\n return (\n <AlignControl\n label={config.label}\n value={String(value ?? PdfVerticalAlignment.Top)}\n onChange={(next) => onPatch({ verticalAlign: Number(next) })}\n options={[\n {\n value: String(PdfVerticalAlignment.Top),\n label: "Align top",\n glyph: <AlignTopGlyph className="size-3.5" />,\n },\n {\n value: String(PdfVerticalAlignment.Middle),\n label: "Align middle",\n glyph: <AlignMiddleGlyph className="size-3.5" />,\n },\n {\n value: String(PdfVerticalAlignment.Bottom),\n label: "Align bottom",\n glyph: <AlignBottomGlyph className="size-3.5" />,\n },\n ]}\n />\n )\n case "blendMode":\n return (\n <SelectControl\n label={config.label}\n value={String(value ?? 0)}\n options={blendModeValues.map((mode) => ({\n value: String(mode),\n label: blendModeLabel(mode),\n }))}\n onChange={(next) => onPatch({ blendMode: Number(next) })}\n />\n )\n case "overlayText":\n return (\n <TextControl\n label={config.label}\n value={typeof value === "string" ? value : ""}\n placeholder="e.g. REDACTED"\n onChange={(next) => onPatch({ overlayText: next })}\n />\n )\n case "rotation":\n return (\n <RotationControl\n value={typeof value === "number" ? value : 0}\n onChange={(next) =>\n onRotate ? onRotate(next) : onPatch({ rotation: next })\n }\n />\n )\n default:\n return null\n }\n}\n\n/* -------------------------------------------------------------------------- */\n/* Widget (form field) properties */\n/* -------------------------------------------------------------------------- */\n\nconst FIELD_TYPE_LABELS: Partial<Record<PDF_FORM_FIELD_TYPE, string>> = {\n [PDF_FORM_FIELD_TYPE.TEXTFIELD]: "Text field",\n [PDF_FORM_FIELD_TYPE.CHECKBOX]: "Checkbox",\n [PDF_FORM_FIELD_TYPE.RADIOBUTTON]: "Radio button",\n [PDF_FORM_FIELD_TYPE.COMBOBOX]: "Dropdown",\n [PDF_FORM_FIELD_TYPE.LISTBOX]: "List box",\n [PDF_FORM_FIELD_TYPE.PUSHBUTTON]: "Button",\n [PDF_FORM_FIELD_TYPE.SIGNATURE]: "Signature field",\n}\n\nexport function getFormFieldTypeLabel(type: PDF_FORM_FIELD_TYPE) {\n return FIELD_TYPE_LABELS[type] ?? "Form field"\n}\n\nfunction WidgetProperties({\n documentId,\n widget,\n}: {\n documentId: string\n widget: PdfWidgetAnnoObject\n}) {\n const { provides: annotation } = useAnnotation(documentId)\n const { provides: form } = useFormCapability()\n const { openDialog, notify } = usePdfEditor()\n const [nameDraft, setNameDraft] = React.useState(widget.field.name)\n const [nameError, setNameError] = React.useState<string | null>(null)\n const field = widget.field\n const fieldLabel = getFormFieldTypeLabel(field.type)\n\n React.useEffect(() => {\n setNameDraft(widget.field.name)\n setNameError(null)\n }, [widget.field.name, widget.id])\n\n const updateField = React.useCallback(\n (patch: Partial<PdfWidgetAnnoField>) => {\n annotation?.updateAnnotations([\n {\n pageIndex: widget.pageIndex,\n id: widget.id,\n patch: { field: { ...widget.field, ...patch } as PdfWidgetAnnoField },\n },\n ])\n },\n [annotation, widget.field, widget.id, widget.pageIndex]\n )\n\n const toggleFlag = (flag: PDF_FORM_FIELD_FLAG, enabled: boolean) => {\n const current = field.flag ?? PDF_FORM_FIELD_FLAG.NONE\n updateField({ flag: enabled ? current | flag : current & ~flag })\n }\n\n const commitName = () => {\n const nextName = nameDraft.trim()\n\n if (!form || !nextName || nextName === field.name) {\n setNameDraft(field.name)\n return\n }\n\n form.renameField(widget.id, nextName, documentId).wait(\n (result) => {\n setNameError(null)\n\n if (result.outcome === "conflict") {\n openDialog({\n type: "confirm",\n title: "Share this field?",\n description: `A ${fieldLabel.toLowerCase()} named "${result.fieldName}" already exists. Sharing makes both widgets show the same value.`,\n confirmLabel: "Share field",\n onConfirm: () => {\n form\n .shareField(widget.id, result.targetAnnotationId, documentId)\n .wait(\n () => notify("Field shared.", "success"),\n (failure) => {\n setNameError(failure.reason.message)\n setNameDraft(field.name)\n }\n )\n },\n })\n }\n },\n (failure) => {\n setNameError(failure.reason.message)\n setNameDraft(field.name)\n }\n )\n }\n\n const options: PdfWidgetAnnoOption[] =\n field.type === PDF_FORM_FIELD_TYPE.COMBOBOX ||\n field.type === PDF_FORM_FIELD_TYPE.LISTBOX\n ? ((field as { options?: PdfWidgetAnnoOption[] }).options ?? [])\n : []\n const setOptions = (next: PdfWidgetAnnoOption[]) =>\n updateField({ options: next } as Partial<PdfWidgetAnnoField>)\n\n const isTextField = field.type === PDF_FORM_FIELD_TYPE.TEXTFIELD\n const textField = field as PdfTextWidgetAnnoField\n const maxLength = isTextField ? (textField.maxLen ?? 0) : 0\n const isComb = Boolean(field.flag & PDF_FORM_FIELD_FLAG.TEXT_COMB)\n\n return (\n <PdfEditorSection title={`${fieldLabel} settings`}>\n <div className="space-y-3">\n <div className="space-y-1.5">\n <PdfEditorFieldLabel htmlFor={`pdf-editor-field-name-${widget.id}`}>\n Field name\n </PdfEditorFieldLabel>\n <Input\n id={`pdf-editor-field-name-${widget.id}`}\n size="sm"\n value={nameDraft}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) =>\n setNameDraft(event.target.value)\n }\n onBlur={commitName}\n onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key === "Enter") event.currentTarget.blur()\n }}\n />\n {nameError ? (\n <div className="text-xs text-destructive">{nameError}</div>\n ) : null}\n </div>\n\n {isTextField ? (\n <>\n <TextControl\n label="Default value"\n value={field.value ?? ""}\n onChange={(next) => updateField({ value: next })}\n />\n <div className="space-y-1.5">\n <PdfEditorFieldLabel>Max length</PdfEditorFieldLabel>\n <Input\n type="number"\n size="sm"\n min={0}\n placeholder="Unlimited"\n value={maxLength || ""}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) => {\n const parsed = Number.parseInt(event.target.value, 10)\n const next =\n Number.isNaN(parsed) || parsed <= 0 ? undefined : parsed\n updateField({ maxLen: next } as Partial<PdfWidgetAnnoField>)\n if (!next && isComb)\n toggleFlag(PDF_FORM_FIELD_FLAG.TEXT_COMB, false)\n }}\n />\n </div>\n </>\n ) : null}\n\n {options.length > 0 ||\n field.type === PDF_FORM_FIELD_TYPE.COMBOBOX ||\n field.type === PDF_FORM_FIELD_TYPE.LISTBOX ? (\n <div className="space-y-1.5">\n <PdfEditorFieldLabel>Options</PdfEditorFieldLabel>\n <div className="space-y-1.5">\n {options.map((option, index) => (\n <div key={index} className="flex items-center gap-1.5">\n <Input\n size="sm"\n defaultValue={option.label}\n onBlur={(event: React.FocusEvent<HTMLInputElement>) => {\n const nextLabel = event.target.value\n if (nextLabel === option.label) return\n setOptions(\n options.map((item, itemIndex) =>\n itemIndex === index\n ? { ...item, label: nextLabel }\n : item\n )\n )\n }}\n onKeyDown={(\n event: React.KeyboardEvent<HTMLInputElement>\n ) => {\n if (event.key === "Enter") event.currentTarget.blur()\n }}\n />\n <Button\n type="button"\n variant="ghost"\n size="icon-xs"\n aria-label="Remove option"\n onClick={() =>\n setOptions(\n options.filter((_, itemIndex) => itemIndex !== index)\n )\n }\n >\n <TrashGlyph className="size-3.5" />\n </Button>\n </div>\n ))}\n <Button\n type="button"\n variant="outline"\n size="xs"\n onClick={() =>\n setOptions([\n ...options,\n {\n label: `Option ${options.length + 1}`,\n isSelected: false,\n },\n ])\n }\n >\n Add option\n </Button>\n </div>\n </div>\n ) : null}\n\n <div className="space-y-0.5">\n <PdfEditorCheckbox\n checked={Boolean(field.flag & PDF_FORM_FIELD_FLAG.READONLY)}\n onCheckedChange={(checked) =>\n toggleFlag(PDF_FORM_FIELD_FLAG.READONLY, checked)\n }\n label="Read only"\n />\n <PdfEditorCheckbox\n checked={Boolean(field.flag & PDF_FORM_FIELD_FLAG.REQUIRED)}\n onCheckedChange={(checked) =>\n toggleFlag(PDF_FORM_FIELD_FLAG.REQUIRED, checked)\n }\n label="Required"\n />\n {isTextField ? (\n <>\n <PdfEditorCheckbox\n checked={Boolean(\n field.flag & PDF_FORM_FIELD_FLAG.TEXT_MULTIPLINE\n )}\n onCheckedChange={(checked) =>\n toggleFlag(PDF_FORM_FIELD_FLAG.TEXT_MULTIPLINE, checked)\n }\n label="Multiline"\n />\n <PdfEditorCheckbox\n checked={isComb}\n disabled={maxLength <= 0}\n onCheckedChange={(checked) =>\n toggleFlag(PDF_FORM_FIELD_FLAG.TEXT_COMB, checked)\n }\n label="Comb of characters"\n description="Requires a max length."\n />\n </>\n ) : null}\n {field.type === PDF_FORM_FIELD_TYPE.LISTBOX ? (\n <PdfEditorCheckbox\n checked={Boolean(\n field.flag & PDF_FORM_FIELD_FLAG.CHOICE_MULTL_SELECT\n )}\n onCheckedChange={(checked) =>\n toggleFlag(PDF_FORM_FIELD_FLAG.CHOICE_MULTL_SELECT, checked)\n }\n label="Allow multiple selections"\n />\n ) : null}\n </div>\n </div>\n </PdfEditorSection>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Panel */\n/* -------------------------------------------------------------------------- */\n\nexport function PdfEditorPropertiesPanel({\n documentId,\n}: {\n documentId: string\n}) {\n const { provides: annotationCapability } = useAnnotationCapability()\n const { provides: annotation, state } = useAnnotation(documentId)\n const { permissions } = usePdfEditor()\n const [toolSnapshot, setToolSnapshot] = React.useState<{\n source: typeof annotationCapability\n tools: AnnotationTool[]\n } | null>(null)\n\n React.useEffect(() => {\n if (!annotationCapability) return\n\n return annotationCapability.onToolsChange(({ tools }) =>\n setToolSnapshot({ source: annotationCapability, tools })\n )\n }, [annotationCapability])\n\n const selected = React.useMemo(() => getSelectedAnnotations(state), [state])\n const tools =\n toolSnapshot?.source === annotationCapability\n ? toolSnapshot.tools\n : (annotationCapability?.getTools() ?? [])\n const activeTool: AnnotationTool | null =\n state.activeToolId && annotationCapability\n ? (tools.find((tool) => tool.id === state.activeToolId) ?? null)\n : null\n const colorPresets = annotationCapability?.getColorPresets() ?? []\n\n const selectedToolIds = React.useMemo(\n () =>\n selected\n .map(\n (item) => annotationCapability?.findToolForAnnotation(item.object)?.id\n )\n .filter((id): id is string => Boolean(id)),\n [annotationCapability, selected]\n )\n\n const isEditing = selected.length > 0\n const propertyKeys = isEditing\n ? getSharedProperties(selectedToolIds)\n : activeTool\n ? (TOOL_PROPERTIES[activeTool.id] ?? [])\n : []\n const configs = propertyKeys\n .map((key) => PROPERTY_CONFIGS[key])\n .filter((config): config is PropertyConfig => Boolean(config))\n .filter((config) => isEditing || !config.editOnly)\n\n const values = React.useMemo<Record<string, unknown>>(() => {\n if (isEditing)\n return selected[0].object as unknown as Record<string, unknown>\n if (activeTool)\n return activeTool.defaults as unknown as Record<string, unknown>\n return {}\n }, [activeTool, isEditing, selected])\n\n const canEdit = permissions.canModifyAnnotations\n const structurallyLocked = selected.some((item) =>\n annotation ? annotation.isAnnotationStructurallyLocked(item.object) : false\n )\n\n const applyPatch = React.useCallback(\n (patch: Record<string, unknown>) => {\n if (isEditing) {\n annotation?.updateAnnotations(\n selected.map((item) => ({\n pageIndex: item.object.pageIndex,\n id: item.object.id,\n patch: {\n ...patch,\n modified: new Date(),\n } as Partial<PdfAnnotationObject>,\n }))\n )\n return\n }\n\n if (activeTool && annotationCapability) {\n annotationCapability.setToolDefaults(\n activeTool.id,\n patch as Partial<PdfAnnotationObject> & Record<string, unknown>\n )\n }\n },\n [activeTool, annotation, annotationCapability, isEditing, selected]\n )\n\n const applyRotation = React.useCallback(\n (rotation: number) => {\n if (!annotation || !annotationCapability) return\n\n for (const item of selected) {\n const current = item.object.rotation ?? 0\n let patch: Partial<PdfAnnotationObject>\n\n try {\n patch = annotationCapability.transformAnnotation(item.object, {\n type: "rotate",\n changes: { rotation },\n metadata: {\n rotationAngle: rotation,\n rotationDelta: rotation - current,\n },\n })\n } catch {\n patch = { rotation }\n }\n\n annotation.updateAnnotation(item.object.pageIndex, item.object.id, {\n ...patch,\n modified: new Date(),\n })\n }\n },\n [annotation, annotationCapability, selected]\n )\n\n const single: TrackedAnnotation | null =\n selected.length === 1 ? selected[0] : null\n const singleMeta = single ? getAnnotationMeta(single.object) : null\n const isWidget = single?.object.type === PdfAnnotationSubtype.WIDGET\n\n const title = isEditing\n ? selected.length > 1\n ? `${selected.length} annotations`\n : (singleMeta?.label ?? "Annotation")\n : activeTool\n ? `${activeTool.name} defaults`\n : "Properties"\n\n if (!isEditing && !activeTool) {\n return (\n <PdfEditorEmptyState\n glyph={SlidersGlyph}\n title="Nothing selected"\n description="Select an annotation on the page, or pick a tool to edit its default style."\n />\n )\n }\n\n const flags = single?.object.flags ?? []\n const contents =\n single && !isWidget && typeof single.object.contents === "string"\n ? single.object.contents\n : ""\n\n return (\n <div className="space-y-5 p-3">\n <div>\n <div className="text-sm font-medium text-foreground">{title}</div>\n <div className="text-xs text-muted-foreground">\n {isEditing\n ? structurallyLocked\n ? "This annotation is locked. Unlock it to make changes."\n : canEdit\n ? "Changes apply immediately."\n : "This document does not allow annotation changes."\n : "New annotations use these settings."}\n </div>\n </div>\n\n {configs.length > 0 ? (\n <PdfEditorSection title="Appearance">\n <fieldset\n disabled={isEditing && (!canEdit || structurallyLocked)}\n className="space-y-4 disabled:opacity-60"\n >\n {configs.map((config) => (\n <PropertyControl\n key={config.key + config.kind}\n config={config}\n values={values}\n colorPresets={colorPresets}\n onPatch={applyPatch}\n onRotate={isEditing ? applyRotation : undefined}\n />\n ))}\n </fieldset>\n </PdfEditorSection>\n ) : null}\n\n {single && isWidget ? (\n <WidgetProperties\n documentId={documentId}\n widget={single.object as PdfWidgetAnnoObject}\n />\n ) : null}\n\n {single && !isWidget ? (\n <PdfEditorSection title="Note">\n <NoteEditor\n key={single.object.id}\n value={contents}\n disabled={!canEdit}\n onChange={(next) =>\n annotation?.updateAnnotation(\n single.object.pageIndex,\n single.object.id,\n {\n contents: next,\n modified: new Date(),\n }\n )\n }\n />\n </PdfEditorSection>\n ) : null}\n\n {isEditing ? (\n <PdfEditorSection title="Behavior">\n <div className="space-y-0.5">\n {FLAG_OPTIONS.map((option) => {\n const checked = selected.every((item) =>\n (item.object.flags ?? []).includes(option.flag)\n )\n\n return (\n <PdfEditorCheckbox\n key={option.flag}\n checked={checked}\n disabled={!canEdit}\n onCheckedChange={(next) => {\n annotation?.updateAnnotations(\n selected.map((item) => {\n const current = item.object.flags ?? []\n const nextFlags = next\n ? current.includes(option.flag)\n ? current\n : [...current, option.flag]\n : current.filter((flag) => flag !== option.flag)\n\n return {\n pageIndex: item.object.pageIndex,\n id: item.object.id,\n patch: { flags: nextFlags },\n }\n })\n )\n }}\n label={option.label}\n description={option.description}\n />\n )\n })}\n </div>\n </PdfEditorSection>\n ) : null}\n\n {single ? (\n <PdfEditorSection title="Details">\n <dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs">\n <dt className="text-muted-foreground">Type</dt>\n <dd>{singleMeta?.label}</dd>\n <dt className="text-muted-foreground">Page</dt>\n <dd>{single.object.pageIndex + 1}</dd>\n <dt className="text-muted-foreground">Author</dt>\n <dd className="truncate">{single.object.author || "—"}</dd>\n <dt className="text-muted-foreground">Created</dt>\n <dd>{formatDateTime(single.object.created)}</dd>\n <dt className="text-muted-foreground">Modified</dt>\n <dd>{formatDateTime(single.object.modified)}</dd>\n {flags.length > 0 ? (\n <>\n <dt className="text-muted-foreground">Flags</dt>\n <dd className="truncate">{flags.join(", ")}</dd>\n </>\n ) : null}\n </dl>\n </PdfEditorSection>\n ) : null}\n </div>\n )\n}\n\nfunction NoteEditor({\n value,\n disabled,\n onChange,\n}: {\n value: string\n disabled?: boolean\n onChange: (value: string) => void\n}) {\n const [draft, setDraft] = React.useState(value)\n\n React.useEffect(() => {\n setDraft(value)\n }, [value])\n\n return (\n <textarea\n value={draft}\n disabled={disabled}\n rows={3}\n placeholder="Add a note…"\n onChange={(event) => setDraft(event.target.value)}\n onBlur={() => {\n if (draft !== value) onChange(draft)\n }}\n className={cn(\n "w-full resize-y rounded-lg border border-input bg-background px-2.5 py-2 text-sm outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60"\n )}\n />\n )\n}\n',+ },+ {+ fileName: "components/extend/pdf-editor-panels.tsx",+ code: '"use client"\n\nimport * as React from "react"\nimport { useDocumentState, useRegistry } from "@embedpdf/core/react"\nimport {\n PDF_FORM_FIELD_TYPE,\n PdfActionType,\n PdfAnnotationName,\n PdfAnnotationSubtype,\n PdfZoomMode,\n uuidV4,\n type PdfAttachmentObject,\n type PdfBookmarkObject,\n type PdfDestinationObject,\n type PdfWidgetAnnoObject,\n} from "@embedpdf/models"\nimport {\n getGroupLeaderId,\n getSelectedAnnotations,\n getSidebarAnnotationsWithRepliesGroupedByPage,\n useAnnotation,\n type SidebarAnnotationEntry,\n type TrackedAnnotation,\n} from "@embedpdf/plugin-annotation/react"\nimport { useAttachmentCapability } from "@embedpdf/plugin-attachment/react"\nimport { useBookmarkCapability } from "@embedpdf/plugin-bookmark/react"\nimport {\n useFormCapability,\n type FormFieldInfo,\n} from "@embedpdf/plugin-form/react"\nimport {\n useRedaction,\n type RedactionItem,\n} from "@embedpdf/plugin-redaction/react"\nimport { useScrollCapability } from "@embedpdf/plugin-scroll/react"\nimport {\n SignatureFieldKind,\n useActivePlacement,\n useSignatureEntries,\n} from "@embedpdf/plugin-signature/react"\nimport {\n StampImg,\n useActiveStamp,\n useStampCapability,\n useStampLibraries,\n useStampsByLibrary,\n type StampDefinition,\n} from "@embedpdf/plugin-stamp/react"\nimport {\n ThumbImg,\n useThumbnailPlugin,\n type ThumbMeta,\n type WindowState,\n} from "@embedpdf/plugin-thumbnail/react"\nimport type { degrees, ParseSpeeds, PDFDocument } from "pdf-lib"\n\nimport { cn } from "@/lib/utils"\nimport { Badge } from "@/components/ui/badge"\nimport { Button } from "@/components/ui/button"\nimport { Input } from "@/components/ui/input"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Spinner } from "@/components/ui/spinner"\nimport { getFormFieldTypeLabel } from "@/components/extend/pdf-editor-properties"\nimport {\n ArrowDownGlyph,\n ArrowUpGlyph,\n CheckGlyph,\n ChevronDownGlyph,\n ChevronRightGlyph,\n CommentsGlyph,\n downloadArrayBuffer,\n downloadBlob,\n DownloadGlyph,\n EditGlyph,\n EyeOffGlyph,\n FilePlusGlyph,\n formatBytes,\n formatRelativeDate,\n getAnnotationMeta,\n GridGlyph,\n ListTreeGlyph,\n MergeGlyph,\n PaperclipGlyph,\n PdfEditorCheckbox,\n PdfEditorEmptyState,\n PdfEditorScrollArea,\n PdfEditorSection,\n PdfEditorToolbarSeparator,\n PdfEditorToolButton,\n PlusGlyph,\n RedactAreaGlyph,\n RotateGlyph,\n ScissorsGlyph,\n SignatureGlyph,\n StampGlyph,\n TextFieldGlyph,\n toArrayBuffer,\n TrashGlyph,\n UploadGlyph,\n usePdfEditor,\n withFileNameSuffix,\n} from "@/components/extend/pdf-editor-shared"\n\n/* -------------------------------------------------------------------------- */\n/* Thumbnails */\n/* -------------------------------------------------------------------------- */\n\nconst THUMBNAIL_FOCUS_RING_CLASS =\n "group-focus-visible/pdf-editor-thumbnails:ring-2 group-focus-visible/pdf-editor-thumbnails:ring-ring group-focus-visible/pdf-editor-thumbnails:ring-offset-1 group-focus-visible/pdf-editor-thumbnails:ring-offset-background"\n\nexport function PdfEditorThumbnailsPanel({\n documentId,\n activePage,\n pageCount,\n onSelectPage,\n}: {\n documentId: string\n activePage: number\n pageCount: number\n onSelectPage: (pageNumber: number) => void\n}) {\n const { plugin: thumbnailPlugin } = useThumbnailPlugin()\n const listboxId = React.useId()\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const scope = React.useMemo(\n () => thumbnailPlugin?.provides().forDocument(documentId) ?? null,\n [documentId, thumbnailPlugin]\n )\n const windowState = React.useSyncExternalStore<WindowState | null>(\n React.useCallback(\n (onStoreChange) => {\n if (!scope) return () => undefined\n\n return scope.onWindow(() => onStoreChange())\n },\n [scope]\n ),\n React.useCallback(() => scope?.getWindow() ?? null, [scope]),\n () => null\n )\n const paddingY = thumbnailPlugin?.cfg.paddingY ?? 0\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !scope) return\n\n const updateWindow = () => {\n scope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n }\n\n updateWindow()\n viewport.addEventListener("scroll", updateWindow, { passive: true })\n const resizeObserver = new ResizeObserver(updateWindow)\n resizeObserver.observe(viewport)\n\n return () => {\n viewport.removeEventListener("scroll", updateWindow)\n resizeObserver.disconnect()\n }\n }, [scope])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !scope) return\n\n return scope.onScrollTo(({ top, behavior }) => {\n viewport.scrollTo({ top, behavior })\n })\n }, [scope])\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (pageCount < 1) return\n\n const currentPage = activePage > 0 ? activePage : 1\n let nextPage: number | null = null\n\n if (event.key === "ArrowDown")\n nextPage = Math.min(pageCount, currentPage + 1)\n else if (event.key === "ArrowUp") nextPage = Math.max(1, currentPage - 1)\n else if (event.key === "Home") nextPage = 1\n else if (event.key === "End") nextPage = pageCount\n\n if (nextPage === null) return\n\n event.preventDefault()\n onSelectPage(nextPage)\n },\n [activePage, onSelectPage, pageCount]\n )\n\n return (\n <PdfEditorScrollArea\n className="h-full w-full"\n viewportClassName="group/pdf-editor-thumbnails px-4 focus-visible:ring-0 focus-visible:ring-offset-0"\n viewportProps={{\n "aria-activedescendant":\n activePage > 0 ? `${listboxId}-page-${activePage}` : undefined,\n "aria-label": "Pages",\n onKeyDown: handleKeyDown,\n onMouseDown: (event) => {\n event.currentTarget.focus({ preventScroll: true })\n },\n role: "listbox",\n style: { paddingBottom: paddingY, paddingTop: paddingY },\n tabIndex: 0,\n }}\n viewportRef={viewportRef}\n >\n <div\n className="relative"\n style={{ height: windowState?.totalHeight ?? 0 }}\n >\n {windowState?.items.map((meta: ThumbMeta) => {\n const pageNumber = meta.pageIndex + 1\n const isActive = pageNumber === activePage\n const imagePadding = meta.padding ?? 0\n\n return (\n <div\n key={meta.pageIndex}\n className={cn(\n "absolute right-0 left-0 flex justify-center",\n isActive && "z-10"\n )}\n style={{ top: meta.top, height: meta.wrapperHeight }}\n >\n <div\n id={`${listboxId}-page-${pageNumber}`}\n role="option"\n aria-selected={isActive}\n aria-current={isActive ? "page" : undefined}\n aria-label={`Page ${pageNumber}`}\n className={cn(\n "flex h-full w-full cursor-default flex-col items-center justify-between rounded-md px-2 text-xs transition-shadow outline-none select-none hover:bg-sidebar-accent",\n isActive\n ? cn(\n "bg-sidebar-accent text-foreground",\n THUMBNAIL_FOCUS_RING_CLASS\n )\n : "text-muted-foreground"\n )}\n onClick={() => onSelectPage(pageNumber)}\n >\n <span\n className="flex items-center justify-center overflow-hidden rounded-md"\n style={{\n width: meta.width + imagePadding * 2,\n height: meta.height + imagePadding * 2,\n padding: imagePadding,\n }}\n >\n <ThumbImg\n documentId={documentId}\n meta={meta}\n className="block rounded-sm object-contain shadow-xs"\n style={{ width: meta.width, height: meta.height }}\n />\n </span>\n <span\n className="flex items-center justify-center tabular-nums"\n style={{ height: meta.labelHeight }}\n >\n {pageNumber}\n </span>\n </div>\n </div>\n )\n })}\n </div>\n </PdfEditorScrollArea>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Outline */\n/* -------------------------------------------------------------------------- */\n\nfunction resolveBookmarkDestination(bookmark: PdfBookmarkObject): {\n destination: PdfDestinationObject | null\n uri: string | null\n} {\n const target = bookmark.target\n\n if (!target) return { destination: null, uri: null }\n\n if (target.type === "destination") {\n return { destination: target.destination, uri: null }\n }\n\n const action = target.action\n\n if (\n action.type === PdfActionType.Goto ||\n action.type === PdfActionType.RemoteGoto\n ) {\n return { destination: action.destination, uri: null }\n }\n\n if (action.type === PdfActionType.URI) {\n return { destination: null, uri: action.uri }\n }\n\n return { destination: null, uri: null }\n}\n\nexport function PdfEditorOutlinePanel({ documentId }: { documentId: string }) {\n const { provides: bookmark } = useBookmarkCapability()\n const { provides: scroll } = useScrollCapability()\n const documentState = useDocumentState(documentId)\n const document = documentState?.document ?? null\n const [bookmarks, setBookmarks] = React.useState<PdfBookmarkObject[] | null>(\n null\n )\n const [expanded, setExpanded] = React.useState<Set<string>>(() => new Set())\n\n React.useEffect(() => {\n if (!bookmark || !document) return\n\n let cancelled = false\n const task = bookmark.forDocument(documentId).getBookmarks()\n\n task.wait(\n (result) => {\n if (cancelled) return\n\n setBookmarks(result.bookmarks)\n setExpanded(\n new Set(result.bookmarks.map((_, index) => `bookmark-${index}`))\n )\n },\n () => {\n if (!cancelled) setBookmarks([])\n }\n )\n\n return () => {\n cancelled = true\n }\n }, [bookmark, document, documentId])\n\n const navigate = React.useCallback(\n (item: PdfBookmarkObject) => {\n const { destination, uri } = resolveBookmarkDestination(item)\n\n if (uri) {\n window.open(uri, "_blank", "noopener")\n return\n }\n\n if (!destination || !scroll) return\n\n const scope = scroll.forDocument(documentId)\n const page = document?.pages[destination.pageIndex]\n\n if (destination.zoom.mode === PdfZoomMode.XYZ && page) {\n scope.scrollToPage({\n pageNumber: destination.pageIndex + 1,\n pageCoordinates: {\n x: destination.zoom.params.x,\n y: page.size.height - destination.zoom.params.y,\n },\n behavior: "smooth",\n })\n return\n }\n\n scope.scrollToPage({\n pageNumber: destination.pageIndex + 1,\n behavior: "smooth",\n })\n },\n [document, documentId, scroll]\n )\n\n if (bookmarks === null) {\n return (\n <div className="grid h-full place-items-center">\n <Spinner className="size-4" />\n </div>\n )\n }\n\n if (bookmarks.length === 0) {\n return (\n <PdfEditorEmptyState\n glyph={ListTreeGlyph}\n title="No outline"\n description="This document does not include bookmarks."\n />\n )\n }\n\n const renderBookmark = (\n item: PdfBookmarkObject,\n id: string,\n level: number\n ): React.ReactNode => {\n const hasChildren = Boolean(item.children && item.children.length > 0)\n const isExpanded = expanded.has(id)\n\n return (\n <div key={id}>\n <div\n className="group flex cursor-default items-center gap-1 rounded-md py-1 pr-2 text-sm hover:bg-sidebar-accent"\n style={{ paddingLeft: level * 12 + 4 }}\n >\n {hasChildren ? (\n <button\n type="button"\n aria-label={isExpanded ? "Collapse" : "Expand"}\n className="grid size-5 shrink-0 place-items-center rounded text-muted-foreground hover:text-foreground"\n onClick={(event) => {\n event.stopPropagation()\n setExpanded((previous) => {\n const next = new Set(previous)\n if (next.has(id)) next.delete(id)\n else next.add(id)\n return next\n })\n }}\n >\n {isExpanded ? (\n <ChevronDownGlyph className="size-3.5" />\n ) : (\n <ChevronRightGlyph className="size-3.5" />\n )}\n </button>\n ) : (\n <span className="size-5 shrink-0" />\n )}\n <button\n type="button"\n className="min-w-0 flex-1 truncate text-left text-foreground/90 outline-none"\n onClick={() => navigate(item)}\n >\n {item.title || "Untitled"}\n </button>\n </div>\n {hasChildren && isExpanded\n ? item.children?.map((child, index) =>\n renderBookmark(child, `${id}-${index}`, level + 1)\n )\n : null}\n </div>\n )\n }\n\n return (\n <PdfEditorScrollArea className="h-full w-full" viewportClassName="p-2">\n {bookmarks.map((item, index) =>\n renderBookmark(item, `bookmark-${index}`, 0)\n )}\n </PdfEditorScrollArea>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Attachments */\n/* -------------------------------------------------------------------------- */\n\nexport function PdfEditorAttachmentsPanel({\n documentId,\n}: {\n documentId: string\n}) {\n const { provides: attachment } = useAttachmentCapability()\n const { registry } = useRegistry()\n const documentState = useDocumentState(documentId)\n const { notify, permissions } = usePdfEditor()\n const document = documentState?.document ?? null\n const [attachments, setAttachments] = React.useState<\n PdfAttachmentObject[] | null\n >(null)\n const [version, setVersion] = React.useState(0)\n const [busy, setBusy] = React.useState(false)\n const inputRef = React.useRef<HTMLInputElement>(null)\n\n React.useEffect(() => {\n if (!attachment || !document) return\n\n let cancelled = false\n\n attachment\n .forDocument(documentId)\n .getAttachments()\n .wait(\n (result) => {\n if (!cancelled) setAttachments(result)\n },\n () => {\n if (!cancelled) setAttachments([])\n }\n )\n\n return () => {\n cancelled = true\n }\n }, [attachment, document, documentId, version])\n\n const refresh = () => setVersion((value) => value + 1)\n\n const handleDownload = (item: PdfAttachmentObject) => {\n attachment\n ?.forDocument(documentId)\n .downloadAttachment(item)\n .wait(\n (buffer) =>\n downloadArrayBuffer(\n buffer,\n item.name,\n item.mimeType || "application/octet-stream"\n ),\n () => notify("The attachment could not be downloaded.", "error")\n )\n }\n\n const handleRemove = (item: PdfAttachmentObject) => {\n if (!registry || !document) return\n\n setBusy(true)\n registry\n .getEngine()\n .removeAttachment(document, item)\n .wait(\n () => {\n setBusy(false)\n refresh()\n notify("Attachment removed.", "success")\n },\n () => {\n setBusy(false)\n notify("The attachment could not be removed.", "error")\n }\n )\n }\n\n const handleAdd = async (file: File) => {\n if (!registry || !document) return\n\n setBusy(true)\n\n try {\n const data = await file.arrayBuffer()\n\n registry\n .getEngine()\n .addAttachment(document, {\n name: file.name,\n description: "",\n mimeType: file.type || "application/octet-stream",\n data,\n })\n .wait(\n () => {\n setBusy(false)\n refresh()\n notify("Attachment added.", "success")\n },\n () => {\n setBusy(false)\n notify("The attachment could not be added.", "error")\n }\n )\n } catch {\n setBusy(false)\n notify("The file could not be read.", "error")\n }\n }\n\n const canModify = permissions.canModifyContents && !busy\n\n return (\n <div className="flex h-full flex-col">\n <div className="flex shrink-0 items-center gap-2 border-b px-3 py-2">\n <input\n ref={inputRef}\n type="file"\n className="sr-only"\n tabIndex={-1}\n onChange={(event) => {\n const file = event.target.files?.[0]\n if (file) void handleAdd(file)\n event.currentTarget.value = ""\n }}\n />\n <Button\n type="button"\n size="sm"\n variant="outline"\n disabled={!canModify}\n onClick={() => inputRef.current?.click()}\n >\n <PlusGlyph className="size-4" />\n Attach file\n </Button>\n {busy ? <Spinner className="size-4" /> : null}\n </div>\n {attachments === null ? (\n <div className="grid flex-1 place-items-center">\n <Spinner className="size-4" />\n </div>\n ) : attachments.length === 0 ? (\n <PdfEditorEmptyState\n glyph={PaperclipGlyph}\n title="No attachments"\n description="Files embedded in the PDF appear here."\n />\n ) : (\n <PdfEditorScrollArea className="min-h-0 flex-1" viewportClassName="p-2">\n <div className="space-y-1">\n {attachments.map((item) => (\n <div\n key={`${item.index}-${item.name}`}\n className="flex items-center gap-2 rounded-lg border px-2.5 py-2"\n >\n <div className="grid size-8 shrink-0 place-items-center rounded-md bg-muted text-muted-foreground">\n <PaperclipGlyph className="size-4" />\n </div>\n <div className="min-w-0 flex-1">\n <div className="truncate text-sm font-medium">\n {item.name}\n </div>\n <div className="truncate text-xs text-muted-foreground">\n {[item.mimeType, formatBytes(item.size), item.description]\n .filter(Boolean)\n .join(" · ")}\n </div>\n </div>\n <PdfEditorToolButton\n label="Download"\n size="icon-xs"\n onClick={() => handleDownload(item)}\n >\n <DownloadGlyph className="size-3.5" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Remove"\n size="icon-xs"\n disabled={!canModify}\n onClick={() => handleRemove(item)}\n >\n <TrashGlyph className="size-3.5" />\n </PdfEditorToolButton>\n </div>\n ))}\n </div>\n </PdfEditorScrollArea>\n )}\n </div>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Pages (organizer) */\n/* -------------------------------------------------------------------------- */\n\nconst PAGE_TILE_WIDTH = 76\n\ntype PdfLibModule = {\n PDFDocument: typeof PDFDocument\n ParseSpeeds: typeof ParseSpeeds\n degrees: typeof degrees\n}\n\nlet pdfLibPromise: Promise<PdfLibModule> | null = null\n\nfunction loadPdfLib() {\n pdfLibPromise ??= import("pdf-lib")\n return pdfLibPromise\n}\n\nexport function PdfEditorPagesPanel({\n documentId,\n activePage,\n}: {\n documentId: string\n activePage: number\n}) {\n const { registry } = useRegistry()\n const documentState = useDocumentState(documentId)\n const { state: annotationState, provides: annotation } =\n useAnnotation(documentId)\n const {\n fileName,\n getDocumentBuffer,\n notify,\n openDialog,\n permissions,\n replaceDocument,\n scrollToPage,\n } = usePdfEditor()\n const document = documentState?.document ?? null\n const pages = React.useMemo(() => document?.pages ?? [], [document])\n const [selected, setSelected] = React.useState<Set<number>>(() => new Set())\n const [busy, setBusy] = React.useState<string | null>(null)\n const anchorRef = React.useRef<number | null>(null)\n const appendInputRef = React.useRef<HTMLInputElement>(null)\n\n React.useEffect(() => {\n void loadPdfLib()\n }, [])\n\n const metas = React.useMemo<ThumbMeta[]>(\n () =>\n pages.map((page) => {\n const height = Math.max(\n 1,\n Math.round(PAGE_TILE_WIDTH * (page.size.height / page.size.width))\n )\n\n return {\n pageIndex: page.index,\n width: PAGE_TILE_WIDTH,\n height,\n wrapperHeight: height,\n top: 0,\n labelHeight: 0,\n padding: 0,\n }\n }),\n [pages]\n )\n\n const selectedIndices = React.useMemo(\n () => [...selected].sort((a, b) => a - b),\n [selected]\n )\n const isEncrypted = document?.isEncrypted ?? false\n const canAssemble =\n permissions.canAssembleDocument && !isEncrypted && busy === null\n const hasSelection = selectedIndices.length > 0\n const isContiguous =\n hasSelection &&\n selectedIndices[selectedIndices.length - 1] - selectedIndices[0] ===\n selectedIndices.length - 1\n\n const select = (pageIndex: number, mode: "replace" | "toggle" | "range") => {\n setSelected((previous) => {\n if (mode === "range" && anchorRef.current !== null) {\n const start = Math.min(anchorRef.current, pageIndex)\n const end = Math.max(anchorRef.current, pageIndex)\n const next = new Set<number>()\n for (let index = start; index <= end; index += 1) next.add(index)\n return next\n }\n\n if (mode === "toggle") {\n const next = new Set(previous)\n if (next.has(pageIndex)) next.delete(pageIndex)\n else next.add(pageIndex)\n anchorRef.current = pageIndex\n return next\n }\n\n anchorRef.current = pageIndex\n return new Set([pageIndex])\n })\n }\n\n const runOperation = async (\n label: string,\n mutate: (doc: PDFDocument, lib: PdfLibModule) => Promise<void> | void,\n options: { replace?: boolean } = { replace: true }\n ) => {\n setBusy(label)\n\n try {\n const [buffer, lib] = await Promise.all([\n getDocumentBuffer(),\n loadPdfLib(),\n ])\n const doc = await lib.PDFDocument.load(buffer, {\n ignoreEncryption: true,\n parseSpeed: lib.ParseSpeeds.Fastest,\n updateMetadata: false,\n })\n\n await mutate(doc, lib)\n\n if (options.replace !== false) {\n const bytes = await doc.save({ objectsPerTick: 500 })\n replaceDocument(toArrayBuffer(bytes), fileName)\n notify(`${label} applied.`, "success")\n }\n } catch (error) {\n console.error(error)\n notify(`${label} failed.`, "error")\n } finally {\n setBusy(null)\n }\n }\n\n const rotateSelected = (delta: 90 | -90) =>\n runOperation("Rotate pages", (doc, lib) => {\n for (const index of selectedIndices) {\n const page = doc.getPage(index)\n page.setRotation(\n lib.degrees((page.getRotation().angle + delta + 360) % 360)\n )\n }\n })\n\n const deleteSelected = () => {\n if (selectedIndices.length >= pages.length) {\n notify("A document needs at least one page.", "error")\n return\n }\n\n openDialog({\n type: "confirm",\n title: `Delete ${selectedIndices.length === 1 ? "this page" : `${selectedIndices.length} pages`}?`,\n description:\n "Content and annotations on the deleted pages are removed permanently.",\n confirmLabel: "Delete",\n destructive: true,\n onConfirm: async () => {\n setBusy("Delete pages")\n\n try {\n if (!registry || !document) {\n throw new Error("The document is not ready.")\n }\n\n if (annotation && annotationState.hasPendingChanges) {\n await annotation.commit().toPromise()\n }\n\n const engine = registry.getEngine()\n\n for (const index of [...selectedIndices].reverse()) {\n await engine.deletePage(document, index).toPromise()\n }\n\n const buffer = await engine.saveAsCopy(document).toPromise()\n replaceDocument(buffer, fileName)\n notify("Delete pages applied.", "success")\n } catch (error) {\n console.error(error)\n notify("Delete pages failed.", "error")\n } finally {\n setBusy(null)\n }\n },\n })\n }\n\n const moveSelected = (direction: -1 | 1) => {\n const first = selectedIndices[0]\n const last = selectedIndices[selectedIndices.length - 1]\n\n if (direction === -1 && first === 0) return\n if (direction === 1 && last === pages.length - 1) return\n\n void runOperation("Move pages", (doc) => {\n // pdf-lib has no move API: detach the neighbouring page from the page\n // tree and re-insert it on the other side of the selected block.\n if (direction === -1) {\n const page = doc.getPage(first - 1)\n doc.removePage(first - 1)\n doc.insertPage(last, page)\n } else {\n const page = doc.getPage(last + 1)\n doc.removePage(last + 1)\n doc.insertPage(first, page)\n }\n })\n }\n\n const insertBlankAfter = () => {\n const referenceIndex = hasSelection\n ? selectedIndices[selectedIndices.length - 1]\n : Math.max(0, activePage - 1)\n\n void runOperation("Insert page", (doc) => {\n const reference = doc.getPage(referenceIndex)\n const { width, height } = reference.getSize()\n doc.insertPage(referenceIndex + 1, [width, height])\n })\n }\n\n const extractSelected = () =>\n runOperation(\n "Extract pages",\n async (doc, lib) => {\n const output = await lib.PDFDocument.create()\n const copied = await output.copyPages(doc, selectedIndices)\n copied.forEach((page) => output.addPage(page))\n const bytes = await output.save()\n downloadArrayBuffer(bytes, withFileNameSuffix(fileName, "-pages"))\n notify(\n `Extracted ${selectedIndices.length} page${selectedIndices.length === 1 ? "" : "s"}.`,\n "success"\n )\n },\n { replace: false }\n )\n\n const appendFile = (file: File) =>\n runOperation("Append PDF", async (doc, lib) => {\n const source = await lib.PDFDocument.load(await file.arrayBuffer(), {\n ignoreEncryption: true,\n parseSpeed: lib.ParseSpeeds.Fastest,\n updateMetadata: false,\n })\n const copied = await doc.copyPages(source, source.getPageIndices())\n copied.forEach((page) => doc.addPage(page))\n })\n\n return (\n <div className="flex h-full flex-col">\n <div className="flex shrink-0 flex-wrap items-center gap-0.5 border-b px-2 py-1.5">\n <PdfEditorToolButton\n label="Rotate left"\n disabled={!canAssemble || !hasSelection}\n onClick={() => rotateSelected(-90)}\n >\n <RotateGlyph className="size-4 -scale-x-100" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Rotate right"\n disabled={!canAssemble || !hasSelection}\n onClick={() => rotateSelected(90)}\n >\n <RotateGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolbarSeparator />\n <PdfEditorToolButton\n label="Move up"\n disabled={!canAssemble || !isContiguous || selectedIndices[0] === 0}\n onClick={() => moveSelected(-1)}\n >\n <ArrowUpGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Move down"\n disabled={\n !canAssemble ||\n !isContiguous ||\n selectedIndices[selectedIndices.length - 1] === pages.length - 1\n }\n onClick={() => moveSelected(1)}\n >\n <ArrowDownGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolbarSeparator />\n <PdfEditorToolButton\n label="Insert blank page after"\n disabled={!canAssemble}\n onClick={insertBlankAfter}\n >\n <FilePlusGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Append PDF"\n disabled={!canAssemble}\n onClick={() => appendInputRef.current?.click()}\n >\n <MergeGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Extract selected pages"\n disabled={busy !== null || !hasSelection}\n onClick={() => void extractSelected()}\n >\n <ScissorsGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Delete pages"\n disabled={!canAssemble || !hasSelection}\n onClick={deleteSelected}\n >\n <TrashGlyph className="size-4" />\n </PdfEditorToolButton>\n <input\n ref={appendInputRef}\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) void appendFile(file)\n event.currentTarget.value = ""\n }}\n />\n </div>\n <div className="flex shrink-0 items-center justify-between gap-2 border-b px-3 py-1.5 text-xs text-muted-foreground">\n <span>\n {hasSelection\n ? `${selectedIndices.length} of ${pages.length} selected`\n : `${pages.length} page${pages.length === 1 ? "" : "s"}`}\n </span>\n {busy ? (\n <span className="flex items-center gap-1.5">\n <Spinner className="size-3" />\n {busy}…\n </span>\n ) : isEncrypted ? (\n <span>Remove protection to edit pages.</span>\n ) : hasSelection ? (\n <button\n type="button"\n className="underline-offset-2 hover:underline"\n onClick={() => setSelected(new Set())}\n >\n Clear\n </button>\n ) : null}\n </div>\n <PdfEditorScrollArea\n className="min-h-0 flex-1"\n viewportClassName="px-2.5 py-3"\n >\n <div className="grid grid-cols-2 gap-2">\n {metas.map((meta) => {\n const pageNumber = meta.pageIndex + 1\n const isSelected = selected.has(meta.pageIndex)\n const isActive = pageNumber === activePage\n\n return (\n <button\n key={meta.pageIndex}\n type="button"\n aria-pressed={isSelected}\n className={cn(\n "group flex min-w-0 flex-col items-center gap-1.5 rounded-lg border p-1.5 text-xs transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",\n isSelected\n ? "border-primary bg-primary/5 ring-1 ring-primary/20"\n : "border-transparent hover:bg-sidebar-accent",\n isActive && !isSelected && "border-border"\n )}\n onClick={(event) => {\n select(\n meta.pageIndex,\n event.shiftKey\n ? "range"\n : event.metaKey || event.ctrlKey\n ? "toggle"\n : "replace"\n )\n }}\n onDoubleClick={() => scrollToPage(pageNumber)}\n >\n <span\n className={cn(\n "grid place-items-center rounded-md border p-1 transition-colors",\n isSelected\n ? "border-primary/40 bg-primary/5"\n : "border-border/60 bg-muted/30"\n )}\n >\n <span\n className="grid place-items-center overflow-hidden rounded-sm bg-white shadow-xs"\n style={{ width: meta.width, height: meta.height }}\n >\n <ThumbImg\n documentId={documentId}\n meta={meta}\n className="block object-contain"\n style={{ width: meta.width, height: meta.height }}\n />\n </span>\n </span>\n <span\n className={cn(\n "tabular-nums",\n isSelected ? "text-foreground" : "text-muted-foreground"\n )}\n >\n {pageNumber}\n </span>\n </button>\n )\n })}\n </div>\n </PdfEditorScrollArea>\n </div>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Comments */\n/* -------------------------------------------------------------------------- */\n\nfunction CommentComposer({\n placeholder,\n initialValue = "",\n autoFocus,\n submitLabel = "Save",\n onSubmit,\n onCancel,\n}: {\n placeholder: string\n initialValue?: string\n autoFocus?: boolean\n submitLabel?: string\n onSubmit: (value: string) => void\n onCancel?: () => void\n}) {\n const [value, setValue] = React.useState(initialValue)\n\n return (\n <div className="space-y-1.5">\n <textarea\n value={value}\n autoFocus={autoFocus}\n rows={2}\n placeholder={placeholder}\n onChange={(event) => setValue(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {\n event.preventDefault()\n if (value.trim()) onSubmit(value.trim())\n }\n\n if (event.key === "Escape") onCancel?.()\n }}\n className="w-full resize-none rounded-md border border-input bg-background px-2 py-1.5 text-sm outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring"\n />\n <div className="flex justify-end gap-1">\n {onCancel ? (\n <Button type="button" size="xs" variant="ghost" onClick={onCancel}>\n Cancel\n </Button>\n ) : null}\n <Button\n type="button"\n size="xs"\n disabled={!value.trim()}\n onClick={() => onSubmit(value.trim())}\n >\n {submitLabel}\n </Button>\n </div>\n </div>\n )\n}\n\nfunction CommentCard({\n entry,\n isSelected,\n readOnly,\n onSelect,\n onUpdate,\n onDelete,\n onReply,\n}: {\n entry: SidebarAnnotationEntry\n isSelected: boolean\n readOnly: boolean\n onSelect: () => void\n onUpdate: (annotation: TrackedAnnotation, contents: string) => void\n onDelete: (annotation: TrackedAnnotation) => void\n onReply: (annotation: TrackedAnnotation, contents: string) => void\n}) {\n const { annotation, replies } = entry\n const [isEditing, setIsEditing] = React.useState(false)\n const [isReplying, setIsReplying] = React.useState(false)\n const meta = getAnnotationMeta(annotation.object)\n const contents =\n typeof annotation.object.contents === "string"\n ? annotation.object.contents\n : ""\n const quotedText =\n annotation.object.custom &&\n typeof annotation.object.custom === "object" &&\n typeof (annotation.object.custom as { text?: unknown }).text === "string"\n ? ((annotation.object.custom as { text: string }).text as string)\n : null\n const Glyph = meta.glyph\n\n return (\n <div\n role="button"\n tabIndex={0}\n onClick={onSelect}\n onKeyDown={(event) => {\n if (event.key === "Enter") onSelect()\n }}\n className={cn(\n "rounded-lg border bg-background p-3 text-left shadow-xs transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring",\n isSelected\n ? "border-primary ring-1 ring-primary/40"\n : "hover:bg-accent/40"\n )}\n >\n <div className="flex items-start gap-2">\n <span\n className="grid size-7 shrink-0 place-items-center rounded-full bg-muted"\n style={meta.color ? { color: meta.color } : undefined}\n >\n <Glyph className="size-3.5" />\n </span>\n <div className="min-w-0 flex-1">\n <div className="flex items-center justify-between gap-2">\n <div className="min-w-0">\n <div className="truncate text-sm font-medium">\n {annotation.object.author || "Guest"}\n </div>\n <div className="text-[11px] text-muted-foreground">\n {meta.label} · page {annotation.object.pageIndex + 1}\n {annotation.object.modified || annotation.object.created\n ? ` · ${formatRelativeDate(annotation.object.modified ?? annotation.object.created)}`\n : ""}\n </div>\n </div>\n {!readOnly ? (\n <div className="flex shrink-0 items-center gap-0.5">\n <PdfEditorToolButton\n label={contents ? "Edit comment" : "Add comment"}\n size="icon-xs"\n onClick={(event) => {\n event.stopPropagation()\n setIsEditing(true)\n }}\n >\n <EditGlyph className="size-3.5" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Delete"\n size="icon-xs"\n onClick={(event) => {\n event.stopPropagation()\n onDelete(annotation)\n }}\n >\n <TrashGlyph className="size-3.5" />\n </PdfEditorToolButton>\n </div>\n ) : null}\n </div>\n {quotedText ? (\n <blockquote className="mt-1.5 line-clamp-3 border-l-2 pl-2 text-xs text-muted-foreground italic">\n {quotedText}\n </blockquote>\n ) : null}\n {isEditing ? (\n <div className="mt-2" onClick={(event) => event.stopPropagation()}>\n <CommentComposer\n placeholder="Write a comment…"\n initialValue={contents}\n autoFocus\n onSubmit={(value) => {\n onUpdate(annotation, value)\n setIsEditing(false)\n }}\n onCancel={() => setIsEditing(false)}\n />\n </div>\n ) : contents ? (\n <p className="mt-1.5 text-sm whitespace-pre-wrap">{contents}</p>\n ) : (\n <p className="mt-1.5 text-xs text-muted-foreground">\n No comment yet.\n </p>\n )}\n </div>\n </div>\n {replies.length > 0 ? (\n <div className="mt-2 space-y-2 border-l pl-3">\n {replies.map((reply) => (\n <div key={reply.object.id} className="text-sm">\n <div className="flex items-center justify-between gap-2">\n <span className="text-xs font-medium">\n {reply.object.author || "Guest"}\n <span className="ml-1.5 font-normal text-muted-foreground">\n {formatRelativeDate(\n reply.object.modified ?? reply.object.created\n )}\n </span>\n </span>\n {!readOnly ? (\n <PdfEditorToolButton\n label="Delete reply"\n size="icon-xs"\n onClick={(event) => {\n event.stopPropagation()\n onDelete(reply)\n }}\n >\n <TrashGlyph className="size-3" />\n </PdfEditorToolButton>\n ) : null}\n </div>\n <p className="whitespace-pre-wrap">{reply.object.contents}</p>\n </div>\n ))}\n </div>\n ) : null}\n {!readOnly ? (\n <div className="mt-2" onClick={(event) => event.stopPropagation()}>\n {isReplying ? (\n <CommentComposer\n placeholder="Reply…"\n autoFocus\n submitLabel="Reply"\n onSubmit={(value) => {\n onReply(annotation, value)\n setIsReplying(false)\n }}\n onCancel={() => setIsReplying(false)}\n />\n ) : (\n <Button\n type="button"\n size="xs"\n variant="ghost"\n className="text-muted-foreground"\n onClick={() => setIsReplying(true)}\n >\n Reply\n </Button>\n )}\n </div>\n ) : null}\n </div>\n )\n}\n\nexport function PdfEditorCommentsPanel({ documentId }: { documentId: string }) {\n const { provides: annotation, state } = useAnnotation(documentId)\n const { annotationAuthor, permissions, scrollToAnnotation } = usePdfEditor()\n const grouped = React.useMemo(\n () => getSidebarAnnotationsWithRepliesGroupedByPage(state),\n [state]\n )\n const selectedLeaderIds = React.useMemo(() => {\n const ids = new Set<string>()\n\n for (const item of getSelectedAnnotations(state)) {\n ids.add(getGroupLeaderId(state, item.object.id) ?? item.object.id)\n }\n\n return ids\n }, [state])\n const pageNumbers = React.useMemo(\n () =>\n Object.keys(grouped)\n .map(Number)\n .sort((a, b) => a - b),\n [grouped]\n )\n const readOnly = !permissions.canModifyAnnotations\n const cardRefs = React.useRef<Map<string, HTMLDivElement>>(new Map())\n const firstSelectedId = selectedLeaderIds.values().next().value\n\n React.useEffect(() => {\n if (!firstSelectedId) return\n\n const element = cardRefs.current.get(firstSelectedId)\n element?.scrollIntoView({ block: "nearest", behavior: "smooth" })\n }, [firstSelectedId])\n\n if (pageNumbers.length === 0) {\n return (\n <PdfEditorEmptyState\n glyph={CommentsGlyph}\n title="No comments yet"\n description="Annotations and notes you add to the document show up here."\n />\n )\n }\n\n return (\n <PdfEditorScrollArea className="h-full w-full" viewportClassName="p-3">\n <div className="space-y-5">\n {pageNumbers.map((pageIndex) => (\n <div key={pageIndex} className="space-y-2">\n <div className="text-xs font-medium text-muted-foreground">\n Page {pageIndex + 1}\n </div>\n <div className="space-y-2">\n {grouped[pageIndex].map((entry) => (\n <div\n key={entry.annotation.object.id}\n ref={(element) => {\n if (element) {\n cardRefs.current.set(entry.annotation.object.id, element)\n } else {\n cardRefs.current.delete(entry.annotation.object.id)\n }\n }}\n >\n <CommentCard\n entry={entry}\n isSelected={selectedLeaderIds.has(\n entry.annotation.object.id\n )}\n readOnly={readOnly}\n onSelect={() => {\n annotation?.selectAnnotation(\n entry.annotation.object.pageIndex,\n entry.annotation.object.id\n )\n scrollToAnnotation(entry.annotation.object)\n }}\n onUpdate={(item, contents) =>\n annotation?.updateAnnotation(\n item.object.pageIndex,\n item.object.id,\n {\n contents,\n modified: new Date(),\n }\n )\n }\n onDelete={(item) =>\n annotation?.deleteAnnotation(\n item.object.pageIndex,\n item.object.id\n )\n }\n onReply={(parent, contents) =>\n annotation?.createAnnotation(parent.object.pageIndex, {\n id: uuidV4(),\n type: PdfAnnotationSubtype.TEXT,\n pageIndex: parent.object.pageIndex,\n rect: {\n origin: {\n x: parent.object.rect.origin.x,\n y: parent.object.rect.origin.y,\n },\n size: { width: 24, height: 24 },\n },\n contents,\n inReplyToId: parent.object.id,\n flags: ["noRotate", "noZoom", "print"],\n name: PdfAnnotationName.Comment,\n author: annotationAuthor,\n created: new Date(),\n modified: new Date(),\n })\n }\n />\n </div>\n ))}\n </div>\n </div>\n ))}\n </div>\n </PdfEditorScrollArea>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Redactions */\n/* -------------------------------------------------------------------------- */\n\nexport function PdfEditorRedactionsPanel({\n documentId,\n}: {\n documentId: string\n}) {\n const { state, provides } = useRedaction(documentId)\n const { provides: scroll } = useScrollCapability()\n const { openDialog, permissions, notify } = usePdfEditor()\n const items = React.useMemo(\n () =>\n Object.entries(state.pending)\n .flatMap(([page, pageItems]) =>\n pageItems.map((item) => ({ item, pageNumber: Number(page) + 1 }))\n )\n .sort((a, b) => a.pageNumber - b.pageNumber),\n [state.pending]\n )\n const [isApplying, setIsApplying] = React.useState(false)\n const canApply = permissions.canModifyContents && !isApplying\n\n const selectItem = (item: RedactionItem) => {\n provides?.selectPending(item.page, item.id)\n scroll?.forDocument(documentId).scrollToPage({\n pageNumber: item.page + 1,\n pageCoordinates: { x: item.rect.origin.x, y: item.rect.origin.y },\n alignX: 50,\n alignY: 25,\n behavior: "smooth",\n })\n }\n\n const applyAll = () =>\n openDialog({\n type: "confirm",\n title: `Apply ${items.length} redaction${items.length === 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 if (!provides) return\n\n setIsApplying(true)\n provides.commitAllPending().wait(\n () => setIsApplying(false),\n () => {\n setIsApplying(false)\n notify("The redactions could not be applied.", "error")\n }\n )\n },\n })\n\n const applyOne = (item: RedactionItem) =>\n openDialog({\n type: "confirm",\n title: "Apply this redaction?",\n description: "The marked content is removed permanently.",\n confirmLabel: "Apply",\n onConfirm: () => {\n provides?.commitPending(item.page, item.id).wait(\n () => undefined,\n () => notify("The redaction could not be applied.", "error")\n )\n },\n })\n\n return (\n <div className="flex h-full flex-col">\n {items.length === 0 ? (\n <PdfEditorEmptyState\n glyph={EyeOffGlyph}\n title="No pending redactions"\n description="Use the Redact tools to mark text or areas. Marks stay editable until you apply them."\n />\n ) : (\n <PdfEditorScrollArea className="min-h-0 flex-1" viewportClassName="p-2">\n <div className="space-y-1.5">\n {items.map(({ item, pageNumber }) => {\n const isSelected = state.selected?.id === item.id\n const Glyph = item.kind === "text" ? EyeOffGlyph : RedactAreaGlyph\n\n return (\n <div\n key={item.id}\n role="button"\n tabIndex={0}\n onClick={() => selectItem(item)}\n onKeyDown={(event) => {\n if (event.key === "Enter") selectItem(item)\n }}\n className={cn(\n "flex items-start gap-2 rounded-lg border px-2.5 py-2 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring",\n isSelected\n ? "border-primary ring-1 ring-primary/40"\n : "hover:bg-accent/40"\n )}\n >\n <span\n className="mt-0.5 grid size-6 shrink-0 place-items-center rounded-md"\n style={{\n backgroundColor: `${item.markColor}22`,\n color: item.markColor,\n }}\n >\n <Glyph className="size-3.5" />\n </span>\n <div className="min-w-0 flex-1">\n <div className="text-sm font-medium">\n {item.kind === "text" ? "Text" : "Area"}\n <span className="ml-1.5 text-xs font-normal text-muted-foreground">\n page {pageNumber}\n </span>\n </div>\n {item.kind === "text" && item.text ? (\n <div className="truncate text-xs text-muted-foreground italic">\n “{item.text}”\n </div>\n ) : null}\n </div>\n <div className="flex shrink-0 items-center gap-0.5">\n <PdfEditorToolButton\n label="Apply"\n size="icon-xs"\n disabled={!canApply}\n onClick={(event) => {\n event.stopPropagation()\n applyOne(item)\n }}\n >\n <CheckGlyph className="size-3.5" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Remove mark"\n size="icon-xs"\n onClick={(event) => {\n event.stopPropagation()\n provides?.removePending(item.page, item.id)\n }}\n >\n <TrashGlyph className="size-3.5" />\n </PdfEditorToolButton>\n </div>\n </div>\n )\n })}\n </div>\n </PdfEditorScrollArea>\n )}\n {items.length > 0 ? (\n <div className="flex shrink-0 gap-2 border-t p-2">\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="flex-1"\n disabled={isApplying}\n onClick={() => provides?.clearPending()}\n >\n Clear all\n </Button>\n <Button\n type="button"\n size="sm"\n className="flex-1"\n loading={isApplying}\n disabled={!canApply}\n onClick={applyAll}\n >\n Apply all\n </Button>\n </div>\n ) : null}\n </div>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Stamps */\n/* -------------------------------------------------------------------------- */\n\nconst CUSTOM_STAMP_LIBRARY_ID = "custom"\nconst STAMP_THUMB_WIDTH = 120\nconst UNSUPPORTED_STAMP_SOURCE_TYPES = new Set<PdfAnnotationSubtype>([\n PdfAnnotationSubtype.REDACT,\n PdfAnnotationSubtype.HIGHLIGHT,\n PdfAnnotationSubtype.SQUIGGLY,\n PdfAnnotationSubtype.UNDERLINE,\n PdfAnnotationSubtype.STRIKEOUT,\n PdfAnnotationSubtype.CARET,\n PdfAnnotationSubtype.WIDGET,\n PdfAnnotationSubtype.LINK,\n])\n\nexport function PdfEditorStampsPanel({ documentId }: { documentId: string }) {\n const { libraries } = useStampLibraries()\n const { provides: stampCapability } = useStampCapability()\n const { provides: annotation, state: annotationState } =\n useAnnotation(documentId)\n const { notify, permissions } = usePdfEditor()\n const [libraryId, setLibraryId] = React.useState("all")\n const stamps = useStampsByLibrary(libraryId === "all" ? undefined : libraryId)\n const activeStamp = useActiveStamp(documentId)\n const [busy, setBusy] = React.useState(false)\n const importInputRef = React.useRef<HTMLInputElement>(null)\n const selected = React.useMemo(\n () => getSelectedAnnotations(annotationState),\n [annotationState]\n )\n const canCreateFromSelection =\n selected.length === 1 &&\n !UNSUPPORTED_STAMP_SOURCE_TYPES.has(selected[0].object.type)\n const customLibrary = libraries.find(\n (library) => library.id === CUSTOM_STAMP_LIBRARY_ID\n )\n const libraryOptions = [\n { label: "All libraries", value: "all" },\n ...libraries.map((library) => ({\n label: library.name,\n value: library.id,\n })),\n ]\n\n React.useEffect(() => {\n if (\n libraryId !== "all" &&\n !libraries.some((library) => library.id === libraryId)\n ) {\n setLibraryId("all")\n }\n }, [libraries, libraryId])\n\n const placeStamp = (targetLibraryId: string, stamp: StampDefinition) => {\n if (!stampCapability) return\n\n const isActive =\n activeStamp?.libraryId === targetLibraryId &&\n activeStamp.stamp.id === stamp.id\n\n if (isActive) {\n annotation?.setActiveTool(null)\n return\n }\n\n stampCapability\n .forDocument(documentId)\n .activateStampPlacement(targetLibraryId, stamp)\n .wait(\n () => undefined,\n () => notify("The stamp could not be activated.", "error")\n )\n }\n\n const createFromSelection = () => {\n if (!stampCapability || !canCreateFromSelection) return\n\n const count = customLibrary?.stamps.length ?? 0\n\n setBusy(true)\n stampCapability\n .forDocument(documentId)\n .createStampFromAnnotation(\n selected[0].object,\n {\n name: PdfAnnotationName.Custom,\n subject: `Custom stamp ${count + 1}`,\n categories: ["custom", "sidebar"],\n },\n CUSTOM_STAMP_LIBRARY_ID\n )\n .wait(\n () => {\n setBusy(false)\n setLibraryId(CUSTOM_STAMP_LIBRARY_ID)\n notify("Stamp saved to your custom library.", "success")\n },\n () => {\n setBusy(false)\n notify("The stamp could not be created from the selection.", "error")\n }\n )\n }\n\n const exportLibrary = (targetLibraryId: string) => {\n stampCapability?.exportLibrary(targetLibraryId).wait(\n (exported) => downloadArrayBuffer(exported.pdf, `${exported.name}.pdf`),\n () => notify("The library could not be exported.", "error")\n )\n }\n\n const importLibrary = async (file: File) => {\n if (!stampCapability) return\n\n setBusy(true)\n\n try {\n const buffer = await file.arrayBuffer()\n const lib = await import("pdf-lib")\n const pageCount = (\n await lib.PDFDocument.load(buffer, { ignoreEncryption: true })\n ).getPageCount()\n const name = file.name.replace(/\\.pdf$/i, "") || "Imported stamps"\n\n stampCapability\n .loadLibrary({\n name,\n pdf: buffer,\n categories: ["sidebar"],\n stamps: Array.from({ length: pageCount }, (_, index) => ({\n id: `page-${index + 1}`,\n pageIndex: index,\n name: PdfAnnotationName.Custom,\n subject: `${name} ${index + 1}`,\n })),\n })\n .wait(\n (id) => {\n setBusy(false)\n setLibraryId(id)\n notify(\n `Imported ${pageCount} stamp${pageCount === 1 ? "" : "s"}.`,\n "success"\n )\n },\n () => {\n setBusy(false)\n notify("The stamp library could not be imported.", "error")\n }\n )\n } catch {\n setBusy(false)\n notify("The file could not be read as a PDF.", "error")\n }\n }\n\n return (\n <div className="flex h-full flex-col">\n <div className="shrink-0 space-y-2 border-b px-3 py-2">\n <div className="flex items-center gap-1.5">\n <Select\n items={libraryOptions}\n value={libraryId}\n onValueChange={(value) => setLibraryId(String(value))}\n >\n <SelectTrigger size="sm" className="min-w-0 flex-1">\n <SelectValue placeholder="Library" />\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {libraryOptions.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <PdfEditorToolButton\n label="Import stamps from a PDF"\n disabled={busy}\n onClick={() => importInputRef.current?.click()}\n >\n <UploadGlyph className="size-4" />\n </PdfEditorToolButton>\n <PdfEditorToolButton\n label="Export library"\n disabled={\n busy ||\n (libraryId === "all"\n ? libraries.length === 0\n : !libraries.some((library) => library.id === libraryId))\n }\n onClick={() => {\n const targets =\n libraryId === "all"\n ? libraries.map((library) => library.id)\n : [libraryId]\n targets.forEach(exportLibrary)\n }}\n >\n <DownloadGlyph className="size-4" />\n </PdfEditorToolButton>\n </div>\n <Button\n type="button"\n size="sm"\n variant="outline"\n className="w-full"\n disabled={\n !canCreateFromSelection || busy || !permissions.canModifyAnnotations\n }\n onClick={createFromSelection}\n >\n <StampGlyph className="size-4" />\n Save selection as stamp\n </Button>\n <input\n ref={importInputRef}\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) void importLibrary(file)\n event.currentTarget.value = ""\n }}\n />\n </div>\n {stamps.length === 0 ? (\n <PdfEditorEmptyState\n glyph={StampGlyph}\n title={libraries.length === 0 ? "Loading stamps…" : "No stamps"}\n description="Pick a library, import stamps from a PDF, or save a selected annotation as a stamp."\n />\n ) : (\n <PdfEditorScrollArea className="min-h-0 flex-1" viewportClassName="p-3">\n <div className="grid grid-cols-2 gap-2.5">\n {stamps.map(({ library, stamp }) => {\n const isActive =\n activeStamp?.libraryId === library.id &&\n activeStamp.stamp.id === stamp.id\n\n return (\n <div\n key={`${library.id}-${stamp.id}`}\n className="group relative"\n >\n <button\n type="button"\n aria-pressed={isActive}\n disabled={!permissions.canModifyAnnotations}\n className={cn(\n "flex aspect-square w-full flex-col items-center justify-center gap-1 rounded-lg border p-2 transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",\n isActive\n ? "border-primary bg-primary/5 ring-1 ring-primary/40"\n : "hover:bg-accent/50"\n )}\n onClick={() => placeStamp(library.id, stamp)}\n >\n <StampImg\n libraryId={library.id}\n pageIndex={stamp.pageIndex}\n width={STAMP_THUMB_WIDTH}\n style={{\n maxWidth: "85%",\n maxHeight: "70%",\n objectFit: "contain",\n }}\n />\n <span className="w-full truncate text-center text-[11px] text-muted-foreground">\n {stamp.label ?? stamp.subject}\n </span>\n </button>\n {!library.readonly ? (\n <button\n type="button"\n aria-label="Remove stamp"\n className="absolute top-1 right-1 grid size-5 place-items-center rounded-full border bg-background text-muted-foreground opacity-0 shadow-sm transition-opacity group-hover:opacity-100 hover:text-foreground focus-visible:opacity-100"\n onClick={() =>\n stampCapability\n ?.removeStampFromLibrary(library.id, stamp.id)\n .wait(\n () => undefined,\n () =>\n notify("The stamp could not be removed.", "error")\n )\n }\n >\n <TrashGlyph className="size-3" />\n </button>\n ) : null}\n </div>\n )\n })}\n </div>\n </PdfEditorScrollArea>\n )}\n {activeStamp ? (\n <div className="shrink-0 border-t px-3 py-2 text-xs text-muted-foreground">\n Click a page to place{" "}\n <span className="font-medium text-foreground">\n {activeStamp.stamp.subject}\n </span>\n .\n </div>\n ) : null}\n </div>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Signatures */\n/* -------------------------------------------------------------------------- */\n\nexport function PdfEditorSignaturesPanel({\n documentId,\n}: {\n documentId: string\n}) {\n const { entries, provides } = useSignatureEntries()\n const activePlacement = useActivePlacement(documentId)\n const { openDialog, permissions } = usePdfEditor()\n const canPlace = permissions.canModifyAnnotations\n\n const isActive = (entryId: string, kind: SignatureFieldKind) =>\n activePlacement?.entryId === entryId && activePlacement.kind === kind\n\n const togglePlacement = (entryId: string, kind: SignatureFieldKind) => {\n if (!provides) return\n\n const scope = provides.forDocument(documentId)\n\n if (isActive(entryId, kind)) {\n scope.deactivatePlacement()\n return\n }\n\n if (kind === SignatureFieldKind.Initials) {\n scope.activateInitialsPlacement(entryId)\n } else {\n scope.activateSignaturePlacement(entryId)\n }\n }\n\n return (\n <div className="flex h-full flex-col">\n <div className="shrink-0 border-b px-3 py-2">\n <Button\n type="button"\n size="sm"\n className="w-full"\n disabled={!canPlace}\n onClick={() => openDialog({ type: "signature" })}\n >\n <PlusGlyph className="size-4" />\n Create signature\n </Button>\n </div>\n {entries.length === 0 ? (\n <PdfEditorEmptyState\n glyph={SignatureGlyph}\n title="No signatures yet"\n description="Draw, type, or upload a signature, then click it to place it on the page."\n />\n ) : (\n <PdfEditorScrollArea className="min-h-0 flex-1" viewportClassName="p-3">\n <div className="space-y-3">\n {entries.map((entry) => (\n <div key={entry.id} className="space-y-2 rounded-lg border p-2.5">\n <div className="flex items-center justify-between">\n <span className="text-[11px] font-medium text-muted-foreground">\n Saved {formatRelativeDate(new Date(entry.createdAt))}\n </span>\n <PdfEditorToolButton\n label="Delete signature"\n size="icon-xs"\n onClick={() => provides?.removeEntry(entry.id)}\n >\n <TrashGlyph className="size-3.5" />\n </PdfEditorToolButton>\n </div>\n <div className="flex gap-2">\n <button\n type="button"\n disabled={!canPlace}\n aria-pressed={isActive(\n entry.id,\n SignatureFieldKind.Signature\n )}\n className={cn(\n "flex h-16 min-w-0 flex-[2] items-center justify-center rounded-md border border-dashed bg-white transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",\n isActive(entry.id, SignatureFieldKind.Signature)\n ? "border-primary ring-1 ring-primary/40"\n : "hover:border-muted-foreground/60"\n )}\n onClick={() =>\n togglePlacement(entry.id, SignatureFieldKind.Signature)\n }\n >\n <img\n src={entry.signature.previewDataUrl}\n alt="Signature"\n className="h-12 max-w-[90%] object-contain"\n />\n </button>\n {entry.initials ? (\n <button\n type="button"\n disabled={!canPlace}\n aria-pressed={isActive(\n entry.id,\n SignatureFieldKind.Initials\n )}\n className={cn(\n "flex h-16 min-w-0 flex-1 items-center justify-center rounded-md border border-dashed bg-white transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",\n isActive(entry.id, SignatureFieldKind.Initials)\n ? "border-primary ring-1 ring-primary/40"\n : "hover:border-muted-foreground/60"\n )}\n onClick={() =>\n togglePlacement(entry.id, SignatureFieldKind.Initials)\n }\n >\n <img\n src={entry.initials.previewDataUrl}\n alt="Initials"\n className="h-10 max-w-[80%] object-contain"\n />\n </button>\n ) : null}\n </div>\n </div>\n ))}\n </div>\n </PdfEditorScrollArea>\n )}\n {activePlacement ? (\n <div className="shrink-0 border-t px-3 py-2 text-xs text-muted-foreground">\n Click a page to place your{" "}\n {activePlacement.kind === SignatureFieldKind.Initials\n ? "initials"\n : "signature"}\n .\n </div>\n ) : null}\n </div>\n )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Forms */\n/* -------------------------------------------------------------------------- */\n\nexport function PdfEditorFormsPanel({ documentId }: { documentId: string }) {\n const { provides: form } = useFormCapability()\n const { provides: annotation, state: annotationState } =\n useAnnotation(documentId)\n const {\n features,\n fileName,\n formDesignMode,\n notify,\n permissions,\n scrollToAnnotation,\n setFormDesignMode,\n } = usePdfEditor()\n const scope = React.useMemo(\n () => form?.forDocument(documentId) ?? null,\n [documentId, form]\n )\n const [fields, setFields] = React.useState<FormFieldInfo[]>([])\n const importInputRef = React.useRef<HTMLInputElement>(null)\n\n React.useEffect(() => {\n if (!scope) return\n\n setFields(scope.getFormFields())\n\n const unsubscribeReady = scope.onFormReady((list) => setFields(list))\n const unsubscribeChange = scope.onFieldValueChange(() =>\n setFields(scope.getFormFields())\n )\n\n return () => {\n unsubscribeReady()\n unsubscribeChange()\n }\n }, [scope])\n\n const widgetsByName = React.useMemo(() => {\n const map = new Map<string, PdfWidgetAnnoObject>()\n\n for (const tracked of Object.values(annotationState.byUid)) {\n if (tracked.object.type !== PdfAnnotationSubtype.WIDGET) continue\n\n const widget = tracked.object as PdfWidgetAnnoObject\n\n if (!map.has(widget.field.name)) map.set(widget.field.name, widget)\n }\n\n return map\n }, [annotationState.byUid])\n\n const focusField = (field: FormFieldInfo) => {\n const widget = widgetsByName.get(field.name)\n\n if (!widget) return\n\n if (formDesignMode) {\n annotation?.selectAnnotation(widget.pageIndex, widget.id)\n } else {\n scope?.selectField(widget.id)\n }\n\n scrollToAnnotation(widget)\n }\n\n const exportValues = () => {\n if (!scope) return\n\n const values = scope.getFormValues()\n\n downloadBlob(\n new Blob([JSON.stringify(values, null, 2)], { type: "application/json" }),\n `${fileName.replace(/\\.pdf$/i, "")}-form-values.json`\n )\n }\n\n const importValues = async (file: File) => {\n if (!scope) return\n\n try {\n const parsed = JSON.parse(await file.text()) as Record<string, unknown>\n const values = Object.fromEntries(\n Object.entries(parsed).map(([key, value]) => [key, String(value ?? "")])\n )\n\n scope.setFormValues(values).wait(\n () => notify("Form values imported.", "success"),\n () => notify("The form values could not be applied.", "error")\n )\n } catch {\n notify("The file is not valid JSON.", "error")\n }\n }\n\n const clearValues = () => {\n if (!scope || fields.length === 0) return\n\n const values = Object.fromEntries(\n fields.map((field) => [\n field.name,\n field.type === PDF_FORM_FIELD_TYPE.CHECKBOX ||\n field.type === PDF_FORM_FIELD_TYPE.RADIOBUTTON\n ? "Off"\n : "",\n ])\n )\n\n scope.setFormValues(values).wait(\n () => notify("Form cleared.", "success"),\n () => notify("The form could not be cleared.", "error")\n )\n }\n\n return (\n <div className="flex h-full flex-col">\n <div className="shrink-0 space-y-2 border-b px-3 py-2">\n {features.forms && permissions.canModifyAnnotations ? (\n <PdfEditorCheckbox\n checked={formDesignMode}\n onCheckedChange={() => setFormDesignMode((enabled) => !enabled)}\n label="Design mode"\n description="Move, resize, and configure fields instead of filling them."\n />\n ) : null}\n <div className="flex flex-wrap gap-1.5">\n <Button\n type="button"\n size="xs"\n variant="outline"\n disabled={fields.length === 0}\n onClick={exportValues}\n >\n <DownloadGlyph className="size-3.5" />\n Export values\n </Button>\n <Button\n type="button"\n size="xs"\n variant="outline"\n disabled={!permissions.canFillForms}\n onClick={() => importInputRef.current?.click()}\n >\n <UploadGlyph className="size-3.5" />\n Import values\n </Button>\n <Button\n type="button"\n size="xs"\n variant="outline"\n disabled={fields.length === 0 || !permissions.canFillForms}\n onClick={clearValues}\n >\n Clear\n </Button>\n </div>\n <input\n ref={importInputRef}\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 importValues(file)\n event.currentTarget.value = ""\n }}\n />\n </div>\n {fields.length === 0 ? (\n <PdfEditorEmptyState\n glyph={TextFieldGlyph}\n title="No form fields"\n description={\n features.forms\n ? "Switch to the Forms mode to add text fields, checkboxes, radio buttons, dropdowns, and list boxes."\n : "This document has no fillable fields."\n }\n />\n ) : (\n <PdfEditorScrollArea className="min-h-0 flex-1" viewportClassName="p-2">\n <div className="space-y-1">\n {fields.map((field) => (\n <button\n key={field.name}\n type="button"\n className="flex w-full items-center gap-2 rounded-lg border px-2.5 py-2 text-left outline-none hover:bg-accent/40 focus-visible:ring-2 focus-visible:ring-ring"\n onClick={() => focusField(field)}\n >\n <div className="min-w-0 flex-1">\n <div className="flex items-center gap-1.5">\n <span className="truncate text-sm font-medium">\n {field.name}\n </span>\n {field.readOnly ? (\n <Badge variant="outline" className="h-4 px-1 text-[10px]">\n Read only\n </Badge>\n ) : null}\n </div>\n <div className="truncate text-xs text-muted-foreground">\n {getFormFieldTypeLabel(field.type)}\n {field.value ? ` · ${field.value}` : ""}\n </div>\n </div>\n </button>\n ))}\n </div>\n </PdfEditorScrollArea>\n )}\n </div>\n )\n}\n\nexport { GridGlyph as PdfEditorPagesGlyph }\n',+ },+]++export function PdfEditorSourceCode() {+ return (+ <div className="space-y-6">+ {pdfEditorSourceFiles.map((file) => (+ <DocsSourceCodeBlock+ key={file.fileName}+ code={file.code}+ fileName={file.fileName}+ />+ ))}+ </div>+ )+}diff --git a/apps/v4/components/pdf-viewer-block-fullscreen.tsx b/apps/v4/components/pdf-viewer-block-fullscreen.tsxindex 4cbdfad..2a55b2a 100644--- a/apps/v4/components/pdf-viewer-block-fullscreen.tsx+++ b/apps/v4/components/pdf-viewer-block-fullscreen.tsx@@ -61,6 +61,12 @@ const XlsxEditorBlock = dynamic<PdfViewerBlockFullscreenPreviewProps>({ loading: () => <BlockViewPlaceholder /> })+const PdfEditorBlock = dynamic<PdfViewerBlockFullscreenPreviewProps>(+ () =>+ import("@/components/pdf-editor-docs").then((mod) => mod.PdfEditorBlock),+ { loading: () => <BlockViewPlaceholder /> }+)+const DocxEditorBlock = dynamic<PdfViewerBlockFullscreenPreviewProps>(() =>import("@/components/docx-editor-docs").then((mod) => mod.DocxEditorBlock),@@ -85,6 +91,7 @@ const blockComponents = {"document-splits": DocumentSplitsBlock,"excel-editor": XlsxEditorBlock,"docx-editor-block": DocxEditorBlock,+ "pdf-editor-block": PdfEditorBlock,"file-system": FileSystemFinderBlock,} satisfies Record<PdfViewerBlockId,diff --git a/apps/v4/components/pdf-viewer-blocks.tsx b/apps/v4/components/pdf-viewer-blocks.tsxindex e5808be..3d63b37 100644--- a/apps/v4/components/pdf-viewer-blocks.tsx+++ b/apps/v4/components/pdf-viewer-blocks.tsx@@ -126,6 +126,12 @@ const XlsxEditorBlock = dynamic<BlockPreviewProps>({ loading: () => <BlockPreviewPlaceholder /> })+const PdfEditorBlock = dynamic<BlockPreviewProps>(+ () =>+ import("@/components/pdf-editor-docs").then((mod) => mod.PdfEditorBlock),+ { loading: () => <BlockPreviewPlaceholder /> }+)+const DocxEditorBlock = dynamic<BlockPreviewProps>(() =>import("@/components/docx-editor-docs").then((mod) => mod.DocxEditorBlock),@@ -148,6 +154,7 @@ const blockComponents = {"document-splits": DocumentSplitsBlock,"excel-editor": XlsxEditorBlock,"docx-editor-block": DocxEditorBlock,+ "pdf-editor-block": PdfEditorBlock,"file-system": FileSystemFinderBlock,} satisfies Record<PdfViewerBlockId, React.ComponentType>diff --git a/apps/v4/components/pdf-viewer-source-code.tsx b/apps/v4/components/pdf-viewer-source-code.tsxindex 57189a3..a96dff8 100644--- a/apps/v4/components/pdf-viewer-source-code.tsx+++ b/apps/v4/components/pdf-viewer-source-code.tsx@@ -2,10 +2,9 @@import { DocsSourceCodeBlock } from "@/components/docs-code-block"-// Generated from components/extend/pdf-viewer.tsx - keep in sync when the-// component changes.+// Generated source snapshot. Regenerate when the component changes.export const pdfViewerSourceCode =- '"use client"\n\nimport * as React from "react"\nimport { createPluginRegistration, refreshPages } from "@embedpdf/core"\nimport { EmbedPDF, useRegistry } from "@embedpdf/core/react"\nimport type {\n PdfDocumentObject,\n PdfEngine,\n Rect,\n Rotation,\n} from "@embedpdf/models"\nimport {\n DocumentManagerPluginPackage,\n useActiveDocument,\n useDocumentManagerCapability,\n} from "@embedpdf/plugin-document-manager/react"\nimport {\n GlobalPointerProvider,\n InteractionManagerPluginPackage,\n PagePointerProvider,\n} from "@embedpdf/plugin-interaction-manager/react"\nimport { RenderLayer, RenderPluginPackage } from "@embedpdf/plugin-render/react"\nimport { Rotate, RotatePluginPackage } from "@embedpdf/plugin-rotate/react"\nimport {\n ScrollPluginPackage,\n ScrollStrategy,\n useScroll,\n useScrollPlugin,\n type PageLayout,\n type ScrollerLayout,\n type VirtualItem,\n} from "@embedpdf/plugin-scroll/react"\nimport {\n SearchLayer,\n SearchPluginPackage,\n useSearch,\n} from "@embedpdf/plugin-search/react"\nimport {\n CopyToClipboard,\n SelectionPluginPackage,\n useSelectionCapability,\n useSelectionPlugin,\n} from "@embedpdf/plugin-selection/react"\nimport {\n ThumbImg,\n ThumbnailPluginPackage,\n useThumbnailCapability,\n useThumbnailPlugin,\n type ThumbMeta,\n} 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 { useZoom, ZoomPluginPackage } from "@embedpdf/plugin-zoom/react"\nimport { flushSync } from "react-dom"\n\nimport { loadSharedPdfEngine } from "@/lib/pdf-thumbnail-utils"\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\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 { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport {\n DocumentViewerSidebarSkeleton,\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/extend/document-viewer-sidebar"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nexport type PDFViewerPageOverlayProps = {\n pageNumber: number\n pageWidth: number\n pageHeight: number\n scale: number\n rotation: number\n}\n\nexport type PDFViewerHandle = {\n scrollToPage: (pageNumber: number, options?: ScrollIntoViewOptions) => void\n scrollToPageArea: (\n pageNumber: number,\n area: { top: number; left?: number; width?: number; height?: number },\n options?: ScrollToOptions\n ) => void\n getViewportElement: () => HTMLDivElement | null\n}\n\nexport type PDFViewerScrollAreaViewportResolver = (\n container: HTMLDivElement\n) => HTMLDivElement | null\n\nexport type PDFViewerProps = {\n className?: string\n defaultZoom?: number\n fileName?: string\n resolveScrollAreaViewport?: PDFViewerScrollAreaViewportResolver\n showDownload?: boolean\n showToolbar?: boolean\n showRotateControls?: boolean\n showUpload?: boolean\n src?: string\n toolbarActions?: React.ReactNode\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onActivePageChange?: (pageNumber: number) => void\n onDocumentLoadSuccess?: (numPages: number) => void\n onPdfUpload?: (file: File) => void\n onPagePointerDown?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerMove?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerUp?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerCancel?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n}\n\nconst DEFAULT_ZOOM = 1\nconst ZOOM_OPTIONS = [0.1, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2]\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 THUMBNAIL_SIDEBAR_WIDTH_CLASS = "w-40"\nconst THUMBNAIL_SIDEBAR_CLOSED_CLASS = "-ml-40"\nconst PAGE_BASE_RENDER_MAX_SCALE = 1\nconst PAGE_BASE_RENDER_DPR = 1\nconst PDF_SEARCH_DEBOUNCE_MS = 300\nconst TEXT_SELECTION_BACKGROUND = "rgba(59, 130, 246, 0.14)"\nconst THUMBNAIL_FOCUS_RING_CLASS =\n "group-focus-visible/pdf-thumbnail-sidebar:ring-2 group-focus-visible/pdf-thumbnail-sidebar:ring-ring group-focus-visible/pdf-thumbnail-sidebar:ring-offset-1 group-focus-visible/pdf-thumbnail-sidebar:ring-offset-background"\nconst DEFAULT_SCROLL_AREA_VIEWPORT_SELECTOR =\n \'[data-slot="scroll-area-viewport"]\'\n\nfunction resolveDefaultScrollAreaViewport(container: HTMLDivElement) {\n return container.querySelector<HTMLDivElement>(\n DEFAULT_SCROLL_AREA_VIEWPORT_SELECTOR\n )\n}\n\nconst PDFViewerScrollAreaResolverContext =\n React.createContext<PDFViewerScrollAreaViewportResolver>(\n resolveDefaultScrollAreaViewport\n )\n\ntype PageRotationDeltas = Map<number, Rotation>\ntype ThumbnailSelectionMode = "replace" | "toggle" | "range"\n\nfunction getPageIndexRange(from: number, to: number): Set<number> {\n const start = Math.min(from, to)\n const end = Math.max(from, to)\n const range = new Set<number>()\n\n for (let pageIndex = start; pageIndex <= end; pageIndex += 1) {\n range.add(pageIndex)\n }\n\n return range\n}\n\nfunction arePageIndexSetsEqual(left: Set<number>, right: Set<number>) {\n if (left.size !== right.size) return false\n\n for (const value of left) {\n if (!right.has(value)) return false\n }\n\n return true\n}\n\nfunction normalizeRotation(rotation: number): Rotation {\n return (((rotation % 4) + 4) % 4) as Rotation\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\nfunction rotationToDegrees(rotation: Rotation) {\n return (rotation as number) * 90\n}\n\nfunction normalizeDegrees(rotation: number) {\n return ((rotation % 360) + 360) % 360\n}\n\nfunction ensurePdfExtension(fileName: string) {\n return fileName.toLowerCase().endsWith(".pdf") ? fileName : `${fileName}.pdf`\n}\n\nfunction getPdfDownloadFileName(fileName: string | undefined, src: string) {\n if (fileName?.trim()) return ensurePdfExtension(fileName.trim())\n\n const pathname = src.split(/[?#]/)[0] ?? ""\n const rawName = pathname.split("/").pop() || "document.pdf"\n\n try {\n return ensurePdfExtension(decodeURIComponent(rawName))\n } catch {\n return ensurePdfExtension(rawName)\n }\n}\n\nfunction getRotatedPdfDownloadFileName(fileName: string) {\n return fileName.replace(/\\.pdf$/i, "-rotated.pdf")\n}\n\nfunction downloadBlob(blob: Blob, fileName: string) {\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n\n anchor.href = url\n anchor.download = fileName\n anchor.rel = "noopener"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nasync function downloadPdfWithPageRotations({\n fileName,\n pageRotationDeltas,\n src,\n}: {\n fileName: string\n pageRotationDeltas: PageRotationDeltas\n src: string\n}) {\n const response = await fetch(src)\n\n if (!response.ok) {\n throw new Error(`Failed to download PDF (${response.status})`)\n }\n\n if (pageRotationDeltas.size === 0) {\n downloadBlob(await response.blob(), fileName)\n return\n }\n\n const [{ PDFDocument, degrees }, pdfBytes] = await Promise.all([\n import("pdf-lib"),\n response.arrayBuffer(),\n ])\n const pdfDocument = await PDFDocument.load(pdfBytes)\n\n pdfDocument.getPages().forEach((page, pageIndex) => {\n const rotationDelta = pageRotationDeltas.get(pageIndex)\n\n if (!rotationDelta) return\n\n page.setRotation(\n degrees(\n normalizeDegrees(\n page.getRotation().angle + rotationToDegrees(rotationDelta)\n )\n )\n )\n })\n\n const nextPdfBytes = await pdfDocument.save()\n const nextPdfBuffer = new ArrayBuffer(nextPdfBytes.byteLength)\n new Uint8Array(nextPdfBuffer).set(nextPdfBytes)\n\n downloadBlob(\n new Blob([nextPdfBuffer], { type: "application/pdf" }),\n getRotatedPdfDownloadFileName(fileName)\n )\n}\n\nfunction getThumbnailMetaForPage({\n page,\n pageIndex,\n rotation,\n width,\n imagePadding,\n labelHeight,\n top,\n}: {\n page: PdfDocumentObject["pages"][number]\n pageIndex: number\n rotation: Rotation\n width: number\n imagePadding: number\n labelHeight: number\n top: number\n}): ThumbMeta {\n const innerWidth = Math.max(1, width - imagePadding * 2)\n const pageWidth = rotation % 2 === 1 ? page.size.height : page.size.width\n const pageHeight = rotation % 2 === 1 ? page.size.width : page.size.height\n const imageHeight = Math.round(innerWidth * (pageHeight / pageWidth))\n const wrapperHeight = imagePadding + imageHeight + imagePadding + labelHeight\n\n return {\n pageIndex,\n width: innerWidth,\n height: imageHeight,\n wrapperHeight,\n top,\n labelHeight,\n padding: imagePadding,\n }\n}\n\nfunction buildThumbnailLayout({\n basePageRotations,\n pageRotationDeltas,\n pdfDocument,\n width,\n gap,\n imagePadding,\n labelHeight,\n paddingY,\n}: {\n basePageRotations: Rotation[]\n pageRotationDeltas: PageRotationDeltas\n pdfDocument: PdfDocumentObject | null\n width: number\n gap: number\n imagePadding: number\n labelHeight: number\n paddingY: number\n}) {\n if (!pdfDocument) return null\n\n let top = paddingY\n const items = pdfDocument.pages.map((page, pageIndex) => {\n const basePageRotation =\n basePageRotations[pageIndex] ?? normalizeRotation(page.rotation)\n const pageRotation = normalizeRotation(\n basePageRotation + (pageRotationDeltas.get(pageIndex) ?? 0)\n )\n const meta = getThumbnailMetaForPage({\n page,\n pageIndex,\n rotation: pageRotation,\n width,\n imagePadding,\n labelHeight,\n top,\n })\n\n top += meta.wrapperHeight + gap\n return meta\n })\n\n return {\n items,\n totalHeight: items.length ? top - gap + paddingY : paddingY * 2,\n }\n}\n\nfunction getVisibleThumbnailItems({\n buffer,\n clientHeight,\n items,\n scrollTop,\n}: {\n buffer: number\n clientHeight: number\n items: ThumbMeta[]\n scrollTop: number\n}) {\n if (items.length === 0) return []\n if (clientHeight <= 0)\n return items.slice(0, Math.min(items.length, buffer * 2))\n\n const viewportBottom = scrollTop + clientHeight\n let start = items.findIndex(\n (item) => item.top + item.wrapperHeight >= scrollTop\n )\n\n if (start === -1) start = items.length - 1\n\n let end = start\n while (end < items.length && items[end].top <= viewportBottom) {\n end += 1\n }\n\n return items.slice(\n Math.max(0, start - buffer),\n Math.min(items.length, end + buffer)\n )\n}\n\nfunction PDFViewerLoadingSkeleton({\n sidebarOpen,\n sidebarInline,\n}: {\n sidebarOpen: boolean\n sidebarInline: boolean\n}) {\n return (\n <div className="absolute inset-0 z-20 flex bg-muted/30">\n {sidebarOpen ? (\n <DocumentViewerSidebarSkeleton\n className={THUMBNAIL_SIDEBAR_WIDTH_CLASS}\n inline={sidebarInline}\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 )\n}\n\n// Rendered while the engine or document is not ready: same frame and controls\n// as the full viewer, with document-dependent controls disabled.\nfunction PDFViewerFallbackShell({\n className,\n defaultZoom,\n errorMessage = "Unable to load the PDF preview.",\n showDownload,\n showRotateControls,\n showToolbar,\n showUpload,\n sidebarOpen,\n state,\n toolbarActions,\n onUploadFile,\n}: {\n className?: string\n defaultZoom: number\n errorMessage?: string\n showDownload: boolean\n showRotateControls: boolean\n showToolbar: boolean\n showUpload: boolean\n sidebarOpen: boolean\n state: "loading" | "error" | "empty"\n toolbarActions?: React.ReactNode\n onUploadFile?: (file: File) => void\n}) {\n return (\n <div\n data-slot="pdf-viewer"\n className={cn(\n "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n {showToolbar ? (\n <PDFViewerToolbar\n activePage={1}\n controlsDisabled\n currentZoomLevel={defaultZoom}\n numPages={0}\n searchControl={\n <ToolbarTooltip label="Search text">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search text"\n disabled\n >\n <IconPlaceholder\n lucide="Search"\n tabler="IconSearch"\n hugeicons="Search01Icon"\n phosphor="MagnifyingGlassIcon"\n remixicon="RiSearchLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n }\n showDownload={showDownload}\n showRotateControls={showRotateControls}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n onPageChange={() => undefined}\n onRotate={() => undefined}\n onToggleSidebar={() => undefined}\n onUploadFile={onUploadFile}\n onZoomChange={() => undefined}\n />\n ) : null}\n <div className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30">\n {state === "loading" ? (\n <PDFViewerLoadingSkeleton sidebarInline sidebarOpen={sidebarOpen} />\n ) : null}\n {state === "error" ? (\n <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-sm text-muted-foreground">\n {errorMessage}\n </div>\n ) : null}\n {state === "empty" ? (\n <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-center text-sm text-muted-foreground">\n <div className="max-w-sm space-y-3">\n <div className="font-medium text-foreground">\n Upload a PDF to preview\n </div>\n <div>\n Pass a PDF URL with the <code>src</code> prop or use the upload\n control.\n </div>\n </div>\n </div>\n ) : null}\n </div>\n </div>\n )\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction PDFViewerFileActionsMenu({\n downloadDisabled,\n isPreparingDownload = false,\n onDownload,\n onUploadFile,\n showDownload = false,\n showUpload = false,\n}: {\n downloadDisabled?: boolean\n isPreparingDownload?: boolean\n onDownload?: () => void\n onUploadFile?: (file: File) => void\n showDownload?: boolean\n showUpload?: boolean\n}) {\n const inputRef = React.useRef<HTMLInputElement>(null)\n\n if (!showDownload && !showUpload) return null\n\n return (\n <>\n {showUpload && onUploadFile ? (\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 nextFile = event.target.files?.[0]\n\n if (nextFile) {\n onUploadFile(nextFile)\n event.currentTarget.value = ""\n }\n }}\n />\n ) : null}\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Open PDF actions"\n >\n <IconPlaceholder\n lucide="Ellipsis"\n tabler="IconDots"\n hugeicons="MoreHorizontalIcon"\n phosphor="DotsThreeIcon"\n remixicon="RiMoreLine"\n className="size-4"\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="w-40">\n {showDownload ? (\n <DropdownMenuItem disabled={downloadDisabled} onClick={onDownload}>\n {isPreparingDownload ? (\n <Spinner className="size-4" />\n ) : (\n <IconPlaceholder\n lucide="Download"\n tabler="IconDownload"\n hugeicons="Download01Icon"\n phosphor="DownloadSimpleIcon"\n remixicon="RiDownload2Line"\n className="size-4"\n />\n )}\n Download\n </DropdownMenuItem>\n ) : null}\n {showUpload && onUploadFile ? (\n <DropdownMenuItem onClick={() => inputRef.current?.click()}>\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload\n </DropdownMenuItem>\n ) : null}\n </DropdownMenuContent>\n </DropdownMenu>\n </>\n )\n}\n\nfunction PDFViewerPageNumberControl({\n activePage,\n controlsDisabled,\n numPages,\n onPageChange,\n}: {\n activePage: number\n controlsDisabled: boolean\n numPages: number\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={controlsDisabled || !numPages}\n onClick={() => {\n setDraftPage(String(displayPage))\n setIsEditing(true)\n }}\n >\n {displayPage}\n </Button>\n )}\n <span>of {numPages || "\u2013"}</span>\n </div>\n )\n}\n\nfunction PDFViewerSearchControl({\n documentId,\n controlsDisabled,\n}: {\n documentId: string\n controlsDisabled: boolean\n}) {\n const { state, provides } = useSearch(documentId)\n const { provides: scroll } = useScroll(documentId)\n const [searchDraft, setSearchDraft] = React.useState("")\n const [searchQuery, setSearchQuery] = React.useState("")\n const [isSearching, setIsSearching] = React.useState(false)\n const providesRef = React.useRef(provides)\n const scrollRef = React.useRef(scroll)\n const searchRequestIdRef = React.useRef(0)\n const hasActiveQuery = Boolean(searchQuery.trim())\n const resultLabel = isSearching\n ? "Searching"\n : !hasActiveQuery\n ? "No search"\n : state.total\n ? `${state.activeResultIndex + 1} / ${state.total}`\n : "No results"\n\n const scrollToResult = React.useCallback(\n (index: number) => {\n const result = state.results[index]\n\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: {\n x: firstRect.origin.x,\n y: firstRect.origin.y,\n },\n alignY: 30,\n }\n : {}),\n behavior: "auto",\n })\n },\n [scroll, state.results]\n )\n\n React.useEffect(() => {\n providesRef.current = provides\n scrollRef.current = scroll\n }, [provides, scroll])\n\n const runSearch = React.useCallback((rawQuery: string) => {\n const query = rawQuery.trim()\n const requestId = searchRequestIdRef.current + 1\n searchRequestIdRef.current = requestId\n setSearchQuery(query)\n\n const searchProvider = providesRef.current\n const scrollProvider = scrollRef.current\n\n if (!searchProvider) {\n setIsSearching(false)\n return\n }\n\n if (!query) {\n searchProvider.stopSearch()\n setIsSearching(false)\n return\n }\n\n setIsSearching(true)\n searchProvider.startSearch()\n searchProvider.searchAllPages(query).wait(\n (result) => {\n if (searchRequestIdRef.current !== requestId) return\n\n const firstResult = result.results[0]\n\n if (firstResult && scrollProvider) {\n searchProvider.goToResult(0)\n const firstRect = firstResult.rects[0]\n\n scrollProvider.scrollToPage({\n pageNumber: firstResult.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 setIsSearching(false)\n },\n () => {\n if (searchRequestIdRef.current !== requestId) return\n setIsSearching(false)\n }\n )\n }, [])\n\n React.useEffect(() => {\n if (!searchDraft.trim()) return\n\n const timeoutId = window.setTimeout(() => {\n runSearch(searchDraft)\n }, PDF_SEARCH_DEBOUNCE_MS)\n\n return () => window.clearTimeout(timeoutId)\n }, [runSearch, searchDraft])\n\n const handleSearchDraftChange = React.useCallback(\n (event: React.ChangeEvent<HTMLInputElement>) => {\n const nextDraft = event.target.value\n\n setSearchDraft(nextDraft)\n\n if (nextDraft.trim()) {\n setIsSearching(true)\n return\n }\n\n searchRequestIdRef.current += 1\n setSearchQuery("")\n setIsSearching(false)\n provides?.stopSearch()\n },\n [provides]\n )\n\n const clearSearch = React.useCallback(() => {\n searchRequestIdRef.current += 1\n setSearchDraft("")\n setSearchQuery("")\n setIsSearching(false)\n provides?.stopSearch()\n }, [provides])\n\n const navigate = React.useCallback(\n (direction: 1 | -1) => {\n if (!provides || state.total === 0) return\n\n const index =\n direction === 1 ? provides.nextResult() : provides.previousResult()\n\n scrollToResult(index)\n },\n [provides, scrollToResult, state.total]\n )\n\n return (\n <Popover>\n <ToolbarTooltip label="Search text">\n <PopoverTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search text"\n disabled={controlsDisabled}\n >\n <IconPlaceholder\n lucide="Search"\n tabler="IconSearch"\n hugeicons="Search01Icon"\n phosphor="MagnifyingGlassIcon"\n remixicon="RiSearchLine"\n className="size-4"\n />\n </Button>\n </PopoverTrigger>\n </ToolbarTooltip>\n <PopoverContent align="end" className="w-72">\n <div className="space-y-3">\n <Input\n placeholder="Search text"\n value={searchDraft}\n onChange={handleSearchDraftChange}\n onKeyDown={(event) => {\n if (event.key !== "Enter") return\n\n event.preventDefault()\n if (event.shiftKey && state.total) {\n navigate(-1)\n } else if (state.total) {\n navigate(1)\n } else if (searchDraft.trim()) {\n runSearch(searchDraft)\n }\n }}\n />\n <div className="flex items-center justify-between gap-2">\n <div className="min-w-0 text-xs text-muted-foreground">\n <div className="truncate">\n {state.total ? (\n <>\n <span className="text-primary">\n {state.activeResultIndex + 1}\n </span>\n {` / ${state.total}`}\n </>\n ) : (\n resultLabel\n )}\n </div>\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 <IconPlaceholder\n lucide="ChevronLeft"\n tabler="IconChevronLeft"\n hugeicons="ArrowLeft01Icon"\n phosphor="CaretLeftIcon"\n remixicon="RiArrowLeftSLine"\n className="size-4"\n />\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 <IconPlaceholder\n lucide="ArrowRight"\n tabler="IconArrowRight"\n hugeicons="ArrowRight01Icon"\n phosphor="ArrowRightIcon"\n remixicon="RiArrowRightLine"\n className="size-4"\n />\n </Button>\n </div>\n </div>\n <div className="flex justify-end">\n <Button\n type="button"\n variant="outline"\n size="sm"\n onClick={clearSearch}\n >\n Clear\n </Button>\n </div>\n </div>\n </PopoverContent>\n </Popover>\n )\n}\n\nfunction PDFViewerToolbar({\n activePage,\n controlsDisabled,\n currentZoomLevel,\n downloadDisabled = controlsDisabled,\n isPreparingDownload = false,\n numPages,\n searchControl,\n showDownload,\n showRotateControls,\n showUpload,\n toolbarActions,\n onDownload,\n onPageChange,\n onRotate,\n onToggleSidebar,\n onUploadFile,\n onZoomChange,\n}: {\n activePage: number\n controlsDisabled: boolean\n currentZoomLevel: number\n downloadDisabled?: boolean\n isPreparingDownload?: boolean\n numPages: number\n searchControl: React.ReactNode\n showDownload: boolean\n showRotateControls: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n onDownload?: () => void\n onPageChange: (pageNumber: number) => void\n onRotate: (direction: 1 | -1) => void\n onToggleSidebar: () => void\n onUploadFile?: (file: File) => void\n onZoomChange: (zoomLevel: number) => void\n}) {\n return (\n <div className="flex min-h-12 flex-wrap items-center justify-between gap-2 border-b bg-background px-3 py-2">\n <div className="flex min-w-0 flex-wrap items-center gap-2">\n <TooltipProvider>\n <ToolbarTooltip label="Toggle thumbnails">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Toggle thumbnails"\n disabled={controlsDisabled}\n onClick={onToggleSidebar}\n >\n <IconPlaceholder\n lucide="PanelLeft"\n tabler="IconLayoutSidebar"\n hugeicons="SidebarLeftIcon"\n phosphor="SidebarIcon"\n remixicon="RiLayoutLeftLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </TooltipProvider>\n <PDFViewerPageNumberControl\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n numPages={numPages}\n onPageChange={onPageChange}\n />\n </div>\n <TooltipProvider>\n <div className="flex min-w-0 flex-wrap items-center justify-end gap-1">\n {showRotateControls ? (\n <>\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Rotate counterclockwise">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Rotate counterclockwise"\n disabled={controlsDisabled}\n onClick={() => onRotate(-1)}\n >\n <IconPlaceholder\n lucide="RotateCw"\n tabler="IconRotateClockwise"\n hugeicons="RotateClockwiseIcon"\n phosphor="ArrowClockwiseIcon"\n remixicon="RiClockwiseLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Rotate clockwise">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Rotate clockwise"\n disabled={controlsDisabled}\n onClick={() => onRotate(1)}\n >\n <IconPlaceholder\n lucide="RotateCw"\n tabler="IconRotateClockwise"\n hugeicons="RotateClockwiseIcon"\n phosphor="ArrowClockwiseIcon"\n remixicon="RiClockwiseLine"\n className="size-4 -scale-x-100"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom out"\n disabled={\n controlsDisabled || currentZoomLevel <= ZOOM_OPTIONS[0]\n }\n onClick={() => {\n const nextZoom = [...ZOOM_OPTIONS]\n .reverse()\n .find((option) => option < currentZoomLevel)\n\n onZoomChange(nextZoom ?? ZOOM_OPTIONS[0])\n }}\n >\n <IconPlaceholder\n lucide="CircleMinus"\n tabler="IconCircleMinus"\n hugeicons="MinusSignCircleIcon"\n phosphor="MinusCircleIcon"\n remixicon="RiIndeterminateCircleLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={String(currentZoomLevel)}\n onValueChange={(value) => onZoomChange(Number(value))}\n disabled={controlsDisabled}\n modal={false}\n >\n <SelectTrigger size="sm" className="w-[84px] min-w-[84px]">\n <SelectValue placeholder="Zoom">\n {Math.round(currentZoomLevel * 100)}%\n </SelectValue>\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((option) => (\n <SelectItem key={option} value={String(option)}>\n {Math.round(option * 100)}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom in"\n disabled={\n controlsDisabled ||\n currentZoomLevel >= ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n }\n onClick={() => {\n const nextZoom = ZOOM_OPTIONS.find(\n (option) => option > currentZoomLevel\n )\n\n onZoomChange(\n nextZoom ?? ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n )\n }}\n >\n <IconPlaceholder\n lucide="CirclePlusIcon"\n tabler="IconCirclePlusFilled"\n hugeicons="PlusSignCircleIcon"\n phosphor="PlusCircleIcon"\n remixicon="RiAddCircleFill"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n {searchControl}\n {toolbarActions ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {toolbarActions}\n </>\n ) : null}\n {showDownload || showUpload ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <PDFViewerFileActionsMenu\n downloadDisabled={downloadDisabled}\n isPreparingDownload={isPreparingDownload}\n onDownload={onDownload}\n onUploadFile={onUploadFile}\n showDownload={showDownload}\n showUpload={showUpload}\n />\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nfunction setPdfViewerRef<T>(ref: React.Ref<T> | undefined, value: T | null) {\n if (!ref) return\n\n if (typeof ref === "function") {\n ref(value)\n } else {\n ref.current = value\n }\n}\n\nfunction PDFViewerScrollArea({\n children,\n className,\n viewportClassName,\n viewportProps,\n viewportRef,\n}: {\n children: React.ReactNode\n className?: string\n viewportClassName?: string\n viewportProps?: React.HTMLAttributes<HTMLDivElement>\n viewportRef?: React.Ref<HTMLDivElement>\n}) {\n const resolveScrollAreaViewport = React.useContext(\n PDFViewerScrollAreaResolverContext\n )\n const containerRef = React.useRef<HTMLDivElement | null>(null)\n const { className: viewportPropsClassName, ...resolvedViewportProps } =\n viewportProps ?? {}\n\n const setViewportRef = React.useCallback(\n (viewport: HTMLDivElement | null) => {\n setPdfViewerRef(viewportRef, viewport)\n },\n [viewportRef]\n )\n\n React.useLayoutEffect(() => {\n const container = containerRef.current\n if (!container) return\n\n const viewport = resolveScrollAreaViewport(container)\n\n if (!viewport) {\n console.error(\n `PDFViewer could not resolve the scroll viewport. Add ${DEFAULT_SCROLL_AREA_VIEWPORT_SELECTOR} to your ScrollArea viewport or pass resolveScrollAreaViewport.`\n )\n return\n }\n\n setViewportRef(viewport)\n\n return () => setViewportRef(null)\n }, [resolveScrollAreaViewport, setViewportRef])\n\n return (\n <div\n ref={containerRef}\n data-slot="pdf-viewer-scroll-area"\n className={cn("size-full min-h-0", className)}\n >\n <ScrollArea className="size-full min-h-0">\n <div\n {...resolvedViewportProps}\n data-slot="pdf-viewer-scroll-content"\n className={cn(\n "min-h-full",\n viewportPropsClassName,\n viewportClassName\n )}\n >\n {children}\n </div>\n </ScrollArea>\n </div>\n )\n}\n\nfunction PDFViewerThumbnails({\n basePageRotations,\n documentId,\n activePage,\n pageCount,\n pageRotationDeltas,\n pdfDocument,\n selectedPageIndexes,\n onSelectPage,\n}: {\n basePageRotations: Rotation[]\n documentId: string\n activePage: number\n pageCount: number\n pageRotationDeltas: PageRotationDeltas\n pdfDocument: PdfDocumentObject | null\n selectedPageIndexes: Set<number>\n onSelectPage: (pageNumber: number, mode: ThumbnailSelectionMode) => void\n}) {\n const thumbnailListboxId = React.useId()\n const activeDescendantId =\n activePage > 0 ? `${thumbnailListboxId}-page-${activePage}` : undefined\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (pageCount < 1) return\n\n const currentPage = activePage > 0 ? activePage : 1\n let nextPage: number | null = null\n\n if (event.key === "ArrowDown") {\n nextPage = Math.min(pageCount, currentPage + 1)\n } else if (event.key === "ArrowUp") {\n nextPage = Math.max(1, currentPage - 1)\n } else if (event.key === "Home") {\n nextPage = 1\n } else if (event.key === "End") {\n nextPage = pageCount\n } else if (event.key === " ") {\n event.preventDefault()\n onSelectPage(currentPage, "toggle")\n return\n }\n\n if (nextPage === null) return\n\n event.preventDefault()\n onSelectPage(nextPage, event.shiftKey ? "range" : "replace")\n },\n [activePage, onSelectPage, pageCount]\n )\n\n return (\n <PDFViewerThumbnailScrollArea\n activeDescendantId={activeDescendantId}\n basePageRotations={basePageRotations}\n documentId={documentId}\n onKeyDown={handleKeyDown}\n pageRotationDeltas={pageRotationDeltas}\n pdfDocument={pdfDocument}\n >\n {(meta: ThumbMeta) => {\n const pageNumber = meta.pageIndex + 1\n const isActive = pageNumber === activePage\n const isSelected = selectedPageIndexes.has(meta.pageIndex)\n const imagePadding = meta.padding ?? 0\n const pageRotationDelta = pageRotationDeltas.get(meta.pageIndex) ?? 0\n const thumbnailImageStyle: React.CSSProperties =\n pageRotationDelta % 2 === 1\n ? {\n height: meta.width,\n transform: `rotate(${rotationToDegrees(pageRotationDelta)}deg)`,\n width: meta.height,\n }\n : {\n height: meta.height,\n transform:\n pageRotationDelta === 0\n ? undefined\n : `rotate(${rotationToDegrees(pageRotationDelta)}deg)`,\n width: meta.width,\n }\n\n return (\n <div\n key={meta.pageIndex}\n data-pdf-viewer-thumbnail={pageNumber}\n className={cn(\n "absolute right-0 left-0 flex justify-center",\n isActive && "z-10"\n )}\n style={{ top: meta.top, height: meta.wrapperHeight }}\n >\n <div\n id={`${thumbnailListboxId}-page-${pageNumber}`}\n role="option"\n data-pdf-viewer-thumbnail-option={pageNumber}\n aria-current={isActive ? "page" : undefined}\n aria-label={`Page ${pageNumber}`}\n aria-posinset={pageNumber}\n aria-selected={isSelected}\n aria-setsize={pageCount}\n data-selected={isSelected ? "" : undefined}\n className={cn(\n "flex h-full w-full cursor-default flex-col items-center justify-between rounded-md px-2 py-0 text-xs transition-shadow outline-none select-none hover:bg-sidebar-accent",\n isActive || isSelected\n ? "bg-sidebar-accent text-foreground"\n : "text-muted-foreground",\n isActive && THUMBNAIL_FOCUS_RING_CLASS\n )}\n onClick={(event) => {\n const mode = event.shiftKey\n ? "range"\n : event.metaKey || event.ctrlKey\n ? "toggle"\n : "replace"\n\n onSelectPage(pageNumber, mode)\n }}\n >\n <span\n className="mt-0 flex items-center justify-center overflow-hidden rounded-md bg-transparent"\n style={{\n width: meta.width + imagePadding * 2,\n height: meta.height + imagePadding * 2,\n padding: imagePadding,\n }}\n >\n <ThumbImg\n documentId={documentId}\n meta={meta}\n className="block rounded-sm object-contain"\n style={thumbnailImageStyle}\n />\n </span>\n <span\n className="flex items-center justify-center tabular-nums"\n style={{ height: meta.labelHeight }}\n >\n <span className="flex min-w-5 items-center justify-center px-1.5 text-center leading-5">\n {pageNumber}\n </span>\n </span>\n </div>\n </div>\n )\n }}\n </PDFViewerThumbnailScrollArea>\n )\n}\n\nfunction PDFViewerThumbnailScrollArea({\n activeDescendantId,\n basePageRotations,\n children,\n documentId,\n onKeyDown,\n pageRotationDeltas,\n pdfDocument,\n}: {\n activeDescendantId?: string\n basePageRotations: Rotation[]\n children: (meta: ThumbMeta) => React.ReactNode\n documentId: string\n onKeyDown: React.KeyboardEventHandler<HTMLDivElement>\n pageRotationDeltas: PageRotationDeltas\n pdfDocument: PdfDocumentObject | null\n}) {\n const { plugin: thumbnailPlugin } = useThumbnailPlugin()\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewportMetrics, setViewportMetrics] = React.useState({\n clientHeight: 0,\n scrollTop: 0,\n })\n const thumbnailScope = React.useMemo(\n () => thumbnailPlugin?.provides().forDocument(documentId) ?? null,\n [documentId, thumbnailPlugin]\n )\n\n const windowState = React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) => {\n if (!thumbnailScope) return () => undefined\n\n return thumbnailScope.onWindow(() => onStoreChange())\n },\n [thumbnailScope]\n ),\n React.useCallback(\n () => thumbnailScope?.getWindow() ?? null,\n [thumbnailScope]\n ),\n () => null\n )\n const hasWindowState = Boolean(windowState)\n const paddingY = thumbnailPlugin?.cfg.paddingY ?? 0\n const thumbnailLayout = React.useMemo(\n () =>\n buildThumbnailLayout({\n basePageRotations,\n pageRotationDeltas,\n pdfDocument,\n width: thumbnailPlugin?.cfg.width ?? THUMBNAIL_WIDTH,\n gap: thumbnailPlugin?.cfg.gap ?? THUMBNAIL_GAP,\n imagePadding: thumbnailPlugin?.cfg.imagePadding ?? 0,\n labelHeight: thumbnailPlugin?.cfg.labelHeight ?? THUMBNAIL_LABEL_HEIGHT,\n paddingY,\n }),\n [\n basePageRotations,\n pageRotationDeltas,\n pdfDocument,\n paddingY,\n thumbnailPlugin,\n ]\n )\n const effectiveWindowState = React.useMemo(() => {\n if (!thumbnailLayout) return windowState\n\n const items = getVisibleThumbnailItems({\n buffer: thumbnailPlugin?.cfg.buffer ?? 3,\n clientHeight: viewportMetrics.clientHeight,\n items: thumbnailLayout.items,\n scrollTop: viewportMetrics.scrollTop,\n })\n\n return {\n start: items[0]?.pageIndex ?? -1,\n end: items.at(-1)?.pageIndex ?? -1,\n items,\n totalHeight: thumbnailLayout.totalHeight,\n }\n }, [thumbnailLayout, thumbnailPlugin, viewportMetrics, windowState])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope) return\n\n const updateWindow = () => {\n setViewportMetrics({\n clientHeight: viewport.clientHeight,\n scrollTop: viewport.scrollTop,\n })\n thumbnailScope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n }\n\n viewport.addEventListener("scroll", updateWindow)\n const frame = window.requestAnimationFrame(updateWindow)\n\n return () => {\n window.cancelAnimationFrame(frame)\n viewport.removeEventListener("scroll", updateWindow)\n }\n }, [thumbnailScope])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope) return\n\n const resizeObserver = new ResizeObserver(() => {\n setViewportMetrics({\n clientHeight: viewport.clientHeight,\n scrollTop: viewport.scrollTop,\n })\n thumbnailScope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n })\n\n resizeObserver.observe(viewport)\n\n return () => resizeObserver.disconnect()\n }, [thumbnailScope])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope) return\n\n thumbnailScope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n }, [thumbnailLayout, thumbnailScope, windowState])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope || !hasWindowState) return\n\n return thumbnailScope.onScrollTo(({ top, behavior }) => {\n viewport.scrollTo({ top, behavior })\n })\n }, [hasWindowState, thumbnailScope])\n\n return (\n <PDFViewerScrollArea\n className="h-full w-full"\n viewportClassName="group/pdf-thumbnail-sidebar px-4 focus-visible:ring-0 focus-visible:ring-offset-0"\n viewportProps={{\n "aria-activedescendant": activeDescendantId,\n "aria-label": "PDF pages",\n "aria-multiselectable": true,\n onKeyDown,\n onMouseDown: (event) => {\n event.currentTarget.focus({ preventScroll: true })\n },\n role: "listbox",\n style: {\n paddingBottom: paddingY,\n paddingTop: paddingY,\n },\n tabIndex: 0,\n }}\n viewportRef={viewportRef}\n >\n <div\n className="relative"\n style={{ height: effectiveWindowState?.totalHeight ?? 0 }}\n >\n {effectiveWindowState?.items.map((meta) => children(meta))}\n </div>\n </PDFViewerScrollArea>\n )\n}\n\nfunction PDFViewerScrollAreaViewport({\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 <PDFViewerScrollArea\n className={className}\n viewportClassName="relative select-none selection:bg-transparent selection:text-inherit"\n viewportProps={{\n style: {\n padding: viewportGap,\n },\n }}\n viewportRef={viewportRef}\n >\n {isGated ? null : children}\n </PDFViewerScrollArea>\n </ViewportElementContext.Provider>\n )\n}\n\n// Captures the scrollable viewport element so the imperative handle can expose\n// it.\nfunction PDFViewerViewportBridge({\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\nfunction PDFViewerTextSelectionLayer({\n documentId,\n pageIndex,\n scale,\n}: {\n documentId: string\n pageIndex: number\n scale: number\n}) {\n const { plugin: selectionPlugin } = useSelectionPlugin()\n const [rects, setRects] = React.useState<Rect[]>([])\n\n React.useEffect(() => {\n if (!selectionPlugin) return\n\n return selectionPlugin.registerSelectionOnPage({\n documentId,\n pageIndex,\n onRectsChange: ({ rects: nextRects }) => {\n setRects(nextRects)\n },\n })\n }, [documentId, pageIndex, selectionPlugin])\n\n if (!rects.length) return null\n\n return (\n <>\n {rects.map((rect, index) => (\n <div\n key={`${index}-${rect.origin.x}-${rect.origin.y}`}\n className="pointer-events-none absolute"\n style={{\n background: TEXT_SELECTION_BACKGROUND,\n height: rect.size.height * scale,\n left: rect.origin.x * scale,\n top: rect.origin.y * scale,\n width: rect.size.width * scale,\n }}\n />\n ))}\n </>\n )\n}\n\nfunction PDFViewerSelectionReleaseGuard({\n documentId,\n}: {\n documentId: string\n}) {\n const { plugin: selectionPlugin } = useSelectionPlugin()\n const { provides: selection } = useSelectionCapability()\n const lastSelectionModeIdRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n if (!selection) return\n\n return selection.forDocument(documentId).onBeginSelection(({ modeId }) => {\n lastSelectionModeIdRef.current = modeId\n })\n }, [documentId, selection])\n\n React.useEffect(() => {\n if (!selection) return\n\n let cleanupFrame = 0\n const finalizeIfStillSelecting = () => {\n window.cancelAnimationFrame(cleanupFrame)\n cleanupFrame = window.requestAnimationFrame(() => {\n const selectionState = selection.getState(documentId)\n\n if (!selectionState.selecting) return\n\n if (selectionState.selection && selectionPlugin) {\n const pluginWithEndSelection = selectionPlugin as unknown as {\n endSelection?: (documentId: string, modeId: string) => void\n }\n\n pluginWithEndSelection.endSelection?.(\n documentId,\n lastSelectionModeIdRef.current ?? "pointerMode"\n )\n return\n }\n\n if (!selectionState.selection) {\n selection.clear(documentId)\n }\n })\n }\n\n window.addEventListener("pointerup", finalizeIfStillSelecting)\n window.addEventListener("pointercancel", finalizeIfStillSelecting)\n window.addEventListener("blur", finalizeIfStillSelecting)\n\n return () => {\n window.cancelAnimationFrame(cleanupFrame)\n window.removeEventListener("pointerup", finalizeIfStillSelecting)\n window.removeEventListener("pointercancel", finalizeIfStillSelecting)\n window.removeEventListener("blur", finalizeIfStillSelecting)\n }\n }, [documentId, selection, selectionPlugin])\n\n return null\n}\n\nfunction isEditableCopyTarget(target: EventTarget | null) {\n if (!(target instanceof HTMLElement)) return false\n\n if (target.isContentEditable) return true\n\n return Boolean(target.closest("input, textarea, [contenteditable=\'true\']"))\n}\n\nfunction PDFViewerSelectionCopyShortcut({\n documentId,\n}: {\n documentId: string\n}) {\n const { provides: selection } = useSelectionCapability()\n\n React.useEffect(() => {\n if (!selection) return\n\n const copySelectedPdfText = (event: Event) => {\n if (isEditableCopyTarget(event.target)) return\n if (!selection.getState(documentId).selection) return\n\n event.preventDefault()\n selection.copyToClipboard(documentId)\n }\n\n const handleKeyDown = (event: KeyboardEvent) => {\n if (event.key.toLowerCase() !== "c") return\n if (!event.metaKey && !event.ctrlKey) return\n\n copySelectedPdfText(event)\n }\n\n document.addEventListener("copy", copySelectedPdfText)\n document.addEventListener("keydown", handleKeyDown)\n\n return () => {\n document.removeEventListener("copy", copySelectedPdfText)\n document.removeEventListener("keydown", handleKeyDown)\n }\n }, [documentId, selection])\n\n return null\n}\n\nfunction isQuarterTurn(rotation: Rotation) {\n return rotation % 2 === 1\n}\n\nfunction getRotatedDimensions({\n height,\n rotation,\n width,\n}: {\n height: number\n rotation: Rotation\n width: number\n}) {\n return isQuarterTurn(rotation)\n ? { height: width, width: height }\n : { height, width }\n}\n\nfunction getRotatedPageDimensions(page: PageLayout, rotation: Rotation) {\n return getRotatedDimensions({\n height: page.height,\n rotation,\n width: page.width,\n })\n}\n\nfunction applyPageRotationDeltasToScrollerLayout({\n basePageRotations,\n layout,\n pageRotationDeltas,\n}: {\n basePageRotations: Rotation[]\n layout: ScrollerLayout\n pageRotationDeltas: PageRotationDeltas\n}): ScrollerLayout {\n if (pageRotationDeltas.size === 0) return layout\n\n let maxWidth = 0\n let maxHeight = 0\n let offset = 0\n const pageGap = layout.pageGap\n let startSpacingAdjustment = 0\n const items: VirtualItem[] = layout.items.map((item, itemIndex) => {\n let pageOffset = 0\n let itemWidth = 0\n let itemHeight = 0\n const pageLayouts = item.pageLayouts.map((page) => {\n const basePageRotation =\n basePageRotations[page.pageIndex] ?? normalizeRotation(0)\n const pageRotation = normalizeRotation(\n basePageRotation + (pageRotationDeltas.get(page.pageIndex) ?? 0)\n )\n const rotatedSize = getRotatedPageDimensions(page, pageRotation)\n const oldScrollAxisSize =\n layout.strategy === ScrollStrategy.Horizontal\n ? page.rotatedWidth\n : page.rotatedHeight\n const newScrollAxisSize =\n layout.strategy === ScrollStrategy.Horizontal\n ? rotatedSize.width\n : rotatedSize.height\n\n if (\n layout.startSpacing === 0 &&\n itemIndex === 0 &&\n pageOffset === 0 &&\n newScrollAxisSize < oldScrollAxisSize\n ) {\n startSpacingAdjustment = Math.max(\n startSpacingAdjustment,\n (oldScrollAxisSize - newScrollAxisSize) / 2\n )\n }\n\n const nextPageLayout = {\n ...page,\n rotatedHeight: rotatedSize.height,\n rotatedWidth: rotatedSize.width,\n x: layout.strategy === ScrollStrategy.Horizontal ? 0 : pageOffset,\n y: layout.strategy === ScrollStrategy.Horizontal ? pageOffset : 0,\n }\n\n pageOffset +=\n (layout.strategy === ScrollStrategy.Horizontal\n ? rotatedSize.height\n : rotatedSize.width) + pageGap\n itemWidth =\n layout.strategy === ScrollStrategy.Horizontal\n ? Math.max(itemWidth, rotatedSize.width)\n : itemWidth + rotatedSize.width\n itemHeight =\n layout.strategy === ScrollStrategy.Horizontal\n ? itemHeight + rotatedSize.height\n : Math.max(itemHeight, rotatedSize.height)\n\n return nextPageLayout\n })\n\n if (pageLayouts.length > 1) {\n if (layout.strategy === ScrollStrategy.Horizontal) {\n itemHeight -= pageGap\n } else {\n itemWidth -= pageGap\n }\n }\n\n const nextItem = {\n ...item,\n height: itemHeight,\n offset,\n pageLayouts,\n width: itemWidth,\n x: layout.strategy === ScrollStrategy.Horizontal ? offset : item.x,\n y: layout.strategy === ScrollStrategy.Horizontal ? item.y : offset,\n }\n\n if (layout.strategy === ScrollStrategy.Horizontal) {\n offset += itemWidth + pageGap\n maxHeight = Math.max(maxHeight, itemHeight)\n } else {\n offset += itemHeight + pageGap\n maxWidth = Math.max(maxWidth, itemWidth)\n }\n\n return nextItem\n })\n\n if (items.length > 0) {\n offset -= pageGap\n }\n\n return {\n ...layout,\n endSpacing: layout.endSpacing,\n items,\n startSpacing: layout.startSpacing + startSpacingAdjustment,\n totalHeight:\n layout.strategy === ScrollStrategy.Horizontal\n ? maxHeight\n : layout.startSpacing +\n startSpacingAdjustment +\n offset +\n layout.endSpacing,\n totalWidth:\n layout.strategy === ScrollStrategy.Horizontal\n ? layout.startSpacing +\n startSpacingAdjustment +\n offset +\n layout.endSpacing\n : maxWidth,\n }\n}\n\nfunction PDFViewerScroller({\n documentId,\n pageRotationDeltas,\n basePageRotations,\n renderPage,\n}: {\n documentId: string\n pageRotationDeltas: PageRotationDeltas\n basePageRotations: Rotation[]\n renderPage: (props: PageLayout) => React.ReactNode\n}) {\n const { plugin: scrollPlugin } = useScrollPlugin()\n const [layoutData, setLayoutData] = React.useState<{\n docId: string | null\n layout: ScrollerLayout | null\n }>({ docId: null, layout: null })\n\n React.useEffect(() => {\n if (!scrollPlugin || !documentId) return\n let frame = 0\n\n const setCurrentLayout = () => {\n try {\n setLayoutData({\n docId: documentId,\n layout: scrollPlugin.getScrollerLayout(documentId),\n })\n } catch {\n setLayoutData({ docId: documentId, layout: null })\n }\n }\n\n const unsubscribe = scrollPlugin.onScrollerData(documentId, (layout) => {\n setLayoutData({ docId: documentId, layout })\n })\n\n frame = window.requestAnimationFrame(setCurrentLayout)\n\n return () => {\n window.cancelAnimationFrame(frame)\n unsubscribe()\n setLayoutData({ docId: null, layout: null })\n scrollPlugin.clearLayoutReady(documentId)\n }\n }, [documentId, scrollPlugin])\n\n const scrollerLayout = React.useMemo(() => {\n if (layoutData.docId !== documentId || !layoutData.layout) return null\n\n return applyPageRotationDeltasToScrollerLayout({\n basePageRotations,\n layout: layoutData.layout,\n pageRotationDeltas,\n })\n }, [basePageRotations, documentId, layoutData, pageRotationDeltas])\n\n React.useLayoutEffect(() => {\n if (!scrollPlugin || !documentId || !scrollerLayout) return\n scrollPlugin.setLayoutReady(documentId)\n }, [documentId, scrollPlugin, scrollerLayout])\n\n if (!scrollerLayout) return null\n\n return (\n <div\n style={{\n width: `${scrollerLayout.totalWidth}px`,\n height: `${scrollerLayout.totalHeight}px`,\n position: "relative",\n boxSizing: "border-box",\n margin: "0 auto",\n ...(scrollerLayout.strategy === ScrollStrategy.Horizontal && {\n display: "flex",\n flexDirection: "row",\n }),\n }}\n >\n <div\n style={\n scrollerLayout.strategy === ScrollStrategy.Horizontal\n ? {\n width: scrollerLayout.startSpacing,\n height: "100%",\n flexShrink: 0,\n }\n : {\n height: scrollerLayout.startSpacing,\n width: "100%",\n }\n }\n />\n <div\n style={{\n gap: scrollerLayout.pageGap,\n display: "flex",\n alignItems: "center",\n position: "relative",\n boxSizing: "border-box",\n ...(scrollerLayout.strategy === ScrollStrategy.Horizontal\n ? {\n flexDirection: "row",\n minHeight: "100%",\n }\n : {\n flexDirection: "column",\n minWidth: "fit-content",\n }),\n }}\n >\n {scrollerLayout.items.map((item) => (\n <div\n key={item.pageNumbers[0]}\n style={{\n display: "flex",\n justifyContent: "center",\n gap: scrollerLayout.pageGap,\n }}\n >\n {item.pageLayouts.map((layout) => (\n <div\n key={layout.pageNumber}\n style={{\n width: `${layout.rotatedWidth}px`,\n height: `${layout.rotatedHeight}px`,\n position: "relative",\n zIndex: layout.elevated ? 1 : undefined,\n }}\n >\n {renderPage(layout)}\n </div>\n ))}\n </div>\n ))}\n </div>\n <div\n style={\n scrollerLayout.strategy === ScrollStrategy.Horizontal\n ? {\n width: scrollerLayout.endSpacing,\n height: "100%",\n flexShrink: 0,\n }\n : {\n height: scrollerLayout.endSpacing,\n width: "100%",\n }\n }\n />\n </div>\n )\n}\n\ntype PDFViewerInnerProps = {\n viewerRef: React.ForwardedRef<PDFViewerHandle>\n pdfFile: string\n documentId: string\n document: PdfDocumentObject | null\n defaultZoom: number\n className?: string\n fileName?: string\n showDownload: boolean\n showToolbar: boolean\n showRotateControls: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onActivePageChange?: (pageNumber: number) => void\n onPdfUpload?: (file: File) => void\n onPagePointerDown?: PDFViewerProps["onPagePointerDown"]\n onPagePointerMove?: PDFViewerProps["onPagePointerMove"]\n onPagePointerUp?: PDFViewerProps["onPagePointerUp"]\n onPagePointerCancel?: PDFViewerProps["onPagePointerCancel"]\n onUploadFile: (file: File) => void\n}\n\nfunction PDFViewerInner({\n viewerRef,\n pdfFile,\n documentId,\n document: pdfDocument,\n defaultZoom,\n className,\n fileName,\n showDownload,\n showToolbar,\n showRotateControls,\n showUpload,\n toolbarActions,\n pageClassName,\n renderPageOverlay,\n onActivePageChange,\n onPdfUpload,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n onUploadFile,\n}: PDFViewerInnerProps) {\n const { registry } = useRegistry()\n const { state: scrollState, provides: scroll } = useScroll(documentId)\n const { state: zoomState, provides: zoom } = useZoom(documentId)\n const { provides: thumbnails } = useThumbnailCapability()\n const { plugin: thumbnailPlugin } = useThumbnailPlugin()\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)\n const [pageRotationDeltas, setPageRotationDeltas] =\n React.useState<PageRotationDeltas>(() => new Map())\n const [selectedPageIndexes, setSelectedPageIndexes] = React.useState<\n Set<number>\n >(() => new Set())\n const basePageRotations = React.useMemo(\n () =>\n pdfDocument?.pages.map((page) => normalizeRotation(page.rotation)) ?? [],\n [pdfDocument]\n )\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const viewportElementRef = React.useRef<HTMLDivElement | null>(null)\n const pageRotationDeltasRef = React.useRef(pageRotationDeltas)\n const selectedPageIndexesRef = React.useRef(selectedPageIndexes)\n const selectionAnchorPageIndexRef = React.useRef<number | null>(null)\n const suppressActivePageSelectionSyncRef = React.useRef<number | null>(null)\n const initializedSelectionDocumentRef = React.useRef<string | null>(null)\n\n const activePage = scrollState.currentPage\n const numPages = pdfDocument?.pageCount ?? 0\n const isLoading = !pdfDocument\n const controlsDisabled = !numPages\n const downloadDisabled = controlsDisabled || isPreparingDownload\n const thumbnailSidebarVisible = sidebarOpen && !isLoading\n const currentZoomLevel = zoomState.currentZoomLevel\n const alignedThumbnailSidebarDocumentRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n pageRotationDeltasRef.current = pageRotationDeltas\n }, [pageRotationDeltas])\n\n React.useEffect(() => {\n selectedPageIndexesRef.current = selectedPageIndexes\n }, [selectedPageIndexes])\n\n React.useEffect(() => {\n if (activePage > 0) onActivePageChange?.(activePage)\n }, [activePage, onActivePageChange])\n\n React.useEffect(() => {\n if (activePage < 1 || numPages < 1) return\n\n const activePageIndex = activePage - 1\n const suppressedPageIndex = suppressActivePageSelectionSyncRef.current\n\n suppressActivePageSelectionSyncRef.current = null\n\n if (suppressedPageIndex === activePageIndex) return\n\n const nextSelection = new Set([activePageIndex])\n\n selectionAnchorPageIndexRef.current = activePageIndex\n selectedPageIndexesRef.current = nextSelection\n setSelectedPageIndexes((previousSelection) =>\n arePageIndexSetsEqual(previousSelection, nextSelection)\n ? previousSelection\n : nextSelection\n )\n }, [activePage, numPages])\n\n React.useEffect(() => {\n if (\n numPages < 1 ||\n initializedSelectionDocumentRef.current === documentId\n ) {\n return\n }\n\n const initialPageIndex = Math.max(0, (activePage > 0 ? activePage : 1) - 1)\n const initialSelection = new Set([initialPageIndex])\n\n initializedSelectionDocumentRef.current = documentId\n selectionAnchorPageIndexRef.current = initialPageIndex\n selectedPageIndexesRef.current = initialSelection\n setSelectedPageIndexes(initialSelection)\n }, [activePage, documentId, numPages])\n\n React.useEffect(() => {\n if (!thumbnailSidebarVisible) {\n alignedThumbnailSidebarDocumentRef.current = null\n return\n }\n\n if (\n activePage < 1 ||\n !thumbnails ||\n alignedThumbnailSidebarDocumentRef.current === documentId\n ) {\n return\n }\n\n alignedThumbnailSidebarDocumentRef.current = documentId\n const frame = window.requestAnimationFrame(() => {\n thumbnails.forDocument(documentId).scrollToThumb(activePage - 1)\n })\n\n return () => window.cancelAnimationFrame(frame)\n }, [activePage, documentId, thumbnailSidebarVisible, thumbnails])\n\n // The zoom plugin only releases its viewport gate for mode-based zoom\n // levels (automatic/fit); with a numeric default the gate would never\n // lift, so apply the initial zoom explicitly once the document loads.\n const initialZoomDocumentRef = React.useRef<string | null>(null)\n React.useEffect(() => {\n if (!pdfDocument || !zoom) return\n if (initialZoomDocumentRef.current === documentId) return\n\n initialZoomDocumentRef.current = documentId\n zoom.requestZoom(defaultZoom)\n }, [defaultZoom, documentId, pdfDocument, zoom])\n\n const scrollToPage = React.useCallback(\n (pageNumber: number, options?: ScrollIntoViewOptions) => {\n scroll?.scrollToPage({\n pageNumber,\n behavior: options?.behavior === "smooth" ? "smooth" : "auto",\n })\n },\n [scroll]\n )\n\n const selectThumbnailPage = React.useCallback(\n (pageNumber: number, mode: ThumbnailSelectionMode) => {\n const pageIndex = pageNumber - 1\n\n if (pageIndex < 0 || pageIndex >= numPages) return\n\n suppressActivePageSelectionSyncRef.current = pageIndex\n\n setSelectedPageIndexes((previousSelection) => {\n let nextSelection: Set<number>\n\n if (mode === "range") {\n const anchorPageIndex =\n selectionAnchorPageIndexRef.current ??\n (activePage > 0 ? activePage - 1 : pageIndex)\n\n nextSelection = getPageIndexRange(anchorPageIndex, pageIndex)\n } else if (mode === "toggle") {\n nextSelection = new Set(previousSelection)\n\n if (nextSelection.has(pageIndex)) {\n nextSelection.delete(pageIndex)\n } else {\n nextSelection.add(pageIndex)\n }\n\n selectionAnchorPageIndexRef.current = pageIndex\n } else {\n nextSelection = new Set([pageIndex])\n selectionAnchorPageIndexRef.current = pageIndex\n }\n\n selectedPageIndexesRef.current = nextSelection\n return nextSelection\n })\n\n scrollToPage(pageNumber)\n },\n [activePage, numPages, scrollToPage]\n )\n\n React.useImperativeHandle(\n viewerRef,\n () => ({\n scrollToPage,\n scrollToPageArea: (pageNumber, area, options) => {\n const pageSize = pdfDocument?.pages[pageNumber - 1]?.size\n\n scroll?.scrollToPage({\n pageNumber,\n ...(pageSize\n ? {\n pageCoordinates: {\n x: ((area.left ?? 0) / 100) * pageSize.width,\n y: (area.top / 100) * pageSize.height,\n },\n alignY: 25,\n }\n : {}),\n behavior: options?.behavior === "smooth" ? "smooth" : "auto",\n })\n },\n getViewportElement: () => viewportElementRef.current,\n }),\n [pdfDocument, scroll, scrollToPage]\n )\n\n const handleDownload = React.useCallback(async () => {\n if (!pdfFile || isPreparingDownload) return\n\n setIsPreparingDownload(true)\n\n try {\n await downloadPdfWithPageRotations({\n fileName: getPdfDownloadFileName(fileName, pdfFile),\n pageRotationDeltas,\n src: pdfFile,\n })\n } catch (error) {\n console.error(error)\n } finally {\n setIsPreparingDownload(false)\n }\n }, [fileName, isPreparingDownload, pageRotationDeltas, pdfFile])\n\n const rotateSelectedPages = React.useCallback(\n (direction: -1 | 1) => {\n if (!pdfDocument || !registry || activePage < 1) return\n\n const documentState = registry.getStore().getState().core.documents[\n documentId\n ]\n const currentDocument = documentState?.document ?? pdfDocument\n const selectedTargetPageIndexes = Array.from(\n selectedPageIndexesRef.current\n ).filter((pageIndex) => currentDocument.pages[pageIndex])\n const fallbackPageIndex = activePage - 1\n const targetPageIndexes = (\n selectedTargetPageIndexes.length\n ? selectedTargetPageIndexes\n : [fallbackPageIndex]\n )\n .filter((pageIndex) => currentDocument.pages[pageIndex])\n .sort((a, b) => a - b)\n\n if (targetPageIndexes.length === 0) return\n\n const previousDeltas = pageRotationDeltasRef.current\n const nextDeltas = new Map(previousDeltas)\n const referencePageIndex =\n activePage > 0 && currentDocument.pages[activePage - 1]\n ? activePage - 1\n : targetPageIndexes[0]\n let scrollDelta = 0\n\n for (const pageIndex of targetPageIndexes) {\n const currentPage = currentDocument.pages[pageIndex]\n if (!currentPage) continue\n\n const previousDelta = previousDeltas.get(pageIndex) ?? 0\n const nextDelta = normalizeRotation(previousDelta + direction)\n const basePageRotation =\n basePageRotations[pageIndex] ??\n normalizeRotation(currentPage.rotation)\n const previousPageRotation = normalizeRotation(\n basePageRotation + previousDelta\n )\n const nextPageRotation = normalizeRotation(basePageRotation + nextDelta)\n const previousRotatedSize = getRotatedDimensions({\n height: currentPage.size.height * currentZoomLevel,\n rotation: previousPageRotation,\n width: currentPage.size.width * currentZoomLevel,\n })\n const nextRotatedSize = getRotatedDimensions({\n height: currentPage.size.height * currentZoomLevel,\n rotation: nextPageRotation,\n width: currentPage.size.width * currentZoomLevel,\n })\n const heightDelta = nextRotatedSize.height - previousRotatedSize.height\n\n if (pageIndex < referencePageIndex) {\n scrollDelta += heightDelta\n } else if (pageIndex === referencePageIndex) {\n scrollDelta += heightDelta / 2\n }\n\n if (nextDelta) {\n nextDeltas.set(pageIndex, nextDelta)\n } else {\n nextDeltas.delete(pageIndex)\n }\n }\n\n const store = registry.getStore()\n const viewport = viewportElementRef.current\n\n pageRotationDeltasRef.current = nextDeltas\n flushSync(() => {\n setPageRotationDeltas(nextDeltas)\n store.dispatchToCore(refreshPages(documentId, targetPageIndexes))\n })\n\n if (viewport && scrollDelta !== 0) {\n viewport.scrollTop += scrollDelta\n }\n ;(\n thumbnailPlugin as {\n calculateWindowState?: (documentId: string) => void\n } | null\n )?.calculateWindowState?.(documentId)\n },\n [\n activePage,\n basePageRotations,\n currentZoomLevel,\n documentId,\n pdfDocument,\n registry,\n thumbnailPlugin,\n ]\n )\n\n const handleUpload = React.useCallback(\n (file: File) => {\n onUploadFile(file)\n onPdfUpload?.(file)\n },\n [onPdfUpload, onUploadFile]\n )\n\n const renderPage = React.useCallback(\n (page: PageLayout) => {\n const pageNumber = page.pageNumber\n const basePageRotation =\n basePageRotations[page.pageIndex] ??\n pdfDocument?.pages[page.pageIndex]?.rotation ??\n normalizeRotation(0)\n const pageRotation = normalizeRotation(\n basePageRotation + (pageRotationDeltas.get(page.pageIndex) ?? 0)\n )\n\n return (\n <Rotate\n documentId={documentId}\n pageIndex={page.pageIndex}\n rotation={pageRotation}\n >\n <PagePointerProvider\n documentId={documentId}\n pageIndex={page.pageIndex}\n rotation={pageRotation}\n key={`${page.pageIndex}-${pageRotation}`}\n data-pdf-viewer-page={pageNumber}\n className={cn(\n "relative border border-transparent bg-transparent shadow-xs select-none selection:bg-transparent selection:text-inherit",\n pageClassName?.(pageNumber)\n )}\n style={{ backgroundColor: "transparent" }}\n onPointerDown={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerDown?.(event, pageNumber)\n }\n onPointerMove={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerMove?.(event, pageNumber)\n }\n onPointerUp={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerUp?.(event, pageNumber)\n }\n onPointerCancel={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerCancel?.(event, pageNumber)\n }\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(currentZoomLevel, 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 key={`tiles-${page.pageIndex}-${pageRotation}`}\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 <PDFViewerTextSelectionLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n scale={currentZoomLevel}\n />\n {renderPageOverlay?.({\n pageNumber,\n pageWidth: page.width,\n pageHeight: page.height,\n scale: currentZoomLevel,\n rotation: rotationToDegrees(pageRotation),\n })}\n </PagePointerProvider>\n </Rotate>\n )\n },\n [\n basePageRotations,\n currentZoomLevel,\n onPagePointerCancel,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n pageClassName,\n pageRotationDeltas,\n renderPageOverlay,\n documentId,\n pdfDocument,\n ]\n )\n\n return (\n <div\n data-slot="pdf-viewer"\n className={cn(\n "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n {showToolbar ? (\n <PDFViewerToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n currentZoomLevel={currentZoomLevel}\n downloadDisabled={downloadDisabled}\n isPreparingDownload={isPreparingDownload}\n numPages={numPages}\n searchControl={\n <PDFViewerSearchControl\n key={documentId}\n documentId={documentId}\n controlsDisabled={controlsDisabled}\n />\n }\n showDownload={showDownload}\n showRotateControls={showRotateControls}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n onDownload={handleDownload}\n onPageChange={scrollToPage}\n onRotate={rotateSelectedPages}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadFile={handleUpload}\n onZoomChange={(zoomLevel) => zoom?.requestZoom(zoomLevel)}\n />\n ) : null}\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {isLoading ? (\n <PDFViewerLoadingSkeleton\n sidebarInline={sidebarInline}\n sidebarOpen={sidebarOpen}\n />\n ) : null}\n <div className="flex h-full max-h-full min-h-0 w-full flex-1 overflow-hidden">\n <DocumentViewerThumbnailSidebar\n closedInlineClassName={THUMBNAIL_SIDEBAR_CLOSED_CLASS}\n inline={sidebarInline}\n open={thumbnailSidebarVisible}\n widthClassName={THUMBNAIL_SIDEBAR_WIDTH_CLASS}\n >\n {thumbnailSidebarVisible ? (\n <PDFViewerThumbnails\n basePageRotations={basePageRotations}\n documentId={documentId}\n activePage={activePage}\n pageCount={numPages}\n pageRotationDeltas={pageRotationDeltas}\n pdfDocument={pdfDocument}\n selectedPageIndexes={selectedPageIndexes}\n onSelectPage={selectThumbnailPage}\n />\n ) : null}\n </DocumentViewerThumbnailSidebar>\n <PDFViewerScrollAreaViewport\n documentId={documentId}\n className="relative h-full max-h-full min-h-0 min-w-0 flex-1"\n >\n <PDFViewerViewportBridge viewportElementRef={viewportElementRef} />\n <PDFViewerSelectionCopyShortcut documentId={documentId} />\n <PDFViewerSelectionReleaseGuard documentId={documentId} />\n <GlobalPointerProvider documentId={documentId}>\n <PDFViewerScroller\n basePageRotations={basePageRotations}\n documentId={documentId}\n pageRotationDeltas={pageRotationDeltas}\n renderPage={renderPage}\n />\n </GlobalPointerProvider>\n <CopyToClipboard />\n </PDFViewerScrollAreaViewport>\n </div>\n </div>\n </div>\n )\n}\n\nfunction PDFViewerDocumentLoader({\n pdfFile,\n onDocumentLoadSuccess,\n ...innerProps\n}: {\n pdfFile: string\n onDocumentLoadSuccess?: (numPages: number) => void\n} & Omit<PDFViewerInnerProps, "pdfFile" | "documentId" | "document">) {\n const { provides: documentManager } = useDocumentManagerCapability()\n const { activeDocumentId, activeDocument } = useActiveDocument()\n const [loadError, setLoadError] = React.useState(false)\n const openedFileRef = React.useRef<string | null>(null)\n const onDocumentLoadSuccessRef = React.useRef(onDocumentLoadSuccess)\n\n React.useEffect(() => {\n onDocumentLoadSuccessRef.current = onDocumentLoadSuccess\n })\n\n React.useEffect(() => {\n if (!documentManager || !pdfFile) return\n if (openedFileRef.current === pdfFile) return\n\n openedFileRef.current = pdfFile\n setLoadError(false)\n\n const previousDocumentIds = documentManager\n .getOpenDocuments()\n .map((openDocument) => openDocument.id)\n const handleOpenError = () => {\n if (openedFileRef.current === pdfFile) setLoadError(true)\n }\n\n documentManager\n .openDocumentUrl({\n url: pdfFile,\n mode: pdfFile.startsWith("blob:") ? "full-fetch" : "auto",\n })\n .wait((response) => {\n response.task.wait((openedDocument) => {\n onDocumentLoadSuccessRef.current?.(openedDocument.pageCount)\n previousDocumentIds.forEach((documentIdToClose) => {\n documentManager.closeDocument(documentIdToClose).wait(\n () => undefined,\n () => undefined\n )\n })\n }, handleOpenError)\n }, handleOpenError)\n }, [documentManager, pdfFile])\n\n const document =\n activeDocument?.status === "loaded" ? activeDocument.document : null\n const documentFailed = loadError || activeDocument?.status === "error"\n\n if (!activeDocumentId || documentFailed || !pdfFile) {\n return (\n <PDFViewerFallbackShell\n className={innerProps.className}\n defaultZoom={innerProps.defaultZoom}\n showDownload={innerProps.showDownload}\n showRotateControls={innerProps.showRotateControls}\n showToolbar={innerProps.showToolbar}\n showUpload={innerProps.showUpload}\n sidebarOpen={false}\n state={!pdfFile ? "empty" : documentFailed ? "error" : "loading"}\n toolbarActions={innerProps.toolbarActions}\n onUploadFile={(file) => {\n innerProps.onUploadFile(file)\n innerProps.onPdfUpload?.(file)\n }}\n />\n )\n }\n\n return (\n <PDFViewerInner\n key={activeDocumentId}\n {...innerProps}\n pdfFile={pdfFile}\n documentId={activeDocumentId}\n document={document}\n />\n )\n}\n\nexport const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(\n function PDFViewer(\n {\n className,\n defaultZoom = DEFAULT_ZOOM,\n fileName,\n resolveScrollAreaViewport,\n showDownload = true,\n showRotateControls = true,\n showToolbar = true,\n showUpload = true,\n src,\n toolbarActions,\n pageClassName,\n renderPageOverlay,\n onActivePageChange,\n onDocumentLoadSuccess,\n onPdfUpload,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n },\n ref\n ) {\n const { engine, error: engineError } = useSharedPdfEngine()\n const [uploadedPdfFile, setUploadedPdfFile] = React.useState<{\n src: string | undefined\n url: string | null\n }>(() => ({ src, url: null }))\n const uploadedPdfUrl =\n uploadedPdfFile.src === src ? uploadedPdfFile.url : null\n const pdfFile = uploadedPdfUrl ?? src ?? ""\n\n React.useEffect(\n () => () => {\n if (uploadedPdfUrl) URL.revokeObjectURL(uploadedPdfUrl)\n },\n [uploadedPdfUrl]\n )\n\n const handleUploadFile = React.useCallback(\n (nextFile: File) => {\n const nextUrl = URL.createObjectURL(nextFile)\n\n setUploadedPdfFile({ src, url: nextUrl })\n },\n [src]\n )\n\n // Plugin registrations are created once per viewer 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 marquee: { enabled: false },\n }),\n createPluginRegistration(SearchPluginPackage, {\n showAllResults: true,\n }),\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: defaultZoom,\n minZoom: ZOOM_OPTIONS[0],\n maxZoom: ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1],\n }),\n createPluginRegistration(RotatePluginPackage),\n ])\n\n if (engineError) {\n return (\n <PDFViewerFallbackShell\n className={className}\n defaultZoom={defaultZoom}\n errorMessage="Unable to load the PDF engine."\n showDownload={showDownload}\n showRotateControls={showRotateControls}\n showToolbar={showToolbar}\n showUpload={showUpload}\n sidebarOpen={false}\n state="error"\n toolbarActions={toolbarActions}\n onUploadFile={(file) => {\n handleUploadFile(file)\n onPdfUpload?.(file)\n }}\n />\n )\n }\n\n if (!engine) {\n return (\n <PDFViewerFallbackShell\n className={className}\n defaultZoom={defaultZoom}\n showDownload={showDownload}\n showRotateControls={showRotateControls}\n showToolbar={showToolbar}\n showUpload={showUpload}\n sidebarOpen={false}\n state="loading"\n toolbarActions={toolbarActions}\n onUploadFile={(file) => {\n handleUploadFile(file)\n onPdfUpload?.(file)\n }}\n />\n )\n }\n\n return (\n <PDFViewerScrollAreaResolverContext.Provider\n value={resolveScrollAreaViewport ?? resolveDefaultScrollAreaViewport}\n >\n <EmbedPDF engine={engine} plugins={plugins}>\n <PDFViewerDocumentLoader\n viewerRef={ref}\n pdfFile={pdfFile}\n defaultZoom={defaultZoom}\n className={className}\n fileName={fileName}\n showDownload={showDownload}\n showToolbar={showToolbar}\n showRotateControls={showRotateControls}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n pageClassName={pageClassName}\n renderPageOverlay={renderPageOverlay}\n onActivePageChange={onActivePageChange}\n onDocumentLoadSuccess={onDocumentLoadSuccess}\n onPdfUpload={onPdfUpload}\n onPagePointerDown={onPagePointerDown}\n onPagePointerMove={onPagePointerMove}\n onPagePointerUp={onPagePointerUp}\n onPagePointerCancel={onPagePointerCancel}\n onUploadFile={handleUploadFile}\n />\n </EmbedPDF>\n </PDFViewerScrollAreaResolverContext.Provider>\n )\n }\n)\n'+ '"use client"\n\nimport * as React from "react"\nimport { createPluginRegistration, refreshPages } from "@embedpdf/core"\nimport { EmbedPDF, useRegistry } from "@embedpdf/core/react"\nimport type {\n PdfDocumentObject,\n PdfEngine,\n Rect,\n Rotation,\n} from "@embedpdf/models"\nimport {\n DocumentManagerPluginPackage,\n useActiveDocument,\n useDocumentManagerCapability,\n} from "@embedpdf/plugin-document-manager/react"\nimport {\n GlobalPointerProvider,\n InteractionManagerPluginPackage,\n PagePointerProvider,\n} from "@embedpdf/plugin-interaction-manager/react"\nimport { RenderLayer, RenderPluginPackage } from "@embedpdf/plugin-render/react"\nimport { Rotate, RotatePluginPackage } from "@embedpdf/plugin-rotate/react"\nimport {\n ScrollPluginPackage,\n ScrollStrategy,\n useScroll,\n useScrollPlugin,\n type PageLayout,\n type ScrollerLayout,\n type VirtualItem,\n} from "@embedpdf/plugin-scroll/react"\nimport {\n SearchLayer,\n SearchPluginPackage,\n useSearch,\n} from "@embedpdf/plugin-search/react"\nimport {\n CopyToClipboard,\n SelectionPluginPackage,\n useSelectionCapability,\n useSelectionPlugin,\n} from "@embedpdf/plugin-selection/react"\nimport {\n ThumbImg,\n ThumbnailPluginPackage,\n useThumbnailCapability,\n useThumbnailPlugin,\n type ThumbMeta,\n} 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 { useZoom, ZoomPluginPackage } from "@embedpdf/plugin-zoom/react"\nimport { flushSync } from "react-dom"\n\nimport { loadSharedPdfEngine } from "@/lib/pdf-thumbnail-utils"\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\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 { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport {\n DocumentViewerSidebarSkeleton,\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/extend/document-viewer-sidebar"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nexport type PDFViewerPageOverlayProps = {\n pageNumber: number\n pageWidth: number\n pageHeight: number\n scale: number\n rotation: number\n}\n\nexport type PDFViewerHandle = {\n scrollToPage: (pageNumber: number, options?: ScrollIntoViewOptions) => void\n scrollToPageArea: (\n pageNumber: number,\n area: { top: number; left?: number; width?: number; height?: number },\n options?: ScrollToOptions\n ) => void\n getViewportElement: () => HTMLDivElement | null\n}\n\nexport type PDFViewerScrollAreaViewportResolver = (\n container: HTMLDivElement\n) => HTMLDivElement | null\n\nexport type PDFViewerProps = {\n className?: string\n defaultZoom?: number\n fileName?: string\n resolveScrollAreaViewport?: PDFViewerScrollAreaViewportResolver\n showDownload?: boolean\n showToolbar?: boolean\n showRotateControls?: boolean\n showUpload?: boolean\n src?: string\n toolbarActions?: React.ReactNode\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onActivePageChange?: (pageNumber: number) => void\n onDocumentLoadSuccess?: (numPages: number) => void\n onPdfUpload?: (file: File) => void\n onPagePointerDown?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerMove?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerUp?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerCancel?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n}\n\nconst DEFAULT_ZOOM = 1\nconst ZOOM_OPTIONS = [0.1, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2]\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 THUMBNAIL_SIDEBAR_WIDTH_CLASS = "w-40"\nconst THUMBNAIL_SIDEBAR_CLOSED_CLASS = "-ml-40"\nconst PAGE_BASE_RENDER_MAX_SCALE = 1\nconst PAGE_BASE_RENDER_DPR = 1\nconst PDF_SEARCH_DEBOUNCE_MS = 300\nconst TEXT_SELECTION_BACKGROUND = "rgba(59, 130, 246, 0.14)"\nconst THUMBNAIL_FOCUS_RING_CLASS =\n "group-focus-visible/pdf-thumbnail-sidebar:ring-2 group-focus-visible/pdf-thumbnail-sidebar:ring-ring group-focus-visible/pdf-thumbnail-sidebar:ring-offset-1 group-focus-visible/pdf-thumbnail-sidebar:ring-offset-background"\nconst DEFAULT_SCROLL_AREA_VIEWPORT_SELECTOR =\n \'[data-slot="scroll-area-viewport"]\'\n\nfunction resolveDefaultScrollAreaViewport(container: HTMLDivElement) {\n return container.querySelector<HTMLDivElement>(\n DEFAULT_SCROLL_AREA_VIEWPORT_SELECTOR\n )\n}\n\nconst PDFViewerScrollAreaResolverContext =\n React.createContext<PDFViewerScrollAreaViewportResolver>(\n resolveDefaultScrollAreaViewport\n )\n\ntype PageRotationDeltas = Map<number, Rotation>\ntype ThumbnailSelectionMode = "replace" | "toggle" | "range"\n\nfunction getPageIndexRange(from: number, to: number): Set<number> {\n const start = Math.min(from, to)\n const end = Math.max(from, to)\n const range = new Set<number>()\n\n for (let pageIndex = start; pageIndex <= end; pageIndex += 1) {\n range.add(pageIndex)\n }\n\n return range\n}\n\nfunction arePageIndexSetsEqual(left: Set<number>, right: Set<number>) {\n if (left.size !== right.size) return false\n\n for (const value of left) {\n if (!right.has(value)) return false\n }\n\n return true\n}\n\nfunction normalizeRotation(rotation: number): Rotation {\n return (((rotation % 4) + 4) % 4) as Rotation\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\nfunction rotationToDegrees(rotation: Rotation) {\n return (rotation as number) * 90\n}\n\nfunction normalizeDegrees(rotation: number) {\n return ((rotation % 360) + 360) % 360\n}\n\nfunction ensurePdfExtension(fileName: string) {\n return fileName.toLowerCase().endsWith(".pdf") ? fileName : `${fileName}.pdf`\n}\n\nfunction getPdfDownloadFileName(fileName: string | undefined, src: string) {\n if (fileName?.trim()) return ensurePdfExtension(fileName.trim())\n\n const pathname = src.split(/[?#]/)[0] ?? ""\n const rawName = pathname.split("/").pop() || "document.pdf"\n\n try {\n return ensurePdfExtension(decodeURIComponent(rawName))\n } catch {\n return ensurePdfExtension(rawName)\n }\n}\n\nfunction getRotatedPdfDownloadFileName(fileName: string) {\n return fileName.replace(/\\.pdf$/i, "-rotated.pdf")\n}\n\nfunction downloadBlob(blob: Blob, fileName: string) {\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n\n anchor.href = url\n anchor.download = fileName\n anchor.rel = "noopener"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nasync function downloadPdfWithPageRotations({\n fileName,\n pageRotationDeltas,\n src,\n}: {\n fileName: string\n pageRotationDeltas: PageRotationDeltas\n src: string\n}) {\n const response = await fetch(src)\n\n if (!response.ok) {\n throw new Error(`Failed to download PDF (${response.status})`)\n }\n\n if (pageRotationDeltas.size === 0) {\n downloadBlob(await response.blob(), fileName)\n return\n }\n\n const [{ PDFDocument, degrees }, pdfBytes] = await Promise.all([\n import("pdf-lib"),\n response.arrayBuffer(),\n ])\n const pdfDocument = await PDFDocument.load(pdfBytes)\n\n pdfDocument.getPages().forEach((page, pageIndex) => {\n const rotationDelta = pageRotationDeltas.get(pageIndex)\n\n if (!rotationDelta) return\n\n page.setRotation(\n degrees(\n normalizeDegrees(\n page.getRotation().angle + rotationToDegrees(rotationDelta)\n )\n )\n )\n })\n\n const nextPdfBytes = await pdfDocument.save()\n const nextPdfBuffer = new ArrayBuffer(nextPdfBytes.byteLength)\n new Uint8Array(nextPdfBuffer).set(nextPdfBytes)\n\n downloadBlob(\n new Blob([nextPdfBuffer], { type: "application/pdf" }),\n getRotatedPdfDownloadFileName(fileName)\n )\n}\n\nfunction getThumbnailMetaForPage({\n page,\n pageIndex,\n rotation,\n width,\n imagePadding,\n labelHeight,\n top,\n}: {\n page: PdfDocumentObject["pages"][number]\n pageIndex: number\n rotation: Rotation\n width: number\n imagePadding: number\n labelHeight: number\n top: number\n}): ThumbMeta {\n const innerWidth = Math.max(1, width - imagePadding * 2)\n const pageWidth = rotation % 2 === 1 ? page.size.height : page.size.width\n const pageHeight = rotation % 2 === 1 ? page.size.width : page.size.height\n const imageHeight = Math.round(innerWidth * (pageHeight / pageWidth))\n const wrapperHeight = imagePadding + imageHeight + imagePadding + labelHeight\n\n return {\n pageIndex,\n width: innerWidth,\n height: imageHeight,\n wrapperHeight,\n top,\n labelHeight,\n padding: imagePadding,\n }\n}\n\nfunction buildThumbnailLayout({\n basePageRotations,\n pageRotationDeltas,\n pdfDocument,\n width,\n gap,\n imagePadding,\n labelHeight,\n paddingY,\n}: {\n basePageRotations: Rotation[]\n pageRotationDeltas: PageRotationDeltas\n pdfDocument: PdfDocumentObject | null\n width: number\n gap: number\n imagePadding: number\n labelHeight: number\n paddingY: number\n}) {\n if (!pdfDocument) return null\n\n let top = paddingY\n const items = pdfDocument.pages.map((page, pageIndex) => {\n const basePageRotation =\n basePageRotations[pageIndex] ?? normalizeRotation(page.rotation)\n const pageRotation = normalizeRotation(\n basePageRotation + (pageRotationDeltas.get(pageIndex) ?? 0)\n )\n const meta = getThumbnailMetaForPage({\n page,\n pageIndex,\n rotation: pageRotation,\n width,\n imagePadding,\n labelHeight,\n top,\n })\n\n top += meta.wrapperHeight + gap\n return meta\n })\n\n return {\n items,\n totalHeight: items.length ? top - gap + paddingY : paddingY * 2,\n }\n}\n\nfunction getVisibleThumbnailItems({\n buffer,\n clientHeight,\n items,\n scrollTop,\n}: {\n buffer: number\n clientHeight: number\n items: ThumbMeta[]\n scrollTop: number\n}) {\n if (items.length === 0) return []\n if (clientHeight <= 0)\n return items.slice(0, Math.min(items.length, buffer * 2))\n\n const viewportBottom = scrollTop + clientHeight\n let start = items.findIndex(\n (item) => item.top + item.wrapperHeight >= scrollTop\n )\n\n if (start === -1) start = items.length - 1\n\n let end = start\n while (end < items.length && items[end].top <= viewportBottom) {\n end += 1\n }\n\n return items.slice(\n Math.max(0, start - buffer),\n Math.min(items.length, end + buffer)\n )\n}\n\nfunction PDFViewerLoadingSkeleton({\n sidebarOpen,\n sidebarInline,\n}: {\n sidebarOpen: boolean\n sidebarInline: boolean\n}) {\n return (\n <div className="absolute inset-0 z-20 flex bg-muted/30">\n {sidebarOpen ? (\n <DocumentViewerSidebarSkeleton\n className={THUMBNAIL_SIDEBAR_WIDTH_CLASS}\n inline={sidebarInline}\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 )\n}\n\n// Rendered while the engine or document is not ready: same frame and controls\n// as the full viewer, with document-dependent controls disabled.\nfunction PDFViewerFallbackShell({\n className,\n defaultZoom,\n errorMessage = "Unable to load the PDF preview.",\n showDownload,\n showRotateControls,\n showToolbar,\n showUpload,\n sidebarOpen,\n state,\n toolbarActions,\n onUploadFile,\n}: {\n className?: string\n defaultZoom: number\n errorMessage?: string\n showDownload: boolean\n showRotateControls: boolean\n showToolbar: boolean\n showUpload: boolean\n sidebarOpen: boolean\n state: "loading" | "error" | "empty"\n toolbarActions?: React.ReactNode\n onUploadFile?: (file: File) => void\n}) {\n return (\n <div\n data-slot="pdf-viewer"\n className={cn(\n "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n {showToolbar ? (\n <PDFViewerToolbar\n activePage={1}\n controlsDisabled\n currentZoomLevel={defaultZoom}\n numPages={0}\n searchControl={\n <ToolbarTooltip label="Search text">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search text"\n disabled\n >\n <IconPlaceholder\n lucide="Search"\n tabler="IconSearch"\n hugeicons="Search01Icon"\n phosphor="MagnifyingGlassIcon"\n remixicon="RiSearchLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n }\n sidebarOpen={sidebarOpen}\n showDownload={showDownload}\n showRotateControls={showRotateControls}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n onPageChange={() => undefined}\n onRotate={() => undefined}\n onToggleSidebar={() => undefined}\n onUploadFile={onUploadFile}\n onZoomChange={() => undefined}\n />\n ) : null}\n <div className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30">\n {state === "loading" ? (\n <PDFViewerLoadingSkeleton sidebarInline sidebarOpen={sidebarOpen} />\n ) : null}\n {state === "error" ? (\n <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-sm text-muted-foreground">\n {errorMessage}\n </div>\n ) : null}\n {state === "empty" ? (\n <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-center text-sm text-muted-foreground">\n <div className="max-w-sm space-y-3">\n <div className="font-medium text-foreground">\n Upload a PDF to preview\n </div>\n <div>\n Pass a PDF URL with the <code>src</code> prop or use the upload\n control.\n </div>\n </div>\n </div>\n ) : null}\n </div>\n </div>\n )\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction PDFViewerFileActionsMenu({\n downloadDisabled,\n isPreparingDownload = false,\n onDownload,\n onUploadFile,\n showDownload = false,\n showUpload = false,\n}: {\n downloadDisabled?: boolean\n isPreparingDownload?: boolean\n onDownload?: () => void\n onUploadFile?: (file: File) => void\n showDownload?: boolean\n showUpload?: boolean\n}) {\n const inputRef = React.useRef<HTMLInputElement>(null)\n\n if (!showDownload && !showUpload) return null\n\n return (\n <>\n {showUpload && onUploadFile ? (\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 nextFile = event.target.files?.[0]\n\n if (nextFile) {\n onUploadFile(nextFile)\n event.currentTarget.value = ""\n }\n }}\n />\n ) : null}\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Open PDF actions"\n >\n <IconPlaceholder\n lucide="Ellipsis"\n tabler="IconDots"\n hugeicons="MoreHorizontalIcon"\n phosphor="DotsThreeIcon"\n remixicon="RiMoreLine"\n className="size-4"\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="w-40">\n {showDownload ? (\n <DropdownMenuItem disabled={downloadDisabled} onClick={onDownload}>\n {isPreparingDownload ? (\n <Spinner className="size-4" />\n ) : (\n <IconPlaceholder\n lucide="Download"\n tabler="IconDownload"\n hugeicons="Download01Icon"\n phosphor="DownloadSimpleIcon"\n remixicon="RiDownload2Line"\n className="size-4"\n />\n )}\n Download\n </DropdownMenuItem>\n ) : null}\n {showUpload && onUploadFile ? (\n <DropdownMenuItem onClick={() => inputRef.current?.click()}>\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload\n </DropdownMenuItem>\n ) : null}\n </DropdownMenuContent>\n </DropdownMenu>\n </>\n )\n}\n\nfunction PDFViewerPageNumberControl({\n activePage,\n controlsDisabled,\n numPages,\n onPageChange,\n}: {\n activePage: number\n controlsDisabled: boolean\n numPages: number\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={controlsDisabled || !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 PDFViewerSearchControl({\n documentId,\n controlsDisabled,\n}: {\n documentId: string\n controlsDisabled: boolean\n}) {\n const { state, provides } = useSearch(documentId)\n const { provides: scroll } = useScroll(documentId)\n const [searchDraft, setSearchDraft] = React.useState("")\n const [searchQuery, setSearchQuery] = React.useState("")\n const [isSearching, setIsSearching] = React.useState(false)\n const providesRef = React.useRef(provides)\n const scrollRef = React.useRef(scroll)\n const searchRequestIdRef = React.useRef(0)\n const hasActiveQuery = Boolean(searchQuery.trim())\n const resultLabel = isSearching\n ? "Searching"\n : !hasActiveQuery\n ? "No search"\n : state.total\n ? `${state.activeResultIndex + 1} / ${state.total}`\n : "No results"\n\n const scrollToResult = React.useCallback(\n (index: number) => {\n const result = state.results[index]\n\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: {\n x: firstRect.origin.x,\n y: firstRect.origin.y,\n },\n alignY: 30,\n }\n : {}),\n behavior: "auto",\n })\n },\n [scroll, state.results]\n )\n\n React.useEffect(() => {\n providesRef.current = provides\n scrollRef.current = scroll\n }, [provides, scroll])\n\n const runSearch = React.useCallback((rawQuery: string) => {\n const query = rawQuery.trim()\n const requestId = searchRequestIdRef.current + 1\n searchRequestIdRef.current = requestId\n setSearchQuery(query)\n\n const searchProvider = providesRef.current\n const scrollProvider = scrollRef.current\n\n if (!searchProvider) {\n setIsSearching(false)\n return\n }\n\n if (!query) {\n searchProvider.stopSearch()\n setIsSearching(false)\n return\n }\n\n setIsSearching(true)\n searchProvider.startSearch()\n searchProvider.searchAllPages(query).wait(\n (result) => {\n if (searchRequestIdRef.current !== requestId) return\n\n const firstResult = result.results[0]\n\n if (firstResult && scrollProvider) {\n searchProvider.goToResult(0)\n const firstRect = firstResult.rects[0]\n\n scrollProvider.scrollToPage({\n pageNumber: firstResult.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 setIsSearching(false)\n },\n () => {\n if (searchRequestIdRef.current !== requestId) return\n setIsSearching(false)\n }\n )\n }, [])\n\n React.useEffect(() => {\n if (!searchDraft.trim()) return\n\n const timeoutId = window.setTimeout(() => {\n runSearch(searchDraft)\n }, PDF_SEARCH_DEBOUNCE_MS)\n\n return () => window.clearTimeout(timeoutId)\n }, [runSearch, searchDraft])\n\n const handleSearchDraftChange = React.useCallback(\n (event: React.ChangeEvent<HTMLInputElement>) => {\n const nextDraft = event.target.value\n\n setSearchDraft(nextDraft)\n\n if (nextDraft.trim()) {\n setIsSearching(true)\n return\n }\n\n searchRequestIdRef.current += 1\n setSearchQuery("")\n setIsSearching(false)\n provides?.stopSearch()\n },\n [provides]\n )\n\n const clearSearch = React.useCallback(() => {\n searchRequestIdRef.current += 1\n setSearchDraft("")\n setSearchQuery("")\n setIsSearching(false)\n provides?.stopSearch()\n }, [provides])\n\n const navigate = React.useCallback(\n (direction: 1 | -1) => {\n if (!provides || state.total === 0) return\n\n const index =\n direction === 1 ? provides.nextResult() : provides.previousResult()\n\n scrollToResult(index)\n },\n [provides, scrollToResult, state.total]\n )\n\n return (\n <Popover>\n <ToolbarTooltip label="Search text">\n <PopoverTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search text"\n disabled={controlsDisabled}\n >\n <IconPlaceholder\n lucide="Search"\n tabler="IconSearch"\n hugeicons="Search01Icon"\n phosphor="MagnifyingGlassIcon"\n remixicon="RiSearchLine"\n className="size-4"\n />\n </Button>\n </PopoverTrigger>\n </ToolbarTooltip>\n <PopoverContent align="end" className="w-72">\n <div className="space-y-3">\n <Input\n placeholder="Search text"\n value={searchDraft}\n onChange={handleSearchDraftChange}\n onKeyDown={(event) => {\n if (event.key !== "Enter") return\n\n event.preventDefault()\n if (event.shiftKey && state.total) {\n navigate(-1)\n } else if (state.total) {\n navigate(1)\n } else if (searchDraft.trim()) {\n runSearch(searchDraft)\n }\n }}\n />\n <div className="flex items-center justify-between gap-2">\n <div className="min-w-0 text-xs text-muted-foreground">\n <div className="truncate">\n {state.total ? (\n <>\n <span className="text-primary">\n {state.activeResultIndex + 1}\n </span>\n {` / ${state.total}`}\n </>\n ) : (\n resultLabel\n )}\n </div>\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 <IconPlaceholder\n lucide="ChevronLeft"\n tabler="IconChevronLeft"\n hugeicons="ArrowLeft01Icon"\n phosphor="CaretLeftIcon"\n remixicon="RiArrowLeftSLine"\n className="size-4"\n />\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 <IconPlaceholder\n lucide="ArrowRight"\n tabler="IconArrowRight"\n hugeicons="ArrowRight01Icon"\n phosphor="ArrowRightIcon"\n remixicon="RiArrowRightLine"\n className="size-4"\n />\n </Button>\n </div>\n </div>\n <div className="flex justify-end">\n <Button\n type="button"\n variant="outline"\n size="sm"\n onClick={clearSearch}\n >\n Clear\n </Button>\n </div>\n </div>\n </PopoverContent>\n </Popover>\n )\n}\n\nfunction PDFViewerToolbar({\n activePage,\n controlsDisabled,\n currentZoomLevel,\n downloadDisabled = controlsDisabled,\n isPreparingDownload = false,\n numPages,\n searchControl,\n sidebarOpen,\n showDownload,\n showRotateControls,\n showUpload,\n toolbarActions,\n onDownload,\n onPageChange,\n onRotate,\n onToggleSidebar,\n onUploadFile,\n onZoomChange,\n}: {\n activePage: number\n controlsDisabled: boolean\n currentZoomLevel: number\n downloadDisabled?: boolean\n isPreparingDownload?: boolean\n numPages: number\n searchControl: React.ReactNode\n sidebarOpen: boolean\n showDownload: boolean\n showRotateControls: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n onDownload?: () => void\n onPageChange: (pageNumber: number) => void\n onRotate: (direction: 1 | -1) => void\n onToggleSidebar: () => void\n onUploadFile?: (file: File) => void\n onZoomChange: (zoomLevel: number) => void\n}) {\n return (\n <div className="flex min-h-12 flex-wrap items-center justify-between gap-2 border-b bg-background px-3 py-2">\n <div className="flex min-w-0 flex-wrap items-center gap-2">\n <TooltipProvider>\n <ToolbarTooltip label="Pages sidebar">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Pages sidebar"\n aria-pressed={sidebarOpen}\n data-active={sidebarOpen ? "" : undefined}\n className={cn(\n sidebarOpen &&\n "bg-accent text-accent-foreground ring-1 ring-ring/40 ring-inset"\n )}\n disabled={controlsDisabled}\n onClick={onToggleSidebar}\n >\n <IconPlaceholder\n lucide="PanelLeft"\n tabler="IconLayoutSidebar"\n hugeicons="SidebarLeftIcon"\n phosphor="SidebarIcon"\n remixicon="RiLayoutLeftLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </TooltipProvider>\n <PDFViewerPageNumberControl\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n numPages={numPages}\n onPageChange={onPageChange}\n />\n </div>\n <TooltipProvider>\n <div className="flex min-w-0 flex-wrap items-center justify-end gap-1">\n {showRotateControls ? (\n <>\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Rotate counterclockwise">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Rotate counterclockwise"\n disabled={controlsDisabled}\n onClick={() => onRotate(-1)}\n >\n <IconPlaceholder\n lucide="RotateCw"\n tabler="IconRotateClockwise"\n hugeicons="RotateClockwiseIcon"\n phosphor="ArrowClockwiseIcon"\n remixicon="RiClockwiseLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Rotate clockwise">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Rotate clockwise"\n disabled={controlsDisabled}\n onClick={() => onRotate(1)}\n >\n <IconPlaceholder\n lucide="RotateCw"\n tabler="IconRotateClockwise"\n hugeicons="RotateClockwiseIcon"\n phosphor="ArrowClockwiseIcon"\n remixicon="RiClockwiseLine"\n className="size-4 -scale-x-100"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom out"\n disabled={\n controlsDisabled || currentZoomLevel <= ZOOM_OPTIONS[0]\n }\n onClick={() => {\n const nextZoom = [...ZOOM_OPTIONS]\n .reverse()\n .find((option) => option < currentZoomLevel)\n\n onZoomChange(nextZoom ?? ZOOM_OPTIONS[0])\n }}\n >\n <IconPlaceholder\n lucide="CircleMinus"\n tabler="IconCircleMinus"\n hugeicons="MinusSignCircleIcon"\n phosphor="MinusCircleIcon"\n remixicon="RiIndeterminateCircleLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={String(currentZoomLevel)}\n onValueChange={(value) => onZoomChange(Number(value))}\n disabled={controlsDisabled}\n modal={false}\n >\n <SelectTrigger size="sm" className="w-[84px] min-w-[84px]">\n <SelectValue placeholder="Zoom">\n {Math.round(currentZoomLevel * 100)}%\n </SelectValue>\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((option) => (\n <SelectItem key={option} value={String(option)}>\n {Math.round(option * 100)}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom in"\n disabled={\n controlsDisabled ||\n currentZoomLevel >= ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n }\n onClick={() => {\n const nextZoom = ZOOM_OPTIONS.find(\n (option) => option > currentZoomLevel\n )\n\n onZoomChange(\n nextZoom ?? ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n )\n }}\n >\n <IconPlaceholder\n lucide="CirclePlusIcon"\n tabler="IconCirclePlusFilled"\n hugeicons="PlusSignCircleIcon"\n phosphor="PlusCircleIcon"\n remixicon="RiAddCircleFill"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n {searchControl}\n {toolbarActions ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {toolbarActions}\n </>\n ) : null}\n {showDownload || showUpload ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <PDFViewerFileActionsMenu\n downloadDisabled={downloadDisabled}\n isPreparingDownload={isPreparingDownload}\n onDownload={onDownload}\n onUploadFile={onUploadFile}\n showDownload={showDownload}\n showUpload={showUpload}\n />\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nfunction setPdfViewerRef<T>(ref: React.Ref<T> | undefined, value: T | null) {\n if (!ref) return\n\n if (typeof ref === "function") {\n ref(value)\n } else {\n ref.current = value\n }\n}\n\nfunction PDFViewerScrollArea({\n children,\n className,\n viewportClassName,\n viewportProps,\n viewportRef,\n}: {\n children: React.ReactNode\n className?: string\n viewportClassName?: string\n viewportProps?: React.HTMLAttributes<HTMLDivElement>\n viewportRef?: React.Ref<HTMLDivElement>\n}) {\n const resolveScrollAreaViewport = React.useContext(\n PDFViewerScrollAreaResolverContext\n )\n const containerRef = React.useRef<HTMLDivElement | null>(null)\n const { className: viewportPropsClassName, ...resolvedViewportProps } =\n viewportProps ?? {}\n\n const setViewportRef = React.useCallback(\n (viewport: HTMLDivElement | null) => {\n setPdfViewerRef(viewportRef, viewport)\n },\n [viewportRef]\n )\n\n React.useLayoutEffect(() => {\n const container = containerRef.current\n if (!container) return\n\n const viewport = resolveScrollAreaViewport(container)\n\n if (!viewport) {\n console.error(\n `PDFViewer could not resolve the scroll viewport. Add ${DEFAULT_SCROLL_AREA_VIEWPORT_SELECTOR} to your ScrollArea viewport or pass resolveScrollAreaViewport.`\n )\n return\n }\n\n setViewportRef(viewport)\n\n return () => setViewportRef(null)\n }, [resolveScrollAreaViewport, setViewportRef])\n\n return (\n <div\n ref={containerRef}\n data-slot="pdf-viewer-scroll-area"\n className={cn("size-full min-h-0", className)}\n >\n <ScrollArea className="size-full min-h-0">\n <div\n {...resolvedViewportProps}\n data-slot="pdf-viewer-scroll-content"\n className={cn(\n "min-h-full",\n viewportPropsClassName,\n viewportClassName\n )}\n >\n {children}\n </div>\n </ScrollArea>\n </div>\n )\n}\n\nfunction PDFViewerThumbnails({\n basePageRotations,\n documentId,\n activePage,\n pageCount,\n pageRotationDeltas,\n pdfDocument,\n selectedPageIndexes,\n onSelectPage,\n}: {\n basePageRotations: Rotation[]\n documentId: string\n activePage: number\n pageCount: number\n pageRotationDeltas: PageRotationDeltas\n pdfDocument: PdfDocumentObject | null\n selectedPageIndexes: Set<number>\n onSelectPage: (pageNumber: number, mode: ThumbnailSelectionMode) => void\n}) {\n const thumbnailListboxId = React.useId()\n const activeDescendantId =\n activePage > 0 ? `${thumbnailListboxId}-page-${activePage}` : undefined\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (pageCount < 1) return\n\n const currentPage = activePage > 0 ? activePage : 1\n let nextPage: number | null = null\n\n if (event.key === "ArrowDown") {\n nextPage = Math.min(pageCount, currentPage + 1)\n } else if (event.key === "ArrowUp") {\n nextPage = Math.max(1, currentPage - 1)\n } else if (event.key === "Home") {\n nextPage = 1\n } else if (event.key === "End") {\n nextPage = pageCount\n } else if (event.key === " ") {\n event.preventDefault()\n onSelectPage(currentPage, "toggle")\n return\n }\n\n if (nextPage === null) return\n\n event.preventDefault()\n onSelectPage(nextPage, event.shiftKey ? "range" : "replace")\n },\n [activePage, onSelectPage, pageCount]\n )\n\n return (\n <PDFViewerThumbnailScrollArea\n activeDescendantId={activeDescendantId}\n basePageRotations={basePageRotations}\n documentId={documentId}\n onKeyDown={handleKeyDown}\n pageRotationDeltas={pageRotationDeltas}\n pdfDocument={pdfDocument}\n >\n {(meta: ThumbMeta) => {\n const pageNumber = meta.pageIndex + 1\n const isActive = pageNumber === activePage\n const isSelected = selectedPageIndexes.has(meta.pageIndex)\n const imagePadding = meta.padding ?? 0\n const pageRotationDelta = pageRotationDeltas.get(meta.pageIndex) ?? 0\n const thumbnailImageStyle: React.CSSProperties =\n pageRotationDelta % 2 === 1\n ? {\n height: meta.width,\n transform: `rotate(${rotationToDegrees(pageRotationDelta)}deg)`,\n width: meta.height,\n }\n : {\n height: meta.height,\n transform:\n pageRotationDelta === 0\n ? undefined\n : `rotate(${rotationToDegrees(pageRotationDelta)}deg)`,\n width: meta.width,\n }\n\n return (\n <div\n key={meta.pageIndex}\n data-pdf-viewer-thumbnail={pageNumber}\n className={cn(\n "absolute right-0 left-0 flex justify-center",\n isActive && "z-10"\n )}\n style={{ top: meta.top, height: meta.wrapperHeight }}\n >\n <div\n id={`${thumbnailListboxId}-page-${pageNumber}`}\n role="option"\n data-pdf-viewer-thumbnail-option={pageNumber}\n aria-current={isActive ? "page" : undefined}\n aria-label={`Page ${pageNumber}`}\n aria-posinset={pageNumber}\n aria-selected={isSelected}\n aria-setsize={pageCount}\n data-selected={isSelected ? "" : undefined}\n className={cn(\n "flex h-full w-full cursor-default flex-col items-center justify-between rounded-md px-2 py-0 text-xs transition-shadow outline-none select-none hover:bg-sidebar-accent",\n isActive || isSelected\n ? "bg-sidebar-accent text-foreground"\n : "text-muted-foreground",\n isActive && THUMBNAIL_FOCUS_RING_CLASS\n )}\n onClick={(event) => {\n const mode = event.shiftKey\n ? "range"\n : event.metaKey || event.ctrlKey\n ? "toggle"\n : "replace"\n\n onSelectPage(pageNumber, mode)\n }}\n >\n <span\n className="mt-0 flex items-center justify-center overflow-hidden rounded-md bg-transparent"\n style={{\n width: meta.width + imagePadding * 2,\n height: meta.height + imagePadding * 2,\n padding: imagePadding,\n }}\n >\n <ThumbImg\n documentId={documentId}\n meta={meta}\n className="block rounded-sm object-contain"\n style={thumbnailImageStyle}\n />\n </span>\n <span\n className="flex items-center justify-center tabular-nums"\n style={{ height: meta.labelHeight }}\n >\n <span className="flex min-w-5 items-center justify-center px-1.5 text-center leading-5">\n {pageNumber}\n </span>\n </span>\n </div>\n </div>\n )\n }}\n </PDFViewerThumbnailScrollArea>\n )\n}\n\nfunction PDFViewerThumbnailScrollArea({\n activeDescendantId,\n basePageRotations,\n children,\n documentId,\n onKeyDown,\n pageRotationDeltas,\n pdfDocument,\n}: {\n activeDescendantId?: string\n basePageRotations: Rotation[]\n children: (meta: ThumbMeta) => React.ReactNode\n documentId: string\n onKeyDown: React.KeyboardEventHandler<HTMLDivElement>\n pageRotationDeltas: PageRotationDeltas\n pdfDocument: PdfDocumentObject | null\n}) {\n const { plugin: thumbnailPlugin } = useThumbnailPlugin()\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewportMetrics, setViewportMetrics] = React.useState({\n clientHeight: 0,\n scrollTop: 0,\n })\n const thumbnailScope = React.useMemo(\n () => thumbnailPlugin?.provides().forDocument(documentId) ?? null,\n [documentId, thumbnailPlugin]\n )\n\n const windowState = React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) => {\n if (!thumbnailScope) return () => undefined\n\n return thumbnailScope.onWindow(() => onStoreChange())\n },\n [thumbnailScope]\n ),\n React.useCallback(\n () => thumbnailScope?.getWindow() ?? null,\n [thumbnailScope]\n ),\n () => null\n )\n const hasWindowState = Boolean(windowState)\n const paddingY = thumbnailPlugin?.cfg.paddingY ?? 0\n const thumbnailLayout = React.useMemo(\n () =>\n buildThumbnailLayout({\n basePageRotations,\n pageRotationDeltas,\n pdfDocument,\n width: thumbnailPlugin?.cfg.width ?? THUMBNAIL_WIDTH,\n gap: thumbnailPlugin?.cfg.gap ?? THUMBNAIL_GAP,\n imagePadding: thumbnailPlugin?.cfg.imagePadding ?? 0,\n labelHeight: thumbnailPlugin?.cfg.labelHeight ?? THUMBNAIL_LABEL_HEIGHT,\n paddingY,\n }),\n [\n basePageRotations,\n pageRotationDeltas,\n pdfDocument,\n paddingY,\n thumbnailPlugin,\n ]\n )\n const effectiveWindowState = React.useMemo(() => {\n if (!thumbnailLayout) return windowState\n\n const items = getVisibleThumbnailItems({\n buffer: thumbnailPlugin?.cfg.buffer ?? 3,\n clientHeight: viewportMetrics.clientHeight,\n items: thumbnailLayout.items,\n scrollTop: viewportMetrics.scrollTop,\n })\n\n return {\n start: items[0]?.pageIndex ?? -1,\n end: items.at(-1)?.pageIndex ?? -1,\n items,\n totalHeight: thumbnailLayout.totalHeight,\n }\n }, [thumbnailLayout, thumbnailPlugin, viewportMetrics, windowState])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope) return\n\n const updateWindow = () => {\n setViewportMetrics({\n clientHeight: viewport.clientHeight,\n scrollTop: viewport.scrollTop,\n })\n thumbnailScope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n }\n\n viewport.addEventListener("scroll", updateWindow)\n const frame = window.requestAnimationFrame(updateWindow)\n\n return () => {\n window.cancelAnimationFrame(frame)\n viewport.removeEventListener("scroll", updateWindow)\n }\n }, [thumbnailScope])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope) return\n\n const resizeObserver = new ResizeObserver(() => {\n setViewportMetrics({\n clientHeight: viewport.clientHeight,\n scrollTop: viewport.scrollTop,\n })\n thumbnailScope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n })\n\n resizeObserver.observe(viewport)\n\n return () => resizeObserver.disconnect()\n }, [thumbnailScope])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope) return\n\n thumbnailScope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n }, [thumbnailLayout, thumbnailScope, windowState])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope || !hasWindowState) return\n\n return thumbnailScope.onScrollTo(({ top, behavior }) => {\n viewport.scrollTo({ top, behavior })\n })\n }, [hasWindowState, thumbnailScope])\n\n return (\n <PDFViewerScrollArea\n className="h-full w-full"\n viewportClassName="group/pdf-thumbnail-sidebar px-4 focus-visible:ring-0 focus-visible:ring-offset-0"\n viewportProps={{\n "aria-activedescendant": activeDescendantId,\n "aria-label": "PDF pages",\n "aria-multiselectable": true,\n onKeyDown,\n onMouseDown: (event) => {\n event.currentTarget.focus({ preventScroll: true })\n },\n role: "listbox",\n style: {\n paddingBottom: paddingY,\n paddingTop: paddingY,\n },\n tabIndex: 0,\n }}\n viewportRef={viewportRef}\n >\n <div\n className="relative"\n style={{ height: effectiveWindowState?.totalHeight ?? 0 }}\n >\n {effectiveWindowState?.items.map((meta) => children(meta))}\n </div>\n </PDFViewerScrollArea>\n )\n}\n\nfunction PDFViewerScrollAreaViewport({\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 <PDFViewerScrollArea\n className={className}\n viewportClassName="relative select-none selection:bg-transparent selection:text-inherit"\n viewportProps={{\n style: {\n padding: viewportGap,\n },\n }}\n viewportRef={viewportRef}\n >\n {isGated ? null : children}\n </PDFViewerScrollArea>\n </ViewportElementContext.Provider>\n )\n}\n\n// Captures the scrollable viewport element so the imperative handle can expose\n// it.\nfunction PDFViewerViewportBridge({\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\nfunction PDFViewerTextSelectionLayer({\n documentId,\n pageIndex,\n scale,\n}: {\n documentId: string\n pageIndex: number\n scale: number\n}) {\n const { plugin: selectionPlugin } = useSelectionPlugin()\n const [rects, setRects] = React.useState<Rect[]>([])\n\n React.useEffect(() => {\n if (!selectionPlugin) return\n\n return selectionPlugin.registerSelectionOnPage({\n documentId,\n pageIndex,\n onRectsChange: ({ rects: nextRects }) => {\n setRects(nextRects)\n },\n })\n }, [documentId, pageIndex, selectionPlugin])\n\n if (!rects.length) return null\n\n return (\n <>\n {rects.map((rect, index) => (\n <div\n key={`${index}-${rect.origin.x}-${rect.origin.y}`}\n className="pointer-events-none absolute"\n style={{\n background: TEXT_SELECTION_BACKGROUND,\n height: rect.size.height * scale,\n left: rect.origin.x * scale,\n top: rect.origin.y * scale,\n width: rect.size.width * scale,\n }}\n />\n ))}\n </>\n )\n}\n\nfunction PDFViewerSelectionReleaseGuard({\n documentId,\n}: {\n documentId: string\n}) {\n const { plugin: selectionPlugin } = useSelectionPlugin()\n const { provides: selection } = useSelectionCapability()\n const lastSelectionModeIdRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n if (!selection) return\n\n return selection.forDocument(documentId).onBeginSelection(({ modeId }) => {\n lastSelectionModeIdRef.current = modeId\n })\n }, [documentId, selection])\n\n React.useEffect(() => {\n if (!selection) return\n\n let cleanupFrame = 0\n const finalizeIfStillSelecting = () => {\n window.cancelAnimationFrame(cleanupFrame)\n cleanupFrame = window.requestAnimationFrame(() => {\n const selectionState = selection.getState(documentId)\n\n if (!selectionState.selecting) return\n\n if (selectionState.selection && selectionPlugin) {\n const pluginWithEndSelection = selectionPlugin as unknown as {\n endSelection?: (documentId: string, modeId: string) => void\n }\n\n pluginWithEndSelection.endSelection?.(\n documentId,\n lastSelectionModeIdRef.current ?? "pointerMode"\n )\n return\n }\n\n if (!selectionState.selection) {\n selection.clear(documentId)\n }\n })\n }\n\n window.addEventListener("pointerup", finalizeIfStillSelecting)\n window.addEventListener("pointercancel", finalizeIfStillSelecting)\n window.addEventListener("blur", finalizeIfStillSelecting)\n\n return () => {\n window.cancelAnimationFrame(cleanupFrame)\n window.removeEventListener("pointerup", finalizeIfStillSelecting)\n window.removeEventListener("pointercancel", finalizeIfStillSelecting)\n window.removeEventListener("blur", finalizeIfStillSelecting)\n }\n }, [documentId, selection, selectionPlugin])\n\n return null\n}\n\nfunction isEditableCopyTarget(target: EventTarget | null) {\n if (!(target instanceof HTMLElement)) return false\n\n if (target.isContentEditable) return true\n\n return Boolean(target.closest("input, textarea, [contenteditable=\'true\']"))\n}\n\nfunction PDFViewerSelectionCopyShortcut({\n documentId,\n}: {\n documentId: string\n}) {\n const { provides: selection } = useSelectionCapability()\n\n React.useEffect(() => {\n if (!selection) return\n\n const copySelectedPdfText = (event: Event) => {\n if (isEditableCopyTarget(event.target)) return\n if (!selection.getState(documentId).selection) return\n\n event.preventDefault()\n selection.copyToClipboard(documentId)\n }\n\n const handleKeyDown = (event: KeyboardEvent) => {\n if (event.key.toLowerCase() !== "c") return\n if (!event.metaKey && !event.ctrlKey) return\n\n copySelectedPdfText(event)\n }\n\n document.addEventListener("copy", copySelectedPdfText)\n document.addEventListener("keydown", handleKeyDown)\n\n return () => {\n document.removeEventListener("copy", copySelectedPdfText)\n document.removeEventListener("keydown", handleKeyDown)\n }\n }, [documentId, selection])\n\n return null\n}\n\nfunction isQuarterTurn(rotation: Rotation) {\n return rotation % 2 === 1\n}\n\nfunction getRotatedDimensions({\n height,\n rotation,\n width,\n}: {\n height: number\n rotation: Rotation\n width: number\n}) {\n return isQuarterTurn(rotation)\n ? { height: width, width: height }\n : { height, width }\n}\n\nfunction getRotatedPageDimensions(page: PageLayout, rotation: Rotation) {\n return getRotatedDimensions({\n height: page.height,\n rotation,\n width: page.width,\n })\n}\n\nfunction applyPageRotationDeltasToScrollerLayout({\n basePageRotations,\n layout,\n pageRotationDeltas,\n}: {\n basePageRotations: Rotation[]\n layout: ScrollerLayout\n pageRotationDeltas: PageRotationDeltas\n}): ScrollerLayout {\n if (pageRotationDeltas.size === 0) return layout\n\n let maxWidth = 0\n let maxHeight = 0\n let offset = 0\n const pageGap = layout.pageGap\n let startSpacingAdjustment = 0\n const items: VirtualItem[] = layout.items.map((item, itemIndex) => {\n let pageOffset = 0\n let itemWidth = 0\n let itemHeight = 0\n const pageLayouts = item.pageLayouts.map((page) => {\n const basePageRotation =\n basePageRotations[page.pageIndex] ?? normalizeRotation(0)\n const pageRotation = normalizeRotation(\n basePageRotation + (pageRotationDeltas.get(page.pageIndex) ?? 0)\n )\n const rotatedSize = getRotatedPageDimensions(page, pageRotation)\n const oldScrollAxisSize =\n layout.strategy === ScrollStrategy.Horizontal\n ? page.rotatedWidth\n : page.rotatedHeight\n const newScrollAxisSize =\n layout.strategy === ScrollStrategy.Horizontal\n ? rotatedSize.width\n : rotatedSize.height\n\n if (\n layout.startSpacing === 0 &&\n itemIndex === 0 &&\n pageOffset === 0 &&\n newScrollAxisSize < oldScrollAxisSize\n ) {\n startSpacingAdjustment = Math.max(\n startSpacingAdjustment,\n (oldScrollAxisSize - newScrollAxisSize) / 2\n )\n }\n\n const nextPageLayout = {\n ...page,\n rotatedHeight: rotatedSize.height,\n rotatedWidth: rotatedSize.width,\n x: layout.strategy === ScrollStrategy.Horizontal ? 0 : pageOffset,\n y: layout.strategy === ScrollStrategy.Horizontal ? pageOffset : 0,\n }\n\n pageOffset +=\n (layout.strategy === ScrollStrategy.Horizontal\n ? rotatedSize.height\n : rotatedSize.width) + pageGap\n itemWidth =\n layout.strategy === ScrollStrategy.Horizontal\n ? Math.max(itemWidth, rotatedSize.width)\n : itemWidth + rotatedSize.width\n itemHeight =\n layout.strategy === ScrollStrategy.Horizontal\n ? itemHeight + rotatedSize.height\n : Math.max(itemHeight, rotatedSize.height)\n\n return nextPageLayout\n })\n\n if (pageLayouts.length > 1) {\n if (layout.strategy === ScrollStrategy.Horizontal) {\n itemHeight -= pageGap\n } else {\n itemWidth -= pageGap\n }\n }\n\n const nextItem = {\n ...item,\n height: itemHeight,\n offset,\n pageLayouts,\n width: itemWidth,\n x: layout.strategy === ScrollStrategy.Horizontal ? offset : item.x,\n y: layout.strategy === ScrollStrategy.Horizontal ? item.y : offset,\n }\n\n if (layout.strategy === ScrollStrategy.Horizontal) {\n offset += itemWidth + pageGap\n maxHeight = Math.max(maxHeight, itemHeight)\n } else {\n offset += itemHeight + pageGap\n maxWidth = Math.max(maxWidth, itemWidth)\n }\n\n return nextItem\n })\n\n if (items.length > 0) {\n offset -= pageGap\n }\n\n return {\n ...layout,\n endSpacing: layout.endSpacing,\n items,\n startSpacing: layout.startSpacing + startSpacingAdjustment,\n totalHeight:\n layout.strategy === ScrollStrategy.Horizontal\n ? maxHeight\n : layout.startSpacing +\n startSpacingAdjustment +\n offset +\n layout.endSpacing,\n totalWidth:\n layout.strategy === ScrollStrategy.Horizontal\n ? layout.startSpacing +\n startSpacingAdjustment +\n offset +\n layout.endSpacing\n : maxWidth,\n }\n}\n\nfunction PDFViewerScroller({\n documentId,\n pageRotationDeltas,\n basePageRotations,\n renderPage,\n}: {\n documentId: string\n pageRotationDeltas: PageRotationDeltas\n basePageRotations: Rotation[]\n renderPage: (props: PageLayout) => React.ReactNode\n}) {\n const { plugin: scrollPlugin } = useScrollPlugin()\n const [layoutData, setLayoutData] = React.useState<{\n docId: string | null\n layout: ScrollerLayout | null\n }>({ docId: null, layout: null })\n\n React.useEffect(() => {\n if (!scrollPlugin || !documentId) return\n let frame = 0\n\n const setCurrentLayout = () => {\n try {\n setLayoutData({\n docId: documentId,\n layout: scrollPlugin.getScrollerLayout(documentId),\n })\n } catch {\n setLayoutData({ docId: documentId, layout: null })\n }\n }\n\n const unsubscribe = scrollPlugin.onScrollerData(documentId, (layout) => {\n setLayoutData({ docId: documentId, layout })\n })\n\n frame = window.requestAnimationFrame(setCurrentLayout)\n\n return () => {\n window.cancelAnimationFrame(frame)\n unsubscribe()\n setLayoutData({ docId: null, layout: null })\n scrollPlugin.clearLayoutReady(documentId)\n }\n }, [documentId, scrollPlugin])\n\n const scrollerLayout = React.useMemo(() => {\n if (layoutData.docId !== documentId || !layoutData.layout) return null\n\n return applyPageRotationDeltasToScrollerLayout({\n basePageRotations,\n layout: layoutData.layout,\n pageRotationDeltas,\n })\n }, [basePageRotations, documentId, layoutData, pageRotationDeltas])\n\n React.useLayoutEffect(() => {\n if (!scrollPlugin || !documentId || !scrollerLayout) return\n scrollPlugin.setLayoutReady(documentId)\n }, [documentId, scrollPlugin, scrollerLayout])\n\n if (!scrollerLayout) return null\n\n return (\n <div\n style={{\n width: `${scrollerLayout.totalWidth}px`,\n height: `${scrollerLayout.totalHeight}px`,\n position: "relative",\n boxSizing: "border-box",\n margin: "0 auto",\n ...(scrollerLayout.strategy === ScrollStrategy.Horizontal && {\n display: "flex",\n flexDirection: "row",\n }),\n }}\n >\n <div\n style={\n scrollerLayout.strategy === ScrollStrategy.Horizontal\n ? {\n width: scrollerLayout.startSpacing,\n height: "100%",\n flexShrink: 0,\n }\n : {\n height: scrollerLayout.startSpacing,\n width: "100%",\n }\n }\n />\n <div\n style={{\n gap: scrollerLayout.pageGap,\n display: "flex",\n alignItems: "center",\n position: "relative",\n boxSizing: "border-box",\n ...(scrollerLayout.strategy === ScrollStrategy.Horizontal\n ? {\n flexDirection: "row",\n minHeight: "100%",\n }\n : {\n flexDirection: "column",\n minWidth: "fit-content",\n }),\n }}\n >\n {scrollerLayout.items.map((item) => (\n <div\n key={item.pageNumbers[0]}\n style={{\n display: "flex",\n justifyContent: "center",\n gap: scrollerLayout.pageGap,\n }}\n >\n {item.pageLayouts.map((layout) => (\n <div\n key={layout.pageNumber}\n style={{\n width: `${layout.rotatedWidth}px`,\n height: `${layout.rotatedHeight}px`,\n position: "relative",\n zIndex: layout.elevated ? 1 : undefined,\n }}\n >\n {renderPage(layout)}\n </div>\n ))}\n </div>\n ))}\n </div>\n <div\n style={\n scrollerLayout.strategy === ScrollStrategy.Horizontal\n ? {\n width: scrollerLayout.endSpacing,\n height: "100%",\n flexShrink: 0,\n }\n : {\n height: scrollerLayout.endSpacing,\n width: "100%",\n }\n }\n />\n </div>\n )\n}\n\ntype PDFViewerInnerProps = {\n viewerRef: React.ForwardedRef<PDFViewerHandle>\n pdfFile: string\n documentId: string\n document: PdfDocumentObject | null\n defaultZoom: number\n className?: string\n fileName?: string\n showDownload: boolean\n showToolbar: boolean\n showRotateControls: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onActivePageChange?: (pageNumber: number) => void\n onPdfUpload?: (file: File) => void\n onPagePointerDown?: PDFViewerProps["onPagePointerDown"]\n onPagePointerMove?: PDFViewerProps["onPagePointerMove"]\n onPagePointerUp?: PDFViewerProps["onPagePointerUp"]\n onPagePointerCancel?: PDFViewerProps["onPagePointerCancel"]\n onUploadFile: (file: File) => void\n}\n\nfunction PDFViewerInner({\n viewerRef,\n pdfFile,\n documentId,\n document: pdfDocument,\n defaultZoom,\n className,\n fileName,\n showDownload,\n showToolbar,\n showRotateControls,\n showUpload,\n toolbarActions,\n pageClassName,\n renderPageOverlay,\n onActivePageChange,\n onPdfUpload,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n onUploadFile,\n}: PDFViewerInnerProps) {\n const { registry } = useRegistry()\n const { state: scrollState, provides: scroll } = useScroll(documentId)\n const { state: zoomState, provides: zoom } = useZoom(documentId)\n const { provides: thumbnails } = useThumbnailCapability()\n const { plugin: thumbnailPlugin } = useThumbnailPlugin()\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)\n const [pageRotationDeltas, setPageRotationDeltas] =\n React.useState<PageRotationDeltas>(() => new Map())\n const [selectedPageIndexes, setSelectedPageIndexes] = React.useState<\n Set<number>\n >(() => new Set())\n const basePageRotations = React.useMemo(\n () =>\n pdfDocument?.pages.map((page) => normalizeRotation(page.rotation)) ?? [],\n [pdfDocument]\n )\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const viewportElementRef = React.useRef<HTMLDivElement | null>(null)\n const pageRotationDeltasRef = React.useRef(pageRotationDeltas)\n const selectedPageIndexesRef = React.useRef(selectedPageIndexes)\n const selectionAnchorPageIndexRef = React.useRef<number | null>(null)\n const suppressActivePageSelectionSyncRef = React.useRef<number | null>(null)\n const initializedSelectionDocumentRef = React.useRef<string | null>(null)\n\n const activePage = scrollState.currentPage\n const numPages = pdfDocument?.pageCount ?? 0\n const isLoading = !pdfDocument\n const controlsDisabled = !numPages\n const downloadDisabled = controlsDisabled || isPreparingDownload\n const thumbnailSidebarVisible = sidebarOpen && !isLoading\n const currentZoomLevel = zoomState.currentZoomLevel\n const alignedThumbnailSidebarDocumentRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n pageRotationDeltasRef.current = pageRotationDeltas\n }, [pageRotationDeltas])\n\n React.useEffect(() => {\n selectedPageIndexesRef.current = selectedPageIndexes\n }, [selectedPageIndexes])\n\n React.useEffect(() => {\n if (activePage > 0) onActivePageChange?.(activePage)\n }, [activePage, onActivePageChange])\n\n React.useEffect(() => {\n if (activePage < 1 || numPages < 1) return\n\n const activePageIndex = activePage - 1\n const suppressedPageIndex = suppressActivePageSelectionSyncRef.current\n\n suppressActivePageSelectionSyncRef.current = null\n\n if (suppressedPageIndex === activePageIndex) return\n\n const nextSelection = new Set([activePageIndex])\n\n selectionAnchorPageIndexRef.current = activePageIndex\n selectedPageIndexesRef.current = nextSelection\n setSelectedPageIndexes((previousSelection) =>\n arePageIndexSetsEqual(previousSelection, nextSelection)\n ? previousSelection\n : nextSelection\n )\n }, [activePage, numPages])\n\n React.useEffect(() => {\n if (\n numPages < 1 ||\n initializedSelectionDocumentRef.current === documentId\n ) {\n return\n }\n\n const initialPageIndex = Math.max(0, (activePage > 0 ? activePage : 1) - 1)\n const initialSelection = new Set([initialPageIndex])\n\n initializedSelectionDocumentRef.current = documentId\n selectionAnchorPageIndexRef.current = initialPageIndex\n selectedPageIndexesRef.current = initialSelection\n setSelectedPageIndexes(initialSelection)\n }, [activePage, documentId, numPages])\n\n React.useEffect(() => {\n if (!thumbnailSidebarVisible) {\n alignedThumbnailSidebarDocumentRef.current = null\n return\n }\n\n if (\n activePage < 1 ||\n !thumbnails ||\n alignedThumbnailSidebarDocumentRef.current === documentId\n ) {\n return\n }\n\n alignedThumbnailSidebarDocumentRef.current = documentId\n const frame = window.requestAnimationFrame(() => {\n thumbnails.forDocument(documentId).scrollToThumb(activePage - 1)\n })\n\n return () => window.cancelAnimationFrame(frame)\n }, [activePage, documentId, thumbnailSidebarVisible, thumbnails])\n\n // The zoom plugin only releases its viewport gate for mode-based zoom\n // levels (automatic/fit); with a numeric default the gate would never\n // lift, so apply the initial zoom explicitly once the document loads.\n const initialZoomDocumentRef = React.useRef<string | null>(null)\n React.useEffect(() => {\n if (!pdfDocument || !zoom) return\n if (initialZoomDocumentRef.current === documentId) return\n\n initialZoomDocumentRef.current = documentId\n zoom.requestZoom(defaultZoom)\n }, [defaultZoom, documentId, pdfDocument, zoom])\n\n const scrollToPage = React.useCallback(\n (pageNumber: number, options?: ScrollIntoViewOptions) => {\n scroll?.scrollToPage({\n pageNumber,\n behavior: options?.behavior === "smooth" ? "smooth" : "auto",\n })\n },\n [scroll]\n )\n\n const selectThumbnailPage = React.useCallback(\n (pageNumber: number, mode: ThumbnailSelectionMode) => {\n const pageIndex = pageNumber - 1\n\n if (pageIndex < 0 || pageIndex >= numPages) return\n\n suppressActivePageSelectionSyncRef.current = pageIndex\n\n setSelectedPageIndexes((previousSelection) => {\n let nextSelection: Set<number>\n\n if (mode === "range") {\n const anchorPageIndex =\n selectionAnchorPageIndexRef.current ??\n (activePage > 0 ? activePage - 1 : pageIndex)\n\n nextSelection = getPageIndexRange(anchorPageIndex, pageIndex)\n } else if (mode === "toggle") {\n nextSelection = new Set(previousSelection)\n\n if (nextSelection.has(pageIndex)) {\n nextSelection.delete(pageIndex)\n } else {\n nextSelection.add(pageIndex)\n }\n\n selectionAnchorPageIndexRef.current = pageIndex\n } else {\n nextSelection = new Set([pageIndex])\n selectionAnchorPageIndexRef.current = pageIndex\n }\n\n selectedPageIndexesRef.current = nextSelection\n return nextSelection\n })\n\n scrollToPage(pageNumber)\n },\n [activePage, numPages, scrollToPage]\n )\n\n React.useImperativeHandle(\n viewerRef,\n () => ({\n scrollToPage,\n scrollToPageArea: (pageNumber, area, options) => {\n const pageSize = pdfDocument?.pages[pageNumber - 1]?.size\n\n scroll?.scrollToPage({\n pageNumber,\n ...(pageSize\n ? {\n pageCoordinates: {\n x: ((area.left ?? 0) / 100) * pageSize.width,\n y: (area.top / 100) * pageSize.height,\n },\n alignY: 25,\n }\n : {}),\n behavior: options?.behavior === "smooth" ? "smooth" : "auto",\n })\n },\n getViewportElement: () => viewportElementRef.current,\n }),\n [pdfDocument, scroll, scrollToPage]\n )\n\n const handleDownload = React.useCallback(async () => {\n if (!pdfFile || isPreparingDownload) return\n\n setIsPreparingDownload(true)\n\n try {\n await downloadPdfWithPageRotations({\n fileName: getPdfDownloadFileName(fileName, pdfFile),\n pageRotationDeltas,\n src: pdfFile,\n })\n } catch (error) {\n console.error(error)\n } finally {\n setIsPreparingDownload(false)\n }\n }, [fileName, isPreparingDownload, pageRotationDeltas, pdfFile])\n\n const rotateSelectedPages = React.useCallback(\n (direction: -1 | 1) => {\n if (!pdfDocument || !registry || activePage < 1) return\n\n const documentState = registry.getStore().getState().core.documents[\n documentId\n ]\n const currentDocument = documentState?.document ?? pdfDocument\n const selectedTargetPageIndexes = Array.from(\n selectedPageIndexesRef.current\n ).filter((pageIndex) => currentDocument.pages[pageIndex])\n const fallbackPageIndex = activePage - 1\n const targetPageIndexes = (\n selectedTargetPageIndexes.length\n ? selectedTargetPageIndexes\n : [fallbackPageIndex]\n )\n .filter((pageIndex) => currentDocument.pages[pageIndex])\n .sort((a, b) => a - b)\n\n if (targetPageIndexes.length === 0) return\n\n const previousDeltas = pageRotationDeltasRef.current\n const nextDeltas = new Map(previousDeltas)\n const referencePageIndex =\n activePage > 0 && currentDocument.pages[activePage - 1]\n ? activePage - 1\n : targetPageIndexes[0]\n let scrollDelta = 0\n\n for (const pageIndex of targetPageIndexes) {\n const currentPage = currentDocument.pages[pageIndex]\n if (!currentPage) continue\n\n const previousDelta = previousDeltas.get(pageIndex) ?? 0\n const nextDelta = normalizeRotation(previousDelta + direction)\n const basePageRotation =\n basePageRotations[pageIndex] ??\n normalizeRotation(currentPage.rotation)\n const previousPageRotation = normalizeRotation(\n basePageRotation + previousDelta\n )\n const nextPageRotation = normalizeRotation(basePageRotation + nextDelta)\n const previousRotatedSize = getRotatedDimensions({\n height: currentPage.size.height * currentZoomLevel,\n rotation: previousPageRotation,\n width: currentPage.size.width * currentZoomLevel,\n })\n const nextRotatedSize = getRotatedDimensions({\n height: currentPage.size.height * currentZoomLevel,\n rotation: nextPageRotation,\n width: currentPage.size.width * currentZoomLevel,\n })\n const heightDelta = nextRotatedSize.height - previousRotatedSize.height\n\n if (pageIndex < referencePageIndex) {\n scrollDelta += heightDelta\n } else if (pageIndex === referencePageIndex) {\n scrollDelta += heightDelta / 2\n }\n\n if (nextDelta) {\n nextDeltas.set(pageIndex, nextDelta)\n } else {\n nextDeltas.delete(pageIndex)\n }\n }\n\n const store = registry.getStore()\n const viewport = viewportElementRef.current\n\n pageRotationDeltasRef.current = nextDeltas\n flushSync(() => {\n setPageRotationDeltas(nextDeltas)\n store.dispatchToCore(refreshPages(documentId, targetPageIndexes))\n })\n\n if (viewport && scrollDelta !== 0) {\n viewport.scrollTop += scrollDelta\n }\n ;(\n thumbnailPlugin as {\n calculateWindowState?: (documentId: string) => void\n } | null\n )?.calculateWindowState?.(documentId)\n },\n [\n activePage,\n basePageRotations,\n currentZoomLevel,\n documentId,\n pdfDocument,\n registry,\n thumbnailPlugin,\n ]\n )\n\n const handleUpload = React.useCallback(\n (file: File) => {\n onUploadFile(file)\n onPdfUpload?.(file)\n },\n [onPdfUpload, onUploadFile]\n )\n\n const renderPage = React.useCallback(\n (page: PageLayout) => {\n const pageNumber = page.pageNumber\n const basePageRotation =\n basePageRotations[page.pageIndex] ??\n pdfDocument?.pages[page.pageIndex]?.rotation ??\n normalizeRotation(0)\n const pageRotation = normalizeRotation(\n basePageRotation + (pageRotationDeltas.get(page.pageIndex) ?? 0)\n )\n\n return (\n <Rotate\n documentId={documentId}\n pageIndex={page.pageIndex}\n rotation={pageRotation}\n >\n <PagePointerProvider\n documentId={documentId}\n pageIndex={page.pageIndex}\n rotation={pageRotation}\n key={`${page.pageIndex}-${pageRotation}`}\n data-pdf-viewer-page={pageNumber}\n className={cn(\n "relative border border-transparent bg-transparent shadow-xs select-none selection:bg-transparent selection:text-inherit",\n pageClassName?.(pageNumber)\n )}\n style={{ backgroundColor: "transparent" }}\n onPointerDown={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerDown?.(event, pageNumber)\n }\n onPointerMove={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerMove?.(event, pageNumber)\n }\n onPointerUp={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerUp?.(event, pageNumber)\n }\n onPointerCancel={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerCancel?.(event, pageNumber)\n }\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(currentZoomLevel, 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 key={`tiles-${page.pageIndex}-${pageRotation}`}\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 <PDFViewerTextSelectionLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n scale={currentZoomLevel}\n />\n {renderPageOverlay?.({\n pageNumber,\n pageWidth: page.width,\n pageHeight: page.height,\n scale: currentZoomLevel,\n rotation: rotationToDegrees(pageRotation),\n })}\n </PagePointerProvider>\n </Rotate>\n )\n },\n [\n basePageRotations,\n currentZoomLevel,\n onPagePointerCancel,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n pageClassName,\n pageRotationDeltas,\n renderPageOverlay,\n documentId,\n pdfDocument,\n ]\n )\n\n return (\n <div\n data-slot="pdf-viewer"\n className={cn(\n "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n {showToolbar ? (\n <PDFViewerToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n currentZoomLevel={currentZoomLevel}\n downloadDisabled={downloadDisabled}\n isPreparingDownload={isPreparingDownload}\n numPages={numPages}\n searchControl={\n <PDFViewerSearchControl\n key={documentId}\n documentId={documentId}\n controlsDisabled={controlsDisabled}\n />\n }\n sidebarOpen={sidebarOpen}\n showDownload={showDownload}\n showRotateControls={showRotateControls}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n onDownload={handleDownload}\n onPageChange={scrollToPage}\n onRotate={rotateSelectedPages}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadFile={handleUpload}\n onZoomChange={(zoomLevel) => zoom?.requestZoom(zoomLevel)}\n />\n ) : null}\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {isLoading ? (\n <PDFViewerLoadingSkeleton\n sidebarInline={sidebarInline}\n sidebarOpen={sidebarOpen}\n />\n ) : null}\n <div className="flex h-full max-h-full min-h-0 w-full flex-1 overflow-hidden">\n <DocumentViewerThumbnailSidebar\n closedInlineClassName={THUMBNAIL_SIDEBAR_CLOSED_CLASS}\n inline={sidebarInline}\n open={thumbnailSidebarVisible}\n widthClassName={THUMBNAIL_SIDEBAR_WIDTH_CLASS}\n >\n {thumbnailSidebarVisible ? (\n <PDFViewerThumbnails\n basePageRotations={basePageRotations}\n documentId={documentId}\n activePage={activePage}\n pageCount={numPages}\n pageRotationDeltas={pageRotationDeltas}\n pdfDocument={pdfDocument}\n selectedPageIndexes={selectedPageIndexes}\n onSelectPage={selectThumbnailPage}\n />\n ) : null}\n </DocumentViewerThumbnailSidebar>\n <PDFViewerScrollAreaViewport\n documentId={documentId}\n className="relative h-full max-h-full min-h-0 min-w-0 flex-1"\n >\n <PDFViewerViewportBridge viewportElementRef={viewportElementRef} />\n <PDFViewerSelectionCopyShortcut documentId={documentId} />\n <PDFViewerSelectionReleaseGuard documentId={documentId} />\n <GlobalPointerProvider documentId={documentId}>\n <PDFViewerScroller\n basePageRotations={basePageRotations}\n documentId={documentId}\n pageRotationDeltas={pageRotationDeltas}\n renderPage={renderPage}\n />\n </GlobalPointerProvider>\n <CopyToClipboard />\n </PDFViewerScrollAreaViewport>\n </div>\n </div>\n </div>\n )\n}\n\nfunction PDFViewerDocumentLoader({\n pdfFile,\n onDocumentLoadSuccess,\n ...innerProps\n}: {\n pdfFile: string\n onDocumentLoadSuccess?: (numPages: number) => void\n} & Omit<PDFViewerInnerProps, "pdfFile" | "documentId" | "document">) {\n const { provides: documentManager } = useDocumentManagerCapability()\n const { activeDocumentId, activeDocument } = useActiveDocument()\n const [loadError, setLoadError] = React.useState(false)\n const openedFileRef = React.useRef<string | null>(null)\n const onDocumentLoadSuccessRef = React.useRef(onDocumentLoadSuccess)\n\n React.useEffect(() => {\n onDocumentLoadSuccessRef.current = onDocumentLoadSuccess\n })\n\n React.useEffect(() => {\n if (!documentManager || !pdfFile) return\n if (openedFileRef.current === pdfFile) return\n\n openedFileRef.current = pdfFile\n setLoadError(false)\n\n const previousDocumentIds = documentManager\n .getOpenDocuments()\n .map((openDocument) => openDocument.id)\n const handleOpenError = () => {\n if (openedFileRef.current === pdfFile) setLoadError(true)\n }\n\n documentManager\n .openDocumentUrl({\n url: pdfFile,\n mode: pdfFile.startsWith("blob:") ? "full-fetch" : "auto",\n })\n .wait((response) => {\n response.task.wait((openedDocument) => {\n onDocumentLoadSuccessRef.current?.(openedDocument.pageCount)\n previousDocumentIds.forEach((documentIdToClose) => {\n documentManager.closeDocument(documentIdToClose).wait(\n () => undefined,\n () => undefined\n )\n })\n }, handleOpenError)\n }, handleOpenError)\n }, [documentManager, pdfFile])\n\n const document =\n activeDocument?.status === "loaded" ? activeDocument.document : null\n const documentFailed = loadError || activeDocument?.status === "error"\n\n if (!activeDocumentId || documentFailed || !pdfFile) {\n return (\n <PDFViewerFallbackShell\n className={innerProps.className}\n defaultZoom={innerProps.defaultZoom}\n showDownload={innerProps.showDownload}\n showRotateControls={innerProps.showRotateControls}\n showToolbar={innerProps.showToolbar}\n showUpload={innerProps.showUpload}\n sidebarOpen={false}\n state={!pdfFile ? "empty" : documentFailed ? "error" : "loading"}\n toolbarActions={innerProps.toolbarActions}\n onUploadFile={(file) => {\n innerProps.onUploadFile(file)\n innerProps.onPdfUpload?.(file)\n }}\n />\n )\n }\n\n return (\n <PDFViewerInner\n key={activeDocumentId}\n {...innerProps}\n pdfFile={pdfFile}\n documentId={activeDocumentId}\n document={document}\n />\n )\n}\n\nexport const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(\n function PDFViewer(\n {\n className,\n defaultZoom = DEFAULT_ZOOM,\n fileName,\n resolveScrollAreaViewport,\n showDownload = true,\n showRotateControls = true,\n showToolbar = true,\n showUpload = true,\n src,\n toolbarActions,\n pageClassName,\n renderPageOverlay,\n onActivePageChange,\n onDocumentLoadSuccess,\n onPdfUpload,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n },\n ref\n ) {\n const { engine, error: engineError } = useSharedPdfEngine()\n const [uploadedPdfFile, setUploadedPdfFile] = React.useState<{\n src: string | undefined\n url: string | null\n }>(() => ({ src, url: null }))\n const uploadedPdfUrl =\n uploadedPdfFile.src === src ? uploadedPdfFile.url : null\n const pdfFile = uploadedPdfUrl ?? src ?? ""\n\n React.useEffect(\n () => () => {\n if (uploadedPdfUrl) URL.revokeObjectURL(uploadedPdfUrl)\n },\n [uploadedPdfUrl]\n )\n\n const handleUploadFile = React.useCallback(\n (nextFile: File) => {\n const nextUrl = URL.createObjectURL(nextFile)\n\n setUploadedPdfFile({ src, url: nextUrl })\n },\n [src]\n )\n\n // Plugin registrations are created once per viewer 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 marquee: { enabled: false },\n }),\n createPluginRegistration(SearchPluginPackage, {\n showAllResults: true,\n }),\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: defaultZoom,\n minZoom: ZOOM_OPTIONS[0],\n maxZoom: ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1],\n }),\n createPluginRegistration(RotatePluginPackage),\n ])\n\n if (engineError) {\n return (\n <PDFViewerFallbackShell\n className={className}\n defaultZoom={defaultZoom}\n errorMessage="Unable to load the PDF engine."\n showDownload={showDownload}\n showRotateControls={showRotateControls}\n showToolbar={showToolbar}\n showUpload={showUpload}\n sidebarOpen={false}\n state="error"\n toolbarActions={toolbarActions}\n onUploadFile={(file) => {\n handleUploadFile(file)\n onPdfUpload?.(file)\n }}\n />\n )\n }\n\n if (!engine) {\n return (\n <PDFViewerFallbackShell\n className={className}\n defaultZoom={defaultZoom}\n showDownload={showDownload}\n showRotateControls={showRotateControls}\n showToolbar={showToolbar}\n showUpload={showUpload}\n sidebarOpen={false}\n state="loading"\n toolbarActions={toolbarActions}\n onUploadFile={(file) => {\n handleUploadFile(file)\n onPdfUpload?.(file)\n }}\n />\n )\n }\n\n return (\n <PDFViewerScrollAreaResolverContext.Provider\n value={resolveScrollAreaViewport ?? resolveDefaultScrollAreaViewport}\n >\n <EmbedPDF engine={engine} plugins={plugins}>\n <PDFViewerDocumentLoader\n viewerRef={ref}\n pdfFile={pdfFile}\n defaultZoom={defaultZoom}\n className={className}\n fileName={fileName}\n showDownload={showDownload}\n showToolbar={showToolbar}\n showRotateControls={showRotateControls}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n pageClassName={pageClassName}\n renderPageOverlay={renderPageOverlay}\n onActivePageChange={onActivePageChange}\n onDocumentLoadSuccess={onDocumentLoadSuccess}\n onPdfUpload={onPdfUpload}\n onPagePointerDown={onPagePointerDown}\n onPagePointerMove={onPagePointerMove}\n onPagePointerUp={onPagePointerUp}\n onPagePointerCancel={onPagePointerCancel}\n onUploadFile={handleUploadFile}\n />\n </EmbedPDF>\n </PDFViewerScrollAreaResolverContext.Provider>\n )\n }\n)\n'export function PdfViewerSourceCode() {return (diff --git a/apps/v4/components/ui/color-picker.tsx b/apps/v4/components/ui/color-picker.tsxindex ed00237..62eb50d 100644--- a/apps/v4/components/ui/color-picker.tsx+++ b/apps/v4/components/ui/color-picker.tsx@@ -2,9 +2,31 @@import * as React from "react"+import {+ clamp,+ cuspColorForHue,+ formatColorValue,+ formatCssColor,+ getOklchPlanePixels,+ hslToRgb,+ hsvToHsl,+ normalizeHue,+ oklchPlaneToRgb,+ oklchToRgb,+ parseColorInput,+ rgbaToHex,+ rgbToHsv,+ rgbToOklch,+ rgbToOklchPlane,+ type ColorFormat,+ type ColorParts,+ type HslColor,+ type HsvColor,+ type OklchColor,+ type RgbColor,+} from "@/lib/color-picker-utils"import { cn } from "@/lib/utils"import { Button } from "@/components/ui/button"-import { Input } from "@/components/ui/input"import {Popover,PopoverContent,@@ -14,8 +36,7 @@ import {Select,SelectContent,SelectItem,- SelectTrigger,- SelectValue,+ SelectPrimitive,} from "@/components/ui/select"import {Tooltip,@@ -24,473 +45,1129 @@ import {} from "@/components/ui/tooltip"import { IconPlaceholder } from "@/components/icon-placeholder"-const COLOR_PICKER_PRESETS = [- "#111827",- "#52525b",- "#dc2626",- "#ea580c",- "#ca8a04",- "#16a34a",- "#0891b2",- "#2563eb",- "#4f46e5",- "#9333ea",- "#db2777",- "#ffffff",-] as const-const COLOR_PICKER_FORMATS = ["hex", "rgb", "css", "hsl"] as const--type ColorPickerFormat = (typeof COLOR_PICKER_FORMATS)[number]-type HslColor = [number, number, number]-type HsvColor = [number, number, number]--function normalizeHexColor(value?: string, fallback = "#111827") {- if (!value) return fallback-- const trimmed = value.trim()- const threeDigit = /^#([0-9a-f]{3})$/i.exec(trimmed)- if (threeDigit?.[1]) {- const [red, green, blue] = threeDigit[1].split("")- return `#${red}${red}${green}${green}${blue}${blue}`.toLowerCase()- }-- const sixDigit = /^#([0-9a-f]{6})$/i.exec(trimmed)- if (sixDigit?.[1]) {- return `#${sixDigit[1].toLowerCase()}`- }+const cossInputKeyboardFocusRing =+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"+const cossInputWrapperFocusRing =+ "focus-within:border-input-focus focus-within:ring-1 focus-within:ring-input-focus/24 focus-within:ring-offset-0 dark:focus-within:border-input-focus dark:focus-within:ring-input-focus/24"+const cossOutlineEdge =+ "before:pointer-events-none before:absolute before:inset-0 before:rounded-[inherit]"+const cossOutlineEdgeHighlight =+ "before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]"- return fallback+interface HsvaColor {+ h: number+ s: number+ v: number+ a: number}-function clampNumber(value: number, min: number, max: number) {- return Math.min(max, Math.max(min, value))+type EyeDropperConstructor = new () => {+ open: () => Promise<{ sRGBHex: string }>}-function normalizeHue(value: number) {- return ((value % 360) + 360) % 360+declare global {+ interface Window {+ EyeDropper?: EyeDropperConstructor+ }}-function clampPercent(value: number) {- return clampNumber(value, 0, 100)-}+const COLOR_FORMAT_OPTIONS: Array<{ value: ColorFormat; label: string }> = [+ { value: "oklch", label: "OKLCH" },+ { value: "hsl", label: "HSL" },+ { value: "rgb", label: "RGB" },+ { value: "hex", label: "Hex" },+]-function clampByte(value: number) {- return clampNumber(Math.round(value), 0, 255)+const OK_HUE_TRACK = `linear-gradient(to bottom, ${Array.from(+ { length: 25 },+ (_, i) => rgbaToHex(cuspColorForHue(i * 15))+).join(", ")})`++// Ignore hue noise from RGB round trips.+function withHueContinuity<T extends { h: number }>(+ next: T,+ previousHue: number,+ chromaFraction: number+): T {+ const delta = Math.abs(next.h - previousHue) % 360+ const angular = Math.min(delta, 360 - delta)+ const tolerance = Math.min(10, 1.5 / Math.max(chromaFraction, 0.15))+ return angular < tolerance ? { ...next, h: previousHue } : next}-function parseHexToRgb(value: string): [number, number, number] | undefined {- const hex = normalizeHexColor(value, "")- const match = /^#([0-9a-f]{6})$/i.exec(hex)- if (!match?.[1]) return undefined+const triggerGroupClass =+ "relative flex h-10 w-full min-w-0 items-center rounded-md border border-input bg-popover not-dark:bg-clip-padding text-base text-foreground shadow-xs/5 ring-input-focus/32 transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-md)-1px)] not-has-disabled:not-has-focus-visible:before:shadow-[0_1px_--theme(--color-black/4%)] has-focus-visible:border-input-focus has-focus-visible:ring-[3px] has-disabled:opacity-64 has-[:disabled,:focus-visible]:shadow-none dark:bg-input/32 dark:ring-input-focus/32 dark:has-focus-visible:border-input-focus dark:not-has-focus-visible:border-white/[0.08] dark:not-has-disabled:before:shadow-[0_-1px_--theme(--color-white/2%)] dark:not-has-disabled:not-has-focus-visible:before:shadow-[0_-1px_--theme(--color-white/6%)]"- return [- Number.parseInt(match[1].slice(0, 2), 16),- Number.parseInt(match[1].slice(2, 4), 16),- Number.parseInt(match[1].slice(4, 6), 16),- ]-}+const fieldSurfaceClass = cn(+ "relative rounded-md border border-input bg-popover text-foreground shadow-xs/5 transition-shadow not-dark:bg-clip-padding dark:border-white/[0.08] dark:bg-input/32",+ cossOutlineEdge,+ cossOutlineEdgeHighlight,+ cossInputWrapperFocusRing+)-function rgbToHsl(red: number, green: number, blue: number): HslColor {- const r = clampByte(red) / 255- const g = clampByte(green) / 255- const b = clampByte(blue) / 255- const max = Math.max(r, g, b)- const min = Math.min(r, g, b)- let h = 0- let s = 0- const l = (max + min) / 2-- if (max !== min) {- const delta = max - min- s = l > 0.5 ? delta / (2 - max - min) : delta / (max + min)- if (max === r) {- h = (g - b) / delta + (g < b ? 6 : 0)- } else if (max === g) {- h = (b - r) / delta + 2- } else {- h = (r - g) / delta + 4- }- h /= 6- }+const channelInputClass =+ "h-full w-full min-w-0 border-0 bg-transparent px-1 py-0 text-center text-sm leading-none tabular-nums text-foreground outline-none [transition:background-color_5000000s_ease-in-out_0s] placeholder:text-muted-foreground/72 focus:border-0 focus:outline-none focus:ring-0"- return [- normalizeHue(h * 360),- clampNumber(s * 100, 0, 100),- clampNumber(l * 100, 0, 100),- ]+const thumbShadow = "shadow-[0_0_0_1px_rgb(0_0_0/24%),0_1px_2px_rgb(0_0_0/32%)]"++function Checkerboard({+ className,+ size = 8,+}: {+ className?: string+ size?: number+}) {+ return (+ <span+ aria-hidden="true"+ className={cn(+ "pointer-events-none absolute inset-0 bg-white [--checker:#00000024] dark:bg-neutral-700 dark:[--checker:#ffffff2e]",+ className+ )}+ style={{+ backgroundImage:+ "conic-gradient(var(--checker) 0 25%, transparent 0 50%, var(--checker) 0 75%, transparent 0)",+ backgroundSize: `${size}px ${size}px`,+ }}+ />+ )}-function hslToRgb(hue: number, saturation: number, lightness: number) {- const h = normalizeHue(hue) / 360- const s = clampPercent(saturation) / 100- const l = clampPercent(lightness) / 100+interface DraftInputProps+ extends Omit<+ React.InputHTMLAttributes<HTMLInputElement>,+ "value" | "onChange"+ > {+ value: string+ onCommitText: (text: string) => void+ onStep?: (direction: 1 | -1, big: boolean) => void+ copyValue?: () => string+ inputRef?: React.MutableRefObject<HTMLInputElement | null>+}- if (s === 0) {- const channel = clampByte(l * 255)- return [channel, channel, channel] as const- }+function DraftInput({+ value,+ onCommitText,+ onStep,+ copyValue,+ inputRef,+ ...props+}: DraftInputProps) {+ const [draft, setDraft] = React.useState<string | null>(null)+ const internalRef = React.useRef<HTMLInputElement | null>(null)+ // Keep mouseup from clearing the focus selection.+ const keepSelectionRef = React.useRef(false)- const hueToRgb = (p: number, q: number, value: number) => {- let t = value- if (t < 0) t += 1- if (t > 1) t -= 1- if (t < 1 / 6) return p + (q - p) * 6 * t- if (t < 1 / 2) return q- if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6- return p+ const setRefs = (node: HTMLInputElement | null) => {+ internalRef.current = node+ if (inputRef) inputRef.current = node}- const q = l < 0.5 ? l * (1 + s) : l + s - l * s- const p = 2 * l - q-- return [- clampByte(hueToRgb(p, q, h + 1 / 3) * 255),- clampByte(hueToRgb(p, q, h) * 255),- clampByte(hueToRgb(p, q, h - 1 / 3) * 255),- ] as const-}--function hslToHex([h, s, l]: HslColor) {- return `#${hslToRgb(h, s, l)- .map((channel) => channel.toString(16).padStart(2, "0"))- .join("")}`-}+ const commitDraft = () => {+ if (draft !== null && draft.trim() !== value) onCommitText(draft)+ setDraft(null)+ }-function hslToHsv([hue, saturation, lightness]: HslColor): HsvColor {- const s = clampPercent(saturation) / 100- const l = clampPercent(lightness) / 100- const value = l + s * Math.min(l, 1 - l)- const hsvSaturation = value === 0 ? 0 : 2 * (1 - l / value)+ const reselect = () => {+ requestAnimationFrame(() => internalRef.current?.select())+ }- return [- normalizeHue(hue),- clampPercent(hsvSaturation * 100),- clampPercent(value * 100),- ]+ return (+ <input+ autoComplete="off"+ autoCorrect="off"+ spellCheck={false}+ type="text"+ {...props}+ ref={setRefs}+ value={draft ?? value}+ onFocus={(event) => {+ setDraft(event.currentTarget.value)+ event.currentTarget.select()+ keepSelectionRef.current = true+ }}+ onMouseUp={(event) => {+ if (keepSelectionRef.current) {+ event.preventDefault()+ keepSelectionRef.current = false+ }+ }}+ onChange={(event) => setDraft(event.target.value)}+ onBlur={commitDraft}+ onCopy={(event) => {+ if (!copyValue) return+ const input = event.currentTarget+ const fullySelected =+ input.value.length > 0 &&+ input.selectionStart === 0 &&+ input.selectionEnd === input.value.length+ if (!fullySelected) return+ event.preventDefault()+ event.clipboardData.setData("text/plain", copyValue())+ }}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ commitDraft()+ reselect()+ } else if (event.key === "Escape") {+ if (draft !== null) {+ event.stopPropagation()+ setDraft(null)+ }+ } else if (+ onStep &&+ (event.key === "ArrowUp" || event.key === "ArrowDown")+ ) {+ event.preventDefault()+ setDraft(null)+ onStep(event.key === "ArrowUp" ? 1 : -1, event.shiftKey)+ reselect()+ }+ }}+ />+ )}-function hsvToHsl([hue, saturation, value]: HsvColor): HslColor {- const s = clampPercent(saturation) / 100- const v = clampPercent(value) / 100- const lightness = v * (1 - s / 2)- const hslSaturation =- lightness === 0 || lightness === 1- ? 0- : (v - lightness) / Math.min(lightness, 1 - lightness)-- return [- normalizeHue(hue),- clampPercent(hslSaturation * 100),- clampPercent(lightness * 100),- ]+interface ChannelSpec {+ key: string+ label: string+ ariaLabel: string+ value: string+ numericValue: number+ step: number+ bigStep: number+ commit: (next: number) => void}-function normalizeHslColor([hue, saturation, lightness]: HslColor): HslColor {- return [normalizeHue(hue), clampPercent(saturation), clampPercent(lightness)]+function parseChannelText(text: string): number | null {+ const numeric = Number.parseFloat(text.replace(/[%°]/g, "").trim())+ return Number.isFinite(numeric) ? numeric : null}-function normalizeHsvColor([hue, saturation, value]: HsvColor): HsvColor {- return [normalizeHue(hue), clampPercent(saturation), clampPercent(value)]+function ChannelGroup({+ channels,+ copyValue,+ disabled,+}: {+ channels: ChannelSpec[]+ copyValue: string+ disabled?: boolean+}) {+ return (+ <div className="flex items-start gap-1.5">+ <div className="min-w-0 flex-1">+ <div className={cn(fieldSurfaceClass, "grid h-8 grid-cols-3")}>+ {channels.map((channel) => (+ <DraftInput+ key={channel.key}+ aria-label={channel.ariaLabel}+ className={channelInputClass}+ disabled={disabled}+ inputMode="decimal"+ value={channel.value}+ onCommitText={(text) => {+ const numeric = parseChannelText(text)+ if (numeric !== null) channel.commit(numeric)+ }}+ onStep={(direction, big) =>+ channel.commit(+ channel.numericValue ++ direction * (big ? channel.bigStep : channel.step)+ )+ }+ />+ ))}+ <span+ aria-hidden="true"+ className="pointer-events-none absolute inset-y-0 left-1/3 w-px bg-input dark:bg-white/[0.08]"+ />+ <span+ aria-hidden="true"+ className="pointer-events-none absolute inset-y-0 left-2/3 w-px bg-input dark:bg-white/[0.08]"+ />+ </div>+ <div className="mt-1 grid h-4 grid-cols-3 items-center text-center text-xs font-medium text-muted-foreground">+ {channels.map((channel) => (+ <span key={channel.key}>{channel.label}</span>+ ))}+ </div>+ </div>+ <CopyColorButton text={copyValue} />+ </div>+ )}-function parseColor(value: string): HslColor | undefined {- const trimmed = value.trim()- if (!trimmed) return undefined-- const rgbFromHex = parseHexToRgb(trimmed)- if (rgbFromHex) return rgbToHsl(...rgbFromHex)+function SaturationValueArea({+ hue,+ s,+ v,+ color,+ onMove,+}: {+ hue: number+ s: number+ v: number+ color: string+ onMove: (s: number, v: number) => void+}) {+ const canvasRef = React.useRef<HTMLCanvasElement | null>(null)+ // Avoid redraws for imperceptible hue changes.+ const quantizedHue = Math.round(normalizeHue(hue) * 2) / 2- const rgbMatch = /^rgba?\(([^)]+)\)$/i.exec(trimmed)- if (rgbMatch?.[1]) {- const values = rgbMatch[1].match(/-?\d+(?:\.\d+)?/g)?.map(Number) ?? []- if (values.length >= 3) return rgbToHsl(values[0], values[1], values[2])- }+ React.useEffect(() => {+ const canvas = canvasRef.current+ const context = canvas?.getContext("2d")+ if (!canvas || !context) return+ const image = context.createImageData(canvas.width, canvas.height)+ image.data.set(+ getOklchPlanePixels(canvas.width, canvas.height, quantizedHue)+ )+ context.putImageData(image, 0, 0)+ }, [quantizedHue])- const hslMatch = /^hsla?\(([^)]+)\)$/i.exec(trimmed)- if (hslMatch?.[1]) {- const values = hslMatch[1].match(/-?\d+(?:\.\d+)?/g)?.map(Number) ?? []- if (values.length >= 3) {- return [- normalizeHue(values[0]),- clampPercent(values[1]),- clampPercent(values[2]),- ]- }+ const update = (event: React.PointerEvent<HTMLButtonElement>) => {+ const rect = event.currentTarget.getBoundingClientRect()+ const inset = 7+ onMove(+ clamp(+ ((event.clientX - rect.left - inset) / (rect.width - inset * 2)) * 100,+ 0,+ 100+ ),+ clamp(+ 100 -+ ((event.clientY - rect.top - inset) / (rect.height - inset * 2)) *+ 100,+ 0,+ 100+ )+ )}- return undefined+ return (+ <button+ type="button"+ aria-label="Chroma and lightness"+ className={cn(+ "relative size-53 shrink-0 cursor-crosshair touch-none rounded-lg",+ cossInputKeyboardFocusRing+ )}+ onPointerDown={(event) => {+ event.preventDefault()+ event.currentTarget.setPointerCapture(event.pointerId)+ event.currentTarget.focus()+ update(event)+ }}+ onPointerMove={(event) => {+ if ((event.buttons & 1) === 0) return+ update(event)+ }}+ onKeyDown={(event) => {+ const delta = event.shiftKey ? 10 : 1+ let next: [number, number] | null = null+ if (event.key === "ArrowLeft") next = [s - delta, v]+ if (event.key === "ArrowRight") next = [s + delta, v]+ if (event.key === "ArrowUp") next = [s, v + delta]+ if (event.key === "ArrowDown") next = [s, v - delta]+ if (next) {+ event.preventDefault()+ onMove(clamp(next[0], 0, 100), clamp(next[1], 0, 100))+ }+ }}+ >+ <canvas+ ref={canvasRef}+ aria-hidden="true"+ width={168}+ height={168}+ className="pointer-events-none absolute inset-0 size-full rounded-[inherit]"+ />+ <span+ className={cn(+ "pointer-events-none absolute size-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-[1.5px] border-white",+ thumbShadow+ )}+ style={{+ left: `calc(7px + (100% - 14px) * ${clamp(s, 0, 100) / 100})`,+ top: `calc(7px + (100% - 14px) * ${clamp(100 - v, 0, 100) / 100})`,+ backgroundColor: color,+ }}+ />+ </button>+ )}-function formatColor(color: HslColor, format: ColorPickerFormat) {- const [h, s, l] = color- const [red, green, blue] = hslToRgb(h, s, l)-- if (format === "rgb") return `rgb(${red}, ${green}, ${blue})`- if (format === "css") return `rgba(${red}, ${green}, ${blue}, 1)`- if (format === "hsl") {- return `hsl(${Math.round(h)}, ${Math.round(s)}%, ${Math.round(l)}%)`+function VerticalSlider({+ ariaLabel,+ ariaValueMax,+ ariaValueNow,+ ariaValueText,+ fraction,+ onFraction,+ onStep,+ track,+}: {+ ariaLabel: string+ ariaValueMax: number+ ariaValueNow: number+ ariaValueText?: string+ fraction: number+ onFraction: (fraction: number) => void+ onStep: (direction: 1 | -1, big: boolean) => void+ track: React.ReactNode+}) {+ const update = (event: React.PointerEvent<HTMLButtonElement>) => {+ const rect = event.currentTarget.getBoundingClientRect()+ const inset = 2.5+ onFraction(+ clamp(+ (event.clientY - rect.top - inset) / (rect.height - inset * 2),+ 0,+ 1+ )+ )}- return hslToHex(color)+ return (+ <button+ type="button"+ role="slider"+ aria-label={ariaLabel}+ aria-orientation="vertical"+ aria-valuemin={0}+ aria-valuemax={ariaValueMax}+ aria-valuenow={ariaValueNow}+ aria-valuetext={ariaValueText}+ className={cn(+ "relative w-3 shrink-0 touch-none self-stretch rounded-full",+ cossInputKeyboardFocusRing+ )}+ onPointerDown={(event) => {+ event.preventDefault()+ event.currentTarget.setPointerCapture(event.pointerId)+ event.currentTarget.focus()+ update(event)+ }}+ onPointerMove={(event) => {+ if ((event.buttons & 1) === 0) return+ update(event)+ }}+ onKeyDown={(event) => {+ let direction: 1 | -1 | null = null+ if (event.key === "ArrowUp" || event.key === "ArrowRight") direction = 1+ if (event.key === "ArrowDown" || event.key === "ArrowLeft")+ direction = -1+ if (direction) {+ event.preventDefault()+ onStep(direction, event.shiftKey)+ }+ }}+ >+ <span className="absolute inset-0 overflow-hidden rounded-full ring-1 ring-black/8 ring-inset dark:ring-white/12">+ {track}+ </span>+ <span+ className="pointer-events-none absolute left-1/2 h-[5px] w-[calc(100%+3px)] -translate-x-1/2 -translate-y-1/2 rounded-full bg-white shadow-[0_0_0_1px_rgb(0_0_0/20%),0_1px_2px_rgb(0_0_0/24%)]"+ style={{ top: `calc(2.5px + (100% - 5px) * ${clamp(fraction, 0, 1)})` }}+ />+ </button>+ )}-function ColorPickerTooltip({- label,- children,+function CopyColorButton({+ text,+ label = "Copy color",}: {- label: string- children: React.ReactNode+ text: string+ label?: string}) {+ const [copied, setCopied] = React.useState(false)++ const handleCopy = async () => {+ try {+ await navigator.clipboard.writeText(text)+ setCopied(true)+ window.setTimeout(() => setCopied(false), 1200)+ } catch {+ // Clipboard access can be unavailable outside secure browser contexts.+ }+ }+return (<Tooltip>- <TooltipTrigger asChild>- <span className="inline-flex">{children}</span>+ <TooltipTrigger+ render={+ <Button+ type="button"+ variant="outline"+ size="icon-sm"+ aria-label={label}+ className="size-8! shrink-0"+ onClick={handleCopy}+ />+ }+ >+ <IconPlaceholder+ lucide={copied ? "Check" : "Copy"}+ tabler={copied ? "IconCheck" : "IconCopy"}+ hugeicons={copied ? "Tick02Icon" : "Copy01Icon"}+ phosphor={copied ? "CheckIcon" : "CopyIcon"}+ remixicon={copied ? "RiCheckLine" : "RiFileCopyLine"}+ className="size-4"+ /></TooltipTrigger>- <TooltipContent side="bottom">{label}</TooltipContent>+ <TooltipContent side="top">{copied ? "Copied" : "Copy"}</TooltipContent></Tooltip>)}-export function ColorPicker({- color,+function AlphaScrubField({+ alphaPercent,disabled,- icon: IconComponent,- label,- onTriggerMouseDown,- onTriggerPointerDown,- onChange,+ onCommit,+ scrubbable = true,+ className,+ inputClassName,+ suffixClassName,}: {- color: string+ alphaPercent: numberdisabled?: boolean- icon: React.ComponentType<React.ComponentProps<"svg">>- label: string- onTriggerMouseDown?: React.MouseEventHandler<HTMLButtonElement>- onTriggerPointerDown?: React.PointerEventHandler<HTMLButtonElement>- onChange: (color: string) => void+ onCommit: (percent: number) => void+ scrubbable?: boolean+ className?: string+ inputClassName?: string+ suffixClassName?: string}) {- const [open, setOpen] = React.useState(false)+ const inputRef = React.useRef<HTMLInputElement | null>(null)+ const scrubRef = React.useRef<{+ startX: number+ startPercent: number+ scrubbed: boolean+ } | null>(null)+ const rounded = Math.round(alphaPercent)++ const scrubHandlers: React.HTMLAttributes<HTMLDivElement> = scrubbable+ ? {+ onPointerDown: (event) => {+ if (disabled) return+ if (document.activeElement === inputRef.current) return+ event.preventDefault()+ event.currentTarget.setPointerCapture(event.pointerId)+ scrubRef.current = {+ startX: event.clientX,+ startPercent: alphaPercent,+ scrubbed: false,+ }+ },+ onPointerMove: (event) => {+ const scrub = scrubRef.current+ if (!scrub || (event.buttons & 1) === 0) return+ const dx = event.clientX - scrub.startX+ if (!scrub.scrubbed && Math.abs(dx) < 3) return+ scrub.scrubbed = true+ onCommit(clamp(scrub.startPercent + dx / 2, 0, 100))+ },+ onPointerUp: () => {+ const scrub = scrubRef.current+ scrubRef.current = null+ if (scrub && !scrub.scrubbed) inputRef.current?.focus()+ },+ onPointerCancel: () => {+ scrubRef.current = null+ },+ }+ : {}return (- <Popover open={open} onOpenChange={setOpen}>- <ColorPickerTooltip label={label}>- <PopoverTrigger asChild>- <Button- type="button"- variant="ghost"- size="icon-sm"- disabled={disabled}- aria-label={label}- className="relative"- onMouseDown={onTriggerMouseDown}- onPointerDown={onTriggerPointerDown}- >- <IconComponent className="size-4" />- <span- className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"- style={{ backgroundColor: color }}- />- </Button>- </PopoverTrigger>- </ColorPickerTooltip>- <PopoverContent align="start" className="z-40 w-72 p-1">- <ColorPickerPanel color={color} label={label} onChange={onChange} />- </PopoverContent>- </Popover>+ <div+ className={cn(+ "flex h-full shrink-0 items-center gap-0.5",+ scrubbable && "cursor-ew-resize touch-none select-none",+ className+ )}+ {...scrubHandlers}+ >+ <DraftInput+ aria-label="Opacity"+ className={cn(+ "border-0 bg-transparent p-0 text-right tabular-nums outline-none focus:border-0 focus:ring-0",+ inputClassName ?? "w-8 text-base"+ )}+ disabled={disabled}+ inputMode="decimal"+ inputRef={inputRef}+ value={String(rounded)}+ onCommitText={(text) => {+ const numeric = parseChannelText(text)+ if (numeric !== null) onCommit(clamp(numeric, 0, 100))+ }}+ onStep={(direction, big) =>+ onCommit(clamp(alphaPercent + direction * (big ? 10 : 1), 0, 100))+ }+ />+ <span+ className={cn("text-muted-foreground", suffixClassName ?? "text-base")}+ >+ %+ </span>+ </div>)}-export function ColorPickerPanel({- className,+export type ColorPickerProps = {+ value?: string+ color?: string+ onChange?: (value: string) => void+ label?: string+ disabled?: boolean+ showAlpha?: boolean+ defaultFormat?: ColorFormat+ variant?: "input" | "swatch" | "panel"+ className?: string+ icon?: React.ComponentType<React.ComponentProps<"svg">>+ rainbowTrigger?: boolean+ onTriggerMouseDown?: React.MouseEventHandler<HTMLButtonElement>+ onTriggerPointerDown?: React.PointerEventHandler<HTMLButtonElement>+}++export function ColorPicker({+ value: valueProp,color,- label,onChange,-}: {- className?: string- color: string- label: string- onChange: (color: string) => void-}) {- const parsedColor = React.useMemo(- () => parseColor(color) ?? parseColor("#111827")!,- [color]- )- const parsedFieldColor = React.useMemo(- () => hslToHsv(parsedColor),- [parsedColor]- )- const [format, setFormat] = React.useState<ColorPickerFormat>("hex")- const [hsl, setHsl] = React.useState<HslColor>(parsedColor)- const [fieldHsv, setFieldHsv] = React.useState<HsvColor>(parsedFieldColor)- const [inputValue, setInputValue] = React.useState(() =>- formatColor(parsedColor, "hex")- )+ label = "Choose color",+ disabled = false,+ showAlpha = false,+ defaultFormat = "hex",+ variant,+ className,+ icon: IconComponent,+ rainbowTrigger = false,+ onTriggerMouseDown,+ onTriggerPointerDown,+}: ColorPickerProps) {+ const value = valueProp ?? color ?? "#111827"+ const resolvedVariant = variant ?? (color !== undefined ? "swatch" : "input")+ const [open, setOpen] = React.useState(false)++ // Keep drag coordinates independent from exact typed RGB values.+ const [picker, setPicker] = React.useState<{+ plane: HsvColor+ rgb: RgbColor+ a: number+ }>(() => {+ const parsed = parseColorInput(value, "hex")+ if (!parsed)+ return { plane: { h: 0, s: 0, v: 0 }, rgb: { r: 0, g: 0, b: 0 }, a: 1 }+ return {+ plane: rgbToOklchPlane(parsed.rgb),+ rgb: parsed.rgb,+ a: showAlpha ? (parsed.alpha ?? 1) : 1,+ }+ })+ const [format, setFormat] = React.useState<ColorFormat>(defaultFormat)+ const lastCommitAtRef = React.useRef(0)+ const triggerGroupRef = React.useRef<HTMLDivElement>(null)React.useEffect(() => {- setHsl(parsedColor)- setFieldHsv(parsedFieldColor)- setInputValue(formatColor(parsedColor, format))- }, [format, parsedColor, parsedFieldColor])-- function applyColor(nextColor: HslColor, nextFieldColor?: HsvColor) {- const normalizedColor = normalizeHslColor(nextColor)- const normalizedFieldColor = normalizeHsvColor(- nextFieldColor ?? hslToHsv(normalizedColor)- )- setHsl(normalizedColor)- setFieldHsv(normalizedFieldColor)- setInputValue(formatColor(normalizedColor, format))- onChange(hslToHex(normalizedColor))+ if (!value) return+ // User input wins over delayed controlled-value echoes.+ if (Date.now() - lastCommitAtRef.current < 400) return+ const parsed = parseColorInput(value, "hex")+ if (!parsed) return+ setPicker((prev) => {+ // Preserve opacity when the parent stores only RGB.+ const alpha = showAlpha ? (parsed.alpha ?? prev.a) : 1+ // Preserve unrounded channel precision.+ if (rgbaToHex(prev.rgb, prev.a) === rgbaToHex(parsed.rgb, alpha))+ return prev+ const derived = rgbToOklchPlane(parsed.rgb, prev.plane.h)+ return {+ plane: withHueContinuity(derived, prev.plane.h, derived.s / 100),+ rgb: parsed.rgb,+ a: alpha,+ }+ })+ }, [value, showAlpha])++ const applyState = (next: { plane: HsvColor; rgb: RgbColor; a: number }) => {+ setPicker(next)+ lastCommitAtRef.current = Date.now()+ const hex = rgbaToHex(next.rgb, next.a)+ onChange?.(hex)}- function updateColorField(- event: React.PointerEvent<HTMLDivElement> | React.MouseEvent<HTMLDivElement>- ) {- const rect = event.currentTarget.getBoundingClientRect()- const x = clampNumber(event.clientX - rect.left, 0, rect.width)- const y = clampNumber(event.clientY - rect.top, 0, rect.height)- const nextFieldColor: HsvColor = [- fieldHsv[0],- Math.round((x / rect.width) * 100),- Math.round(100 - (y / rect.height) * 100),- ]-- applyColor(hsvToHsl(nextFieldColor), nextFieldColor)+ const commitHsva = (next: HsvaColor) => {+ const plane: HsvColor = {+ h: clamp(next.h, 0, 360),+ s: clamp(next.s, 0, 100),+ v: clamp(next.v, 0, 100),+ }+ applyState({+ plane,+ rgb: oklchPlaneToRgb(plane),+ a: showAlpha ? clamp(next.a, 0, 1) : 1,+ })}- function handleInputChange(event: React.ChangeEvent<HTMLInputElement>) {- const nextValue = event.target.value- setInputValue(nextValue)+ const hsva: HsvaColor = { ...picker.plane, a: picker.a }+ const rgb = picker.rgb+ // Preserve hue for achromatic colors.+ const srgbHueRef = React.useRef(0)+ const displayHsv = rgbToHsv(rgb, srgbHueRef.current)+ srgbHueRef.current = displayHsv.h+ const hsl = hsvToHsl(displayHsv)+ const rawOklch = rgbToOklch(rgb, hsva.h)+ const oklch = withHueContinuity(rawOklch, hsva.h, rawOklch.c / 0.33)+ const parts: ColorParts = { rgb, hsl, oklch, alpha: hsva.a }+ const opaqueColor = `rgb(${Math.round(rgb.r)} ${Math.round(rgb.g)} ${Math.round(rgb.b)})`+ const currentColor = `rgb(${Math.round(rgb.r)} ${Math.round(rgb.g)} ${Math.round(rgb.b)} / ${hsva.a})`- const parsed = parseColor(nextValue)- if (parsed) {- setHsl(parsed)- setFieldHsv(hslToHsv(parsed))- onChange(hslToHex(parsed))+ const commitRgb = (+ nextRgb: RgbColor,+ alpha?: number | null,+ intendedHue?: number+ ) => {+ const exact: RgbColor = {+ r: clamp(nextRgb.r, 0, 255),+ g: clamp(nextRgb.g, 0, 255),+ b: clamp(nextRgb.b, 0, 255),}+ const targetHue = intendedHue ?? picker.plane.h+ const derived = rgbToOklchPlane(exact, targetHue)+ applyState({+ plane: withHueContinuity(derived, targetHue, derived.s / 100),+ rgb: exact,+ a: showAlpha ? clamp(alpha ?? picker.a, 0, 1) : 1,+ })+ }+ const commitHsl = (nextHsl: HslColor) => commitRgb(hslToRgb(nextHsl))+ const commitOklch = (nextOklch: OklchColor) =>+ commitRgb(oklchToRgb(nextOklch), undefined, normalizeHue(nextOklch.h))+ const commitText = (text: string) => {+ const parsed = parseColorInput(text, format)+ if (!parsed) return+ if (parsed.format && parsed.format !== format) setFormat(parsed.format)+ commitRgb(parsed.rgb, parsed.alpha)}- return (- <div className={cn("space-y-1.5", className)}>- <div className="flex justify-end">- <Select- value={format}- onValueChange={(value) => {- const nextFormat = value as ColorPickerFormat- setFormat(nextFormat)- setInputValue(formatColor(hsl, nextFormat))- }}- >- <SelectTrigger- size="sm"- className="h-7 w-24 text-xs"- aria-label="Color format"- >- <SelectValue />- </SelectTrigger>- <SelectContent align="end" alignItemWithTrigger={false}>- {COLOR_PICKER_FORMATS.map((option) => (- <SelectItem key={option} value={option}>- {option.toUpperCase()}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>+ const cssColor = formatCssColor(format, parts, { includeAlpha: showAlpha })+ const portalContainer =+ typeof document === "undefined" ? undefined : document.body+ const supportsEyeDropper =+ typeof window !== "undefined" && window.EyeDropper !== undefined- <div- className="relative h-32 cursor-crosshair overflow-hidden rounded-lg"- style={{- background: `- linear-gradient(to top, rgb(0 0 0), transparent),- linear-gradient(to right, rgb(255 255 255), rgb(255 255 255 / 0)),- hsl(${hsl[0]} 100% 50%)- `,- }}- onPointerDown={(event) => {- event.preventDefault()- event.currentTarget.setPointerCapture(event.pointerId)- updateColorField(event)- }}- onPointerMove={(event) => {- if (event.buttons !== 1) return- updateColorField(event)- }}- >- <span- className="absolute size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_1px_4px_rgb(0_0_0/0.45)] ring-1 ring-black/20"- style={{- left: `${fieldHsv[1]}%`,- top: `${100 - fieldHsv[2]}%`,- backgroundColor: hslToHex(hsl),- }}- />- </div>+ const handleEyeDropper = () => {+ const eyeDropperCtor = window.EyeDropper+ if (!eyeDropperCtor) return+ new eyeDropperCtor()+ .open()+ .then((result) => {+ const parsed = parseColorInput(result.sRGBHex, "hex")+ if (parsed) commitRgb(parsed.rgb)+ })+ .catch(() => {})+ }- <input- type="range"- min={0}- max={359}- value={hsl[0]}- aria-label="Hue"- className="h-3 w-full cursor-pointer appearance-none rounded-full border border-border bg-transparent accent-foreground"- style={{- background:- "linear-gradient(to right, hsl(0 100% 50%), hsl(60 100% 50%), hsl(120 100% 50%), hsl(180 100% 50%), hsl(240 100% 50%), hsl(300 100% 50%), hsl(360 100% 50%))",- }}- onChange={(event) =>- applyColor(- hsvToHsl([Number(event.target.value), fieldHsv[1], fieldHsv[2]]),- [Number(event.target.value), fieldHsv[1], fieldHsv[2]]- )- }- />+ const oklchChannels: ChannelSpec[] = [+ {+ key: "l",+ label: "L",+ ariaLabel: "OKLCH lightness",+ value: (oklch.l * 100).toFixed(1),+ numericValue: oklch.l * 100,+ step: 1,+ bigStep: 10,+ commit: (next) => commitOklch({ ...oklch, l: clamp(next, 0, 100) / 100 }),+ },+ {+ key: "c",+ label: "C",+ ariaLabel: "OKLCH chroma",+ value: oklch.c.toFixed(3),+ numericValue: oklch.c,+ step: 0.01,+ bigStep: 0.05,+ commit: (next) => commitOklch({ ...oklch, c: Math.max(0, next) }),+ },+ {+ key: "h",+ label: "H",+ ariaLabel: "OKLCH hue",+ value: oklch.h.toFixed(1),+ numericValue: oklch.h,+ step: 1,+ bigStep: 10,+ commit: (next) => commitOklch({ ...oklch, h: normalizeHue(next) }),+ },+ ]++ const hslChannels: ChannelSpec[] = [+ {+ key: "h",+ label: "H",+ ariaLabel: "HSL hue",+ value: hsl.h.toFixed(1),+ numericValue: hsl.h,+ step: 1,+ bigStep: 10,+ commit: (next) => commitHsl({ ...hsl, h: normalizeHue(next) }),+ },+ {+ key: "s",+ label: "S",+ ariaLabel: "HSL saturation",+ value: hsl.s.toFixed(1),+ numericValue: hsl.s,+ step: 1,+ bigStep: 10,+ commit: (next) => commitHsl({ ...hsl, s: clamp(next, 0, 100) }),+ },+ {+ key: "l",+ label: "L",+ ariaLabel: "HSL lightness",+ value: hsl.l.toFixed(1),+ numericValue: hsl.l,+ step: 1,+ bigStep: 10,+ commit: (next) => commitHsl({ ...hsl, l: clamp(next, 0, 100) }),+ },+ ]++ const rgbChannels: ChannelSpec[] = (["r", "g", "b"] as const).map(+ (channel) => ({+ key: channel,+ label: channel.toUpperCase(),+ ariaLabel: { r: "Red", g: "Green", b: "Blue" }[channel],+ value: String(Math.round(rgb[channel])),+ numericValue: rgb[channel],+ step: 1,+ bigStep: 10,+ commit: (next) => commitRgb({ ...rgb, [channel]: clamp(next, 0, 255) }),+ })+ )- <Input- value={inputValue}- aria-label={`${label} value`}- className="h-8 w-full font-mono text-xs"- spellCheck={false}- onChange={handleInputChange}- onBlur={() => setInputValue(formatColor(hsl, format))}+ const panel = (+ <div+ className={cn(+ "flex items-stretch gap-3",+ resolvedVariant === "panel" && className+ )}+ >+ <SaturationValueArea+ hue={hsva.h}+ s={hsva.s}+ v={hsva.v}+ color={opaqueColor}+ onMove={(s, v) => commitHsva({ ...hsva, s, v })}/>- <div className="grid grid-cols-6 gap-1.5">- {COLOR_PICKER_PRESETS.map((preset) => {- const selected = hslToHex(hsl) === preset+ <div className="flex shrink-0 flex-col items-center gap-1.5 self-stretch">+ <div className="flex min-h-0 flex-1 items-stretch gap-2">+ {showAlpha && (+ <VerticalSlider+ ariaLabel="Opacity"+ ariaValueMax={100}+ ariaValueNow={Math.round(hsva.a * 100)}+ ariaValueText={`${Math.round(hsva.a * 100)}%`}+ fraction={1 - hsva.a}+ onFraction={(fraction) =>+ commitHsva({ ...hsva, a: 1 - fraction })+ }+ onStep={(direction, big) =>+ commitHsva({+ ...hsva,+ a: clamp(hsva.a + direction * (big ? 0.1 : 0.01), 0, 1),+ })+ }+ track={+ <>+ <Checkerboard size={6} />+ <span+ className="absolute inset-0"+ style={{+ background: `linear-gradient(to bottom, ${opaqueColor}, transparent)`,+ }}+ />+ </>+ }+ />+ )}- return (- <button- key={preset}- type="button"- className={cn(- "grid size-6 place-items-center rounded-full border shadow-xs transition-transform hover:scale-110 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",- selected && "ring-2 ring-ring ring-offset-2"- )}- style={{ backgroundColor: preset }}- aria-label={`Use ${preset}`}- onMouseDown={(event) => event.preventDefault()}- onClick={() => {- const parsedPreset = parseColor(preset)- if (parsedPreset) applyColor(parsedPreset)- }}+ <VerticalSlider+ ariaLabel="Hue"+ ariaValueMax={360}+ ariaValueNow={Math.round(hsva.h)}+ fraction={clamp(hsva.h, 0, 360) / 360}+ onFraction={(fraction) =>+ commitHsva({ ...hsva, h: fraction * 360 })+ }+ onStep={(direction, big) =>+ commitHsva({+ ...hsva,+ h: clamp(hsva.h - direction * (big ? 10 : 1), 0, 360),+ })+ }+ track={+ <span+ className="absolute inset-0"+ style={{ background: OK_HUE_TRACK }}+ />+ }+ />+ </div>+ {supportsEyeDropper ? (+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ type="button"+ variant="outline"+ size="icon-sm"+ aria-label="Pick color from screen"+ className="size-8! shrink-0"+ onClick={handleEyeDropper}+ />+ }>- {selected ? (- <IconPlaceholder- lucide="Check"- tabler="IconCheck"- hugeicons="CheckIcon"- phosphor="CheckIcon"- remixicon="RiCheckLine"- className={cn(- "size-3.5",- preset === "#ffffff" ? "text-foreground" : "text-white"- )}+ <IconPlaceholder+ lucide="Pipette"+ tabler="IconColorPicker"+ hugeicons="ColorPickerIcon"+ phosphor="EyedropperIcon"+ remixicon="RiColorPickerLine"+ className="size-4"+ />+ </TooltipTrigger>+ <TooltipContent side="top" className="whitespace-nowrap">+ Pick color from screen+ </TooltipContent>+ </Tooltip>+ ) : null}+ </div>++ <div className="flex w-64 shrink-0 flex-col gap-2">+ <ChannelGroup+ channels={oklchChannels}+ copyValue={formatCssColor("oklch", parts, {+ includeAlpha: showAlpha,+ })}+ disabled={disabled}+ />+ <ChannelGroup+ channels={hslChannels}+ copyValue={formatCssColor("hsl", parts, { includeAlpha: showAlpha })}+ disabled={disabled}+ />+ <ChannelGroup+ channels={rgbChannels}+ copyValue={formatCssColor("rgb", parts, { includeAlpha: showAlpha })}+ disabled={disabled}+ />++ <div className="flex items-center gap-1.5">+ <div+ className={cn(+ fieldSurfaceClass,+ "flex h-8 min-w-0 flex-1 items-center"+ )}+ >+ <DraftInput+ aria-label="Color value"+ className="h-full min-w-0 flex-1 rounded-[inherit] border-0 bg-transparent px-2 py-0 text-center text-sm leading-none tabular-nums outline-none focus:border-0 focus:ring-0"+ copyValue={() => cssColor}+ value={formatColorValue(format, parts)}+ onCommitText={commitText}+ />+ {showAlpha && (+ <AlphaScrubField+ alphaPercent={hsva.a * 100}+ disabled={disabled}+ scrubbable={false}+ className="gap-0.5 pr-2 pl-0.5"+ inputClassName="w-8 text-sm"+ suffixClassName="text-sm"+ onCommit={(percent) =>+ commitHsva({ ...hsva, a: percent / 100 })+ }+ />+ )}+ </div>+ <Select+ value={format}+ onValueChange={(next) => {+ if (next !== null) setFormat(next)+ }}+ >+ <SelectPrimitive.Trigger+ render={+ <Button+ type="button"+ variant="outline"+ size="icon-sm"+ aria-label="Color format"+ className="size-8! shrink-0"/>- ) : null}- </button>- )- })}+ }+ >+ <IconPlaceholder+ lucide="ChevronsUpDown"+ tabler="IconSelector"+ hugeicons="UnfoldMoreIcon"+ phosphor="CaretUpDownIcon"+ remixicon="RiExpandUpDownLine"+ className="size-3.5"+ />+ </SelectPrimitive.Trigger>+ <SelectContent+ align="end"+ className="min-w-28"+ portalProps={{ container: portalContainer }}+ >+ {COLOR_FORMAT_OPTIONS.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div></div></div>)++ if (resolvedVariant === "panel") return panel++ return (+ <Popover open={open} onOpenChange={setOpen}>+ {resolvedVariant === "swatch" ? (+ <PopoverTrigger+ render={+ <Button+ type="button"+ variant={IconComponent || rainbowTrigger ? "ghost" : "outline"}+ size="icon-sm"+ aria-label={label}+ disabled={disabled}+ data-color-picker-trigger=""+ className={cn("relative shrink-0", className)}+ onMouseDown={onTriggerMouseDown}+ onPointerDown={onTriggerPointerDown}+ />+ }+ >+ {rainbowTrigger ? (+ <span+ aria-hidden="true"+ className="size-5 shrink-0 rounded-full bg-[conic-gradient(from_90deg,#ff3b30,#ffcc00,#34c759,#00c7be,#007aff,#af52de,#ff2d55,#ff3b30)] shadow-[0_0_0_1px_rgb(0_0_0/10%)]"+ />+ ) : IconComponent ? (+ <>+ <IconComponent className="size-4" />+ <span+ aria-hidden="true"+ className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"+ style={{ backgroundColor: currentColor }}+ />+ </>+ ) : (+ <span className="relative size-4 shrink-0 overflow-hidden rounded-[4px]">+ <Checkerboard size={4} />+ <span+ aria-hidden="true"+ className="absolute inset-0"+ style={{ backgroundColor: currentColor }}+ />+ <span+ aria-hidden="true"+ className="absolute inset-0 rounded-[inherit] ring-1 ring-black/12 ring-inset dark:ring-white/16"+ />+ </span>+ )}+ </PopoverTrigger>+ ) : (+ <div+ ref={triggerGroupRef}+ data-color-picker-trigger=""+ data-slot="color-picker"+ className={cn(triggerGroupClass, className)}+ >+ <PopoverTrigger+ render={+ <button+ type="button"+ aria-label={label}+ disabled={disabled}+ className={cn(+ "relative ml-2 size-6 shrink-0 overflow-hidden rounded-[calc(var(--radius-md)-2px)]",+ cossInputKeyboardFocusRing+ )}+ />+ }+ >+ <Checkerboard size={6} />+ <span+ aria-hidden="true"+ className="absolute inset-0"+ style={{ backgroundColor: currentColor }}+ />+ <span+ aria-hidden="true"+ className="absolute inset-0 rounded-[inherit] ring-1 ring-black/12 ring-inset dark:ring-white/16"+ />+ </PopoverTrigger>+ <DraftInput+ aria-label={`${label} value`}+ className="h-full w-full min-w-0 grow border-0 bg-transparent px-[calc(--spacing(2.5)-1px)] text-base tabular-nums outline-none [transition:background-color_5000000s_ease-in-out_0s] placeholder:text-muted-foreground/72 focus:border-0 focus:ring-0"+ copyValue={() => cssColor}+ disabled={disabled}+ value={formatColorValue(format, parts)}+ onCommitText={commitText}+ />+ {showAlpha && (+ <AlphaScrubField+ alphaPercent={hsva.a * 100}+ disabled={disabled}+ className="pr-[calc(--spacing(3)-1px)] pl-1"+ onCommit={(percent) => commitHsva({ ...hsva, a: percent / 100 })}+ />+ )}+ </div>+ )}+ <PopoverContent+ anchor={resolvedVariant === "swatch" ? undefined : triggerGroupRef}+ align={resolvedVariant === "swatch" ? "end" : "start"}+ sideOffset={8}+ portalProps={{ container: portalContainer }}+ className="w-auto p-0 [&>[data-slot=popover-viewport]]:p-3.5!"+ >+ {panel}+ </PopoverContent>+ </Popover>+ )+}++export function ColorPickerPanel({+ className,+ color,+ label,+ onChange,+ showAlpha = false,+}: {+ className?: string+ color: string+ label: string+ onChange: (color: string) => void+ showAlpha?: boolean+}) {+ return (+ <ColorPicker+ className={className}+ value={color}+ label={label}+ onChange={onChange}+ showAlpha={showAlpha}+ variant="panel"+ />+ )}diff --git a/apps/v4/components/ui/scroll-area.tsx b/apps/v4/components/ui/scroll-area.tsxindex 40566a0..006d85d 100644--- a/apps/v4/components/ui/scroll-area.tsx+++ b/apps/v4/components/ui/scroll-area.tsx@@ -53,8 +53,8 @@ export function ScrollArea({"transition-shadows h-full rounded-[inherit] outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-has-overflow-x:overscroll-x-contain data-has-overflow-y:overscroll-y-contain",scrollFade &&"mask-t-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-start)))] mask-r-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-end)))] mask-b-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-end)))] mask-l-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-start)))] [--fade-size:1.5rem]",- scrollbarGutter &&- "data-has-overflow-x:pb-2.5 data-has-overflow-y:pe-2.5",+ scrollbarGutter && orientation !== "vertical" && "pb-3.5",+ scrollbarGutter && orientation !== "horizontal" && "pe-3.5",viewportPropsClassName,viewportClassName)}diff --git a/apps/v4/components/ui/switch.tsx b/apps/v4/components/ui/switch.tsxnew file mode 100644index 0000000..ff002a4--- /dev/null+++ b/apps/v4/components/ui/switch.tsx@@ -0,0 +1,3 @@+"use client"++export * from "@/registry/new-york-v4/ui/switch"diff --git a/apps/v4/components/ui/toast.tsx b/apps/v4/components/ui/toast.tsxnew file mode 100644index 0000000..8b5da30--- /dev/null+++ b/apps/v4/components/ui/toast.tsx@@ -0,0 +1,12 @@+"use client"++export {+ AnchoredToastProvider,+ anchoredToastManager,+ ToastPrimitive,+ ToastProvider,+ toastManager,+ type AnchoredToastProviderProps,+ type ToastPosition,+ type ToastProviderProps,+} from "@/registry/new-york-v4/ui/toast"diff --git a/apps/v4/components/ui/toggle.tsx b/apps/v4/components/ui/toggle.tsxindex a785c9d..07f687d 100644--- a/apps/v4/components/ui/toggle.tsx+++ b/apps/v4/components/ui/toggle.tsx@@ -6,6 +6,7 @@ import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-groupimport { cva, type VariantProps } from "class-variance-authority"import { cn } from "@/lib/utils"+import { groupVariants } from "@/components/ui/group"export const toggleVariants = cva("relative inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 rounded-lg border text-base font-medium whitespace-nowrap text-foreground transition-shadow outline-none select-none before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-64 data-pressed:bg-input/64 data-pressed:text-accent-foreground sm:text-sm pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 [&_svg]:pointer-events-none [&_svg]:-mx-0.5 [&_svg]:shrink-0 [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4",@@ -76,6 +77,8 @@ export function ToggleGroup<Value extends string>({<ToggleGroupPrimitiveclassName={cn(toggleGroupVariants({ orientation, spacing: resolvedSpacing }),+ resolvedSpacing === "none" && groupVariants({ orientation }),+ "inline-flex",className)}data-orientation={orientation}@@ -96,10 +99,7 @@ export function ToggleGroupItem({VariantProps<typeof toggleVariants>): React.ReactElement {return (<Toggle- className={cn(- "in-data-[spacing=none]:rounded-none in-data-[spacing=none]:shadow-none in-data-[orientation=horizontal]:in-data-[spacing=none]:first:rounded-l-lg in-data-[orientation=horizontal]:in-data-[spacing=none]:last:rounded-r-lg in-data-[orientation=vertical]:in-data-[spacing=none]:first:rounded-t-lg in-data-[orientation=vertical]:in-data-[spacing=none]:last:rounded-b-lg",- className- )}+ className={className}data-slot="toggle-group-item"size={size}variant={variant}diff --git a/apps/v4/components/xlsx-editor-docs.tsx b/apps/v4/components/xlsx-editor-docs.tsxindex da4b69e..4aa7550 100644--- a/apps/v4/components/xlsx-editor-docs.tsx+++ b/apps/v4/components/xlsx-editor-docs.tsx@@ -67,7 +67,7 @@ export function XlsxEditorExample() {}`const xlsxEditorSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n useXlsxViewer,\n useXlsxViewerController,\n useXlsxViewerEditing,\n useXlsxViewerSelection,\n useXlsxViewerZoom,\n XlsxViewer,\n XlsxViewerProvider,\n type XlsxCellAlignmentInput,\n type XlsxCellBorderEdgeInput,\n type XlsxCellRange,\n type XlsxCellStyleInput,\n type XlsxSheetData,\n type XlsxTableHeaderMenuRenderProps,\n} from "@extend-ai/react-xlsx"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport { ColorPicker, ColorPickerPanel } from "@/components/ui/color-picker"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuGroup,\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuSub,\n DropdownMenuSubContent,\n DropdownMenuSubTrigger,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { Group, GroupSeparator, GroupText } from "@/components/ui/group"\nimport { Input } from "@/components/ui/input"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport {\n renderXlsxScroller,\n WorkbookSheetTabs,\n WorkbookTableHeaderMenu,\n} from "@/components/extend/xlsx-viewer"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nfunction BorderAll01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Grid2x2"\n tabler="IconBorderAll"\n hugeicons="BorderAll01Icon"\n phosphor="GridFourIcon"\n remixicon="RiGridLine"\n {...props}\n />\n )\n}\n\nfunction BorderBottom01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PanelBottom"\n tabler="IconBorderBottom"\n hugeicons="BorderBottom01Icon"\n phosphor="SquareHalfBottomIcon"\n remixicon="RiLayoutBottomLine"\n {...props}\n />\n )\n}\n\nfunction BorderLeft01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PanelLeft"\n tabler="IconBorderLeft"\n hugeicons="BorderLeft01Icon"\n phosphor="SquareHalfIcon"\n remixicon="RiLayoutLeftLine"\n {...props}\n />\n )\n}\n\nfunction BorderNone01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="SquareDashed"\n tabler="IconBorderNone"\n hugeicons="BorderNone01Icon"\n phosphor="SelectionIcon"\n remixicon="RiCheckboxBlankLine"\n {...props}\n />\n )\n}\n\nfunction BorderRight01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PanelRight"\n tabler="IconBorderRight"\n hugeicons="BorderRight01Icon"\n phosphor="SquareHalfIcon"\n remixicon="RiLayoutRightLine"\n {...props}\n />\n )\n}\n\nfunction BorderTop01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PanelTop"\n tabler="IconBorderTop"\n hugeicons="BorderTop01Icon"\n phosphor="AlignTopSimpleIcon"\n remixicon="RiLayoutTopLine"\n {...props}\n />\n )\n}\n\nfunction Calendar03Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Calendar"\n tabler="IconCalendar"\n hugeicons="Calendar03Icon"\n phosphor="CalendarIcon"\n remixicon="RiCalendarLine"\n {...props}\n />\n )\n}\n\nfunction DollarCircleGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="CircleDollarSign"\n tabler="IconCurrencyDollar"\n hugeicons="DollarCircleIcon"\n phosphor="CurrencyCircleDollarIcon"\n remixicon="RiMoneyDollarCircleLine"\n {...props}\n />\n )\n}\n\nfunction Moon02Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Moon"\n tabler="IconMoon"\n hugeicons="Moon02Icon"\n phosphor="MoonIcon"\n remixicon="RiMoonLine"\n {...props}\n />\n )\n}\n\nfunction PaintBucketGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PaintBucket"\n tabler="IconPaint"\n hugeicons="PaintBucketIcon"\n phosphor="PaintBucketIcon"\n remixicon="RiPaintFill"\n {...props}\n />\n )\n}\n\nfunction PercentGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Percent"\n tabler="IconPercentage"\n hugeicons="PercentIcon"\n phosphor="PercentIcon"\n remixicon="RiPercentLine"\n {...props}\n />\n )\n}\n\nfunction Sun03Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Sun"\n tabler="IconSun"\n hugeicons="Sun03Icon"\n phosphor="SunIcon"\n remixicon="RiSunLine"\n {...props}\n />\n )\n}\n\nfunction TextColorGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Baseline"\n tabler="IconTextColor"\n hugeicons="TextColorIcon"\n phosphor="TextAaIcon"\n remixicon="RiFontColor"\n {...props}\n />\n )\n}\n\nfunction TextNumberSignGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Hash"\n tabler="IconHash"\n hugeicons="TextNumberSignIcon"\n phosphor="HashIcon"\n remixicon="RiHashtag"\n {...props}\n />\n )\n}\n\nfunction TextWrapGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="WrapText"\n tabler="IconTextWrap"\n hugeicons="TextWrapIcon"\n phosphor="ArrowElbowDownLeftIcon"\n remixicon="RiTextWrap"\n {...props}\n />\n )\n}\n\nconst XLSX_LOADING_INDICATOR_DELAY_MS = 300\nconst XLSX_EDITOR_READ_ONLY_THRESHOLD_BYTES = 5 * 1024 * 1024\nconst XLSX_DROPDOWN_Z_INDEX_CLASS = "z-40"\nconst ZOOM_OPTIONS = [50, 75, 100, 125, 150, 200, 400] as const\nconst DEFAULT_FONT_FAMILY = "Arial"\nconst FONT_FAMILIES = [\n "Arial",\n "Times New Roman",\n "Georgia",\n "Helvetica",\n "Courier New",\n] as const\nconst FONT_SIZE_OPTIONS = [\n 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48,\n] as const\nconst DEFAULT_TEXT_COLOR = "#111827"\nconst DEFAULT_FILL_COLOR = "#fde68a"\nconst DEFAULT_BORDER_COLOR = "#111827"\nconst XLSX_EDITOR_SELECT_CHROME_CLASS =\n "shadow-none before:shadow-none not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-none dark:not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-none"\nconst XLSX_EDITOR_FORMULA_INPUT_CHROME_CLASS =\n "has-disabled:opacity-100 dark:has-disabled:before:shadow-[0_-1px_--theme(--color-white/6%)]"\n\ntype UploadedWorkbook = {\n buffer: ArrayBuffer\n fileName: string\n identity: string\n}\n\ntype NumberFormatOption = {\n formatString?: string\n formatType: NonNullable<XlsxCellStyleInput["numberFormat"]>["formatType"]\n icon: React.ComponentType<React.ComponentProps<"svg">>\n id?: number\n label: string\n value: string\n}\n\ntype BorderOption = {\n action: XlsxBorderAction\n icon: React.ComponentType<React.ComponentProps<"svg">>\n label: string\n}\n\ntype XlsxResolvedCellStyle = XlsxSheetData["styleById"][number]\ntype XlsxResolvedStyleGroup = Record<string, unknown>\n\ntype HorizontalAlignment = NonNullable<XlsxCellAlignmentInput["horizontal"]>\n\ntype VerticalAlignment = NonNullable<XlsxCellAlignmentInput["vertical"]>\n\ntype HorizontalAlignmentToggleValue = Extract<\n HorizontalAlignment,\n "left" | "center" | "right"\n>\n\ntype VerticalAlignmentToggleValue = Extract<\n VerticalAlignment,\n "top" | "center" | "bottom"\n>\n\ntype XlsxFontToggleValue = "bold" | "italic" | "underline" | "strikethrough"\n\ntype XlsxMergeRegion = XlsxCellRange\n\ntype XlsxBorderEdgeKey = "bottom" | "left" | "top" | "right"\n\ntype XlsxBorderAction = "all" | "outside" | "none" | XlsxBorderEdgeKey\n\ntype XlsxWorksheetWithMergeRegions = {\n mergedRegions?: unknown[]\n unmergeCells?: (range: string) => boolean\n}\n\nconst NUMBER_FORMAT_OPTIONS: NumberFormatOption[] = [\n {\n formatType: "general",\n icon: TextNumberSignGlyph,\n label: "General",\n value: "General",\n },\n {\n formatString: "0.00",\n formatType: "custom",\n icon: TextNumberSignGlyph,\n label: "Number",\n value: "Number",\n },\n {\n formatString: "$#,##0.00",\n formatType: "custom",\n icon: DollarCircleGlyph,\n label: "Currency",\n value: "Currency",\n },\n {\n formatString: "0.00%",\n formatType: "custom",\n icon: PercentGlyph,\n label: "Percent",\n value: "Percent",\n },\n {\n formatString: "m/d/yyyy",\n formatType: "custom",\n icon: Calendar03Glyph,\n label: "Date",\n value: "Date",\n },\n]\n\nconst GENERAL_NUMBER_FORMAT_VALUE = "General"\nconst BUILTIN_NUMBER_FORMAT_VALUE_PREFIX = "builtin:"\n\nfunction formatWorkbookName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "workbook.xlsx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\n}\n\nfunction normalizeHexColor(value: string, fallback = DEFAULT_TEXT_COLOR) {\n const trimmed = value.trim()\n const threeDigit = /^#?([0-9a-f]{3})$/i.exec(trimmed)\n if (threeDigit?.[1]) {\n const [red, green, blue] = threeDigit[1].split("")\n return `#${red}${red}${green}${green}${blue}${blue}`.toLowerCase()\n }\n\n const sixDigit = /^#?([0-9a-f]{6})$/i.exec(trimmed)\n if (sixDigit?.[1]) {\n return `#${sixDigit[1].toLowerCase()}`\n }\n\n return fallback\n}\n\nfunction toXlsxRgbColor(value: string) {\n return {\n colorType: "rgb" as const,\n hex: normalizeHexColor(value).slice(1).toUpperCase(),\n }\n}\n\nfunction asResolvedStyleGroup(\n value: unknown\n): XlsxResolvedStyleGroup | undefined {\n return value && typeof value === "object" && !Array.isArray(value)\n ? (value as XlsxResolvedStyleGroup)\n : undefined\n}\n\nfunction mergeResolvedCellStyle(\n base: XlsxResolvedCellStyle | null | undefined,\n overlay: XlsxResolvedCellStyle | null | undefined\n): XlsxResolvedCellStyle | null {\n if (!base && !overlay) return null\n\n const nextStyle = { ...(base ?? {}), ...(overlay ?? {}) }\n const baseFont = asResolvedStyleGroup(base?.font)\n const overlayFont = asResolvedStyleGroup(overlay?.font)\n\n if (baseFont || overlayFont) {\n nextStyle.font = overlayFont ?? baseFont\n }\n\n return nextStyle\n}\n\nfunction resolveInheritedCellStyle(\n sheet: XlsxSheetData | null,\n row: number,\n col: number\n): XlsxResolvedCellStyle | null {\n if (!sheet) return null\n\n const colStyleId = sheet.colStyleIds[col]\n const rowStyleId = sheet.rowStyleIds[row]\n const colStyle =\n colStyleId !== undefined ? sheet.styleById[colStyleId] : undefined\n const rowStyle =\n rowStyleId !== undefined ? sheet.styleById[rowStyleId] : undefined\n\n return mergeResolvedCellStyle(colStyle, rowStyle)\n}\n\nfunction getFontToggleValuesFromStyle(\n style: XlsxResolvedCellStyle | null\n): XlsxFontToggleValue[] {\n const font = asResolvedStyleGroup(style?.font)\n const values: XlsxFontToggleValue[] = []\n\n if (font?.bold === true) values.push("bold")\n if (font?.italic === true) values.push("italic")\n if (font?.underline && font.underline !== "none") values.push("underline")\n if (font?.strikethrough === true) values.push("strikethrough")\n\n return values\n}\n\nfunction getFontFamilyValue(style: XlsxResolvedCellStyle | null) {\n const font = asResolvedStyleGroup(style?.font)\n const fontName = font?.name\n\n return typeof fontName === "string" && fontName.trim()\n ? fontName.trim()\n : undefined\n}\n\nfunction getHorizontalAlignmentValue(\n style: XlsxResolvedCellStyle | null\n): HorizontalAlignmentToggleValue[] {\n const alignment = asResolvedStyleGroup(style?.alignment)\n const horizontal = alignment?.horizontal\n\n return horizontal === "left" ||\n horizontal === "center" ||\n horizontal === "right"\n ? [horizontal]\n : []\n}\n\nfunction getVerticalAlignmentValue(\n style: XlsxResolvedCellStyle | null\n): VerticalAlignmentToggleValue[] {\n const alignment = asResolvedStyleGroup(style?.alignment)\n const vertical = alignment?.vertical\n\n if (vertical === undefined || vertical === null) return ["bottom"]\n\n return vertical === "top" || vertical === "center" || vertical === "bottom"\n ? [vertical]\n : []\n}\n\nfunction getNumberFormatValue(style: XlsxResolvedCellStyle | null) {\n const numberFormat = asResolvedStyleGroup(style?.numberFormat)\n\n if (!numberFormat) return GENERAL_NUMBER_FORMAT_VALUE\n\n const formatType = numberFormat.formatType\n const formatString =\n typeof numberFormat.formatString === "string"\n ? numberFormat.formatString.trim()\n : ""\n const id = getNumericValue(numberFormat.id)\n\n if (formatString) {\n const matchingOption = NUMBER_FORMAT_OPTIONS.find(\n (option) => option.formatString === formatString\n )\n\n return matchingOption?.value ?? formatString\n }\n if (formatType === "builtin" && id !== undefined) {\n const matchingOption = NUMBER_FORMAT_OPTIONS.find(\n (option) => option.id === id\n )\n\n if (matchingOption) return matchingOption.value\n\n return `${BUILTIN_NUMBER_FORMAT_VALUE_PREFIX}${id}`\n }\n if (formatType === "general") return GENERAL_NUMBER_FORMAT_VALUE\n\n return GENERAL_NUMBER_FORMAT_VALUE\n}\n\nfunction getNumberFormatLabel(value: string) {\n if (value === GENERAL_NUMBER_FORMAT_VALUE) return "General"\n\n const matchingOption = NUMBER_FORMAT_OPTIONS.find(\n (option) => option.value === value\n )\n if (matchingOption) return matchingOption.label\n\n if (value.startsWith(BUILTIN_NUMBER_FORMAT_VALUE_PREFIX)) {\n return `Builtin ${value.slice(BUILTIN_NUMBER_FORMAT_VALUE_PREFIX.length)}`\n }\n\n return value\n}\n\nfunction getNumberFormatIcon(value: string) {\n return (\n NUMBER_FORMAT_OPTIONS.find((option) => option.value === value)?.icon ??\n TextNumberSignGlyph\n )\n}\n\nfunction createNumberFormatStyle(value: string): XlsxCellStyleInput {\n const matchingOption = NUMBER_FORMAT_OPTIONS.find(\n (option) => option.value === value\n )\n\n if (matchingOption) {\n return {\n numberFormat: {\n formatString: matchingOption.formatString,\n formatType: matchingOption.formatType,\n id: matchingOption.id,\n },\n }\n }\n\n if (value.startsWith(BUILTIN_NUMBER_FORMAT_VALUE_PREFIX)) {\n const id = Number(value.slice(BUILTIN_NUMBER_FORMAT_VALUE_PREFIX.length))\n\n if (Number.isFinite(id)) {\n return {\n numberFormat: {\n formatType: "builtin",\n id: Math.max(0, Math.trunc(id)),\n },\n }\n }\n }\n\n return {\n numberFormat: {\n formatString: value,\n formatType: "custom",\n },\n }\n}\n\nfunction normalizeCellRange(range: XlsxCellRange): XlsxCellRange {\n return {\n start: {\n row: Math.min(range.start.row, range.end.row),\n col: Math.min(range.start.col, range.end.col),\n },\n end: {\n row: Math.max(range.start.row, range.end.row),\n col: Math.max(range.start.col, range.end.col),\n },\n }\n}\n\nfunction getNumericValue(value: unknown) {\n return typeof value === "number" && Number.isFinite(value)\n ? Math.max(0, Math.trunc(value))\n : undefined\n}\n\nfunction getWorksheetMergeRegions(\n worksheet: XlsxWorksheetWithMergeRegions | null\n): XlsxMergeRegion[] {\n if (!Array.isArray(worksheet?.mergedRegions)) return []\n\n return worksheet.mergedRegions.flatMap((entry) => {\n if (!entry || typeof entry !== "object") return []\n\n const region = entry as Record<string, unknown>\n const start = asResolvedStyleGroup(region.start)\n const end = asResolvedStyleGroup(region.end)\n const startRow = getNumericValue(region.startRow ?? start?.row)\n const startCol = getNumericValue(region.startCol ?? start?.col)\n const endRow = getNumericValue(region.endRow ?? end?.row)\n const endCol = getNumericValue(region.endCol ?? end?.col)\n\n if (\n startRow === undefined ||\n startCol === undefined ||\n endRow === undefined ||\n endCol === undefined\n ) {\n return []\n }\n\n return [\n normalizeCellRange({\n start: { row: startRow, col: startCol },\n end: { row: endRow, col: endCol },\n }),\n ]\n })\n}\n\nfunction rangesIntersect(\n firstRange: XlsxCellRange,\n secondRange: XlsxCellRange\n) {\n const first = normalizeCellRange(firstRange)\n const second = normalizeCellRange(secondRange)\n\n return (\n first.start.row <= second.end.row &&\n first.end.row >= second.start.row &&\n first.start.col <= second.end.col &&\n first.end.col >= second.start.col\n )\n}\n\nfunction isSingleCellRange(range: XlsxCellRange) {\n const normalizedRange = normalizeCellRange(range)\n\n return (\n normalizedRange.start.row === normalizedRange.end.row &&\n normalizedRange.start.col === normalizedRange.end.col\n )\n}\n\nfunction getCellColumnLabel(col: number) {\n let label = ""\n let value = col\n\n do {\n label = String.fromCharCode(65 + (value % 26)) + label\n value = Math.floor(value / 26) - 1\n } while (value >= 0)\n\n return label\n}\n\nfunction cellAddressToA1(cell: XlsxCellRange["start"]) {\n return `${getCellColumnLabel(cell.col)}${cell.row + 1}`\n}\n\nfunction rangeToA1(range: XlsxCellRange) {\n const normalizedRange = normalizeCellRange(range)\n\n return `${cellAddressToA1(normalizedRange.start)}:${cellAddressToA1(\n normalizedRange.end\n )}`\n}\n\nfunction getRangeKey(range: XlsxCellRange) {\n const normalizedRange = normalizeCellRange(range)\n\n return `${normalizedRange.start.row}:${normalizedRange.start.col}:${normalizedRange.end.row}:${normalizedRange.end.col}`\n}\n\nfunction createBorderEdge(\n color = DEFAULT_BORDER_COLOR\n): XlsxCellBorderEdgeInput {\n return {\n color: toXlsxRgbColor(color),\n style: "thin",\n }\n}\n\nfunction createBorderPatch(\n entries: Partial<Record<XlsxBorderEdgeKey, XlsxCellBorderEdgeInput>>\n): XlsxCellStyleInput {\n return {\n border: entries,\n }\n}\n\nfunction createNoBorderPatch(): XlsxCellStyleInput {\n return {\n border: {\n bottom: { style: "none" },\n left: { style: "none" },\n right: { style: "none" },\n top: { style: "none" },\n },\n }\n}\n\nfunction createBorderOptions(): BorderOption[] {\n return [\n {\n action: "bottom",\n icon: BorderBottom01Glyph,\n label: "Bottom border",\n },\n {\n action: "left",\n icon: BorderLeft01Glyph,\n label: "Left border",\n },\n {\n action: "top",\n icon: BorderTop01Glyph,\n label: "Top border",\n },\n {\n action: "right",\n icon: BorderRight01Glyph,\n label: "Right border",\n },\n {\n action: "all",\n icon: BorderAll01Glyph,\n label: "All borders",\n },\n {\n action: "outside",\n icon: BorderAll01Glyph,\n label: "Outside border",\n },\n {\n action: "none",\n icon: BorderNone01Glyph,\n label: "No border",\n },\n ]\n}\n\nfunction getBorderEdgeRange(\n range: XlsxCellRange,\n edgeKey: XlsxBorderEdgeKey\n): XlsxCellRange {\n const normalizedRange = normalizeCellRange(range)\n\n if (edgeKey === "top") {\n return {\n start: normalizedRange.start,\n end: { row: normalizedRange.start.row, col: normalizedRange.end.col },\n }\n }\n\n if (edgeKey === "bottom") {\n return {\n start: { row: normalizedRange.end.row, col: normalizedRange.start.col },\n end: normalizedRange.end,\n }\n }\n\n if (edgeKey === "left") {\n return {\n start: normalizedRange.start,\n end: { row: normalizedRange.end.row, col: normalizedRange.start.col },\n }\n }\n\n return {\n start: { row: normalizedRange.start.row, col: normalizedRange.end.col },\n end: normalizedRange.end,\n }\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction EditorLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 w-full min-w-full place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction ToolbarIconButton({\n active,\n children,\n label,\n ...props\n}: React.ComponentProps<typeof Button> & {\n active?: boolean\n label: string\n}) {\n return (\n <ToolbarTooltip label={label}>\n <Button\n type="button"\n variant={active ? "secondary" : "ghost"}\n size="icon-sm"\n aria-label={label}\n data-pressed={active ? "" : undefined}\n {...props}\n >\n {children}\n </Button>\n </ToolbarTooltip>\n )\n}\n\nfunction ToolbarSeparator() {\n return <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n}\n\nfunction StyleDropdownItem({\n children,\n icon,\n onClick,\n}: {\n children: React.ReactNode\n icon: React.ComponentType<React.ComponentProps<"svg">>\n onClick: () => void\n}) {\n const IconComponent = icon\n return (\n <DropdownMenuItem onClick={onClick}>\n <IconComponent className="size-4" />\n {children}\n </DropdownMenuItem>\n )\n}\n\nfunction MergeCellsMenu({\n canMerge,\n canMergeAcross,\n canUnmerge,\n disabled,\n isMerged,\n onMergeAcross,\n onMergeAndCenter,\n onMergeCells,\n onUnmergeCells,\n}: {\n canMerge: boolean\n canMergeAcross: boolean\n canUnmerge: boolean\n disabled: boolean\n isMerged: boolean\n onMergeAcross: () => void\n onMergeAndCenter: () => void\n onMergeCells: () => void\n onUnmergeCells: () => void\n}) {\n return (\n <DropdownMenu>\n <div\n className={cn(\n "inline-flex shrink-0 overflow-hidden rounded-lg border border-transparent"\n )}\n >\n <ToolbarTooltip\n label={isMerged ? "Unmerge cells from the menu" : "Merge & Center"}\n >\n <Button\n type="button"\n variant={isMerged ? "secondary" : "ghost"}\n size="sm"\n aria-label="Merge & Center"\n className="h-7 rounded-r-none border-0 px-2.5 before:rounded-r-none"\n data-pressed={isMerged ? "" : undefined}\n disabled={disabled || !canMerge}\n onClick={onMergeAndCenter}\n >\n <IconPlaceholder\n lucide="TableCellsMerge"\n tabler="IconArrowMerge"\n hugeicons="PathfinderMergeIcon"\n phosphor="ArrowsMergeIcon"\n remixicon="RiMergeCellsVertical"\n className="size-4"\n />\n <span className="hidden text-xs font-medium lg:inline">\n Merge & Center\n </span>\n </Button>\n </ToolbarTooltip>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant={isMerged ? "secondary" : "ghost"}\n size="icon-sm"\n aria-label="Merge cells options"\n className="h-7 w-6 rounded-l-none border-0 px-0 before:rounded-l-none"\n data-pressed={isMerged ? "" : undefined}\n disabled={disabled}\n >\n <IconPlaceholder\n lucide="ChevronDown"\n tabler="IconChevronDown"\n hugeicons="ChevronDownIcon"\n phosphor="CaretDownIcon"\n remixicon="RiArrowDownSLine"\n className="size-3.5 opacity-100"\n />\n </Button>\n </DropdownMenuTrigger>\n </div>\n <DropdownMenuContent\n align="start"\n className={cn("w-56", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <DropdownMenuItem disabled={!canMerge} onClick={onMergeAndCenter}>\n <IconPlaceholder\n lucide="TableCellsMerge"\n tabler="IconArrowMerge"\n hugeicons="PathfinderMergeIcon"\n phosphor="ArrowsMergeIcon"\n remixicon="RiMergeCellsVertical"\n className="size-4"\n />\n Merge & Center\n </DropdownMenuItem>\n <DropdownMenuItem disabled={!canMergeAcross} onClick={onMergeAcross}>\n <IconPlaceholder\n lucide="TableRowsSplit"\n tabler="IconArrowsSplit"\n hugeicons="TableRowsSplitIcon"\n phosphor="ArrowsSplitIcon"\n remixicon="RiSplitCellsVertical"\n className="size-4"\n />\n Merge Across\n </DropdownMenuItem>\n <DropdownMenuItem disabled={!canMerge} onClick={onMergeCells}>\n <IconPlaceholder\n lucide="Grid3x3"\n tabler="IconGrid4x4"\n hugeicons="CellsIcon"\n phosphor="GridNineIcon"\n remixicon="RiMergeCellsHorizontal"\n className="size-4"\n />\n Merge Cells\n </DropdownMenuItem>\n <DropdownMenuSeparator />\n <DropdownMenuItem disabled={!canUnmerge} onClick={onUnmergeCells}>\n <IconPlaceholder\n lucide="Grid2x2X"\n tabler="IconTableMinus"\n hugeicons="Grid2X2XIcon"\n phosphor="SelectionSlashIcon"\n remixicon="RiSplitCellsHorizontal"\n className="size-4"\n />\n Unmerge Cells\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction NumberFormatSelect({\n disabled,\n onApplyStyle,\n value,\n}: {\n disabled: boolean\n onApplyStyle: (style: XlsxCellStyleInput) => void\n value: string\n}) {\n const hasMatchingOption = NUMBER_FORMAT_OPTIONS.some(\n (option) => option.value === value\n )\n const currentLabel = getNumberFormatLabel(value)\n const currentIcon = React.createElement(getNumberFormatIcon(value), {\n className: "size-4",\n })\n\n return (\n <Select\n value={value}\n onValueChange={(nextValue) => {\n if (!nextValue) return\n onApplyStyle(createNumberFormatStyle(nextValue))\n }}\n disabled={disabled}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[132px] min-w-[132px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Number format"\n >\n {currentIcon}\n <SelectValue placeholder="General" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {NUMBER_FORMAT_OPTIONS.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n <span className="flex min-w-0 items-center gap-2">\n <option.icon className="size-4" />\n <span className="truncate">{option.label}</span>\n </span>\n </SelectItem>\n ))}\n {!hasMatchingOption && value !== GENERAL_NUMBER_FORMAT_VALUE ? (\n <SelectItem value={value}>\n <span className="flex min-w-0 items-center gap-2">\n {currentIcon}\n <span className="truncate">{currentLabel}</span>\n </span>\n </SelectItem>\n ) : null}\n </SelectContent>\n </Select>\n )\n}\n\nfunction BorderMenu({\n borderColor,\n disabled,\n onApplyBorder,\n onBorderColorChange,\n}: {\n borderColor: string\n disabled: boolean\n onApplyBorder: (action: XlsxBorderAction) => void\n onBorderColorChange: (color: string) => void\n}) {\n const borderOptions = React.useMemo(() => createBorderOptions(), [])\n const edgeBorderOptions = borderOptions.filter(\n (option) =>\n option.action === "bottom" ||\n option.action === "left" ||\n option.action === "top" ||\n option.action === "right"\n )\n const groupedBorderOptions = borderOptions.filter(\n (option) =>\n option.action === "all" ||\n option.action === "outside" ||\n option.action === "none"\n )\n\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={disabled}\n aria-label="Cell borders"\n className="relative"\n >\n <IconPlaceholder\n lucide="Grid2x2"\n tabler="IconBorderAll"\n hugeicons="BorderAll01Icon"\n phosphor="GridFourIcon"\n remixicon="RiGridLine"\n className="size-4"\n />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: borderColor }}\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align="start"\n className={cn("w-48", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n {edgeBorderOptions.map((option) => (\n <StyleDropdownItem\n key={option.label}\n icon={option.icon}\n onClick={() => onApplyBorder(option.action)}\n >\n {option.label}\n </StyleDropdownItem>\n ))}\n <DropdownMenuSeparator />\n <DropdownMenuGroup>\n {groupedBorderOptions.map((option) => (\n <StyleDropdownItem\n key={option.label}\n icon={option.icon}\n onClick={() => onApplyBorder(option.action)}\n >\n {option.label}\n </StyleDropdownItem>\n ))}\n </DropdownMenuGroup>\n <DropdownMenuSeparator />\n <DropdownMenuSub>\n <DropdownMenuSubTrigger>\n <IconPlaceholder\n lucide="Baseline"\n tabler="IconTextColor"\n hugeicons="TextColorIcon"\n phosphor="TextAaIcon"\n remixicon="RiFontColor"\n className="size-4 text-muted-foreground"\n />\n Border color\n <span\n className="h-3 w-5 rounded-full border border-border"\n style={{ backgroundColor: borderColor }}\n />\n </DropdownMenuSubTrigger>\n <DropdownMenuSubContent\n className={cn("w-64 p-2", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <ColorPickerPanel\n label="Border color"\n color={borderColor}\n onChange={(color) =>\n onBorderColorChange(normalizeHexColor(color))\n }\n />\n </DropdownMenuSubContent>\n </DropdownMenuSub>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction AlignmentMoreMenu({\n disabled,\n onApplyStyle,\n}: {\n disabled: boolean\n onApplyStyle: (style: XlsxCellStyleInput) => void\n}) {\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={disabled}\n aria-label="More alignment"\n >\n <IconPlaceholder\n lucide="Ellipsis"\n tabler="IconDots"\n hugeicons="MoreHorizontalIcon"\n phosphor="DotsThreeIcon"\n remixicon="RiMoreLine"\n className="size-4"\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align="start"\n className={cn("w-48", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <StyleDropdownItem\n icon={TextWrapGlyph}\n onClick={() => onApplyStyle({ alignment: { wrapText: false } })}\n >\n Do not wrap\n </StyleDropdownItem>\n <StyleDropdownItem\n icon={TextWrapGlyph}\n onClick={() => onApplyStyle({ alignment: { shrinkToFit: true } })}\n >\n Shrink to fit\n </StyleDropdownItem>\n <StyleDropdownItem\n icon={TextWrapGlyph}\n onClick={() => onApplyStyle({ alignment: { shrinkToFit: false } })}\n >\n Do not shrink\n </StyleDropdownItem>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction EditorFileActionsMenu({\n canExport,\n exportXlsx,\n onUploadClick,\n}: {\n canExport: boolean\n exportXlsx: () => void\n onUploadClick: () => void\n}) {\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Open workbook actions"\n >\n <IconPlaceholder\n lucide="Ellipsis"\n tabler="IconDots"\n hugeicons="MoreHorizontalIcon"\n phosphor="DotsThreeIcon"\n remixicon="RiMoreLine"\n className="size-4"\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align="end"\n className={cn("w-40", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <DropdownMenuItem disabled={!canExport} onClick={exportXlsx}>\n <IconPlaceholder\n lucide="Download"\n tabler="IconDownload"\n hugeicons="Download01Icon"\n phosphor="DownloadSimpleIcon"\n remixicon="RiDownload2Line"\n className="size-4"\n />\n Download\n </DropdownMenuItem>\n <DropdownMenuItem onClick={onUploadClick}>\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction EditorToolbar({\n isDark,\n onIsDarkChange,\n onUploadClick,\n showNightRenderToggle,\n workbookIdentity,\n}: {\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n showNightRenderToggle: boolean\n workbookIdentity: string\n}) {\n const {\n activeSheet,\n activeSheetIndex,\n canExport,\n exportXlsx,\n getActiveWorksheet,\n revision,\n setActiveSheetIndex,\n sheets,\n } = useXlsxViewer()\n const { activeCell, activeCellAddress, selectRange, selection } =\n useXlsxViewerSelection()\n const {\n addSheet,\n canRedo,\n canUndo,\n mergeSelection,\n pasteStructuredClipboardData,\n readOnly,\n redo,\n removeActiveSheet,\n selectedFormula,\n selectedValue,\n setCellStyle,\n setCellFormula,\n setCellValue,\n setRangeStyle,\n setSelectedCellStyle,\n undo,\n unmergeSelection,\n } = useXlsxViewerEditing()\n const { canZoomIn, canZoomOut, setZoomScale, zoomIn, zoomOut, zoomScale } =\n useXlsxViewerZoom()\n const [formulaDraft, setFormulaDraft] = React.useState("")\n const [formulaFocused, setFormulaFocused] = React.useState(false)\n const [fontFamily, setFontFamily] = React.useState(DEFAULT_FONT_FAMILY)\n const [fontSize, setFontSize] = React.useState(11)\n const [textColor, setTextColor] = React.useState(DEFAULT_TEXT_COLOR)\n const [fillColor, setFillColor] = React.useState(DEFAULT_FILL_COLOR)\n const [borderColor, setBorderColor] = React.useState(DEFAULT_BORDER_COLOR)\n const [appliedMergeRegions, setAppliedMergeRegions] = React.useState<\n XlsxMergeRegion[]\n >([])\n const lastStyleTargetRef = React.useRef<{\n range: XlsxCellRange\n sheetIndex: number\n workbookIdentity: string\n } | null>(null)\n const formulaEditCellRef = React.useRef<typeof activeCell>(null)\n const formulaInitialValueRef = React.useRef("")\n const hasWorkbook = sheets.length > 0\n const hasSelection = Boolean(selection)\n const hasActiveCell = Boolean(activeCell)\n const canStyleSelection = (hasSelection || hasActiveCell) && !readOnly\n const activeRange = React.useMemo<XlsxCellRange | null>(() => {\n if (selection) return normalizeCellRange(selection)\n if (!activeCell) return null\n\n return {\n start: activeCell,\n end: activeCell,\n }\n }, [activeCell, selection])\n\n React.useEffect(() => {\n if (!activeRange) return\n\n lastStyleTargetRef.current = {\n range: activeRange,\n sheetIndex: activeSheetIndex,\n workbookIdentity,\n }\n }, [activeRange, activeSheetIndex, workbookIdentity])\n const worksheetMergeRegions = React.useMemo(() => {\n void revision\n\n return getWorksheetMergeRegions(\n getActiveWorksheet() as XlsxWorksheetWithMergeRegions | null\n )\n }, [getActiveWorksheet, revision])\n const mergeRegions = React.useMemo(\n () => [...worksheetMergeRegions, ...appliedMergeRegions],\n [appliedMergeRegions, worksheetMergeRegions]\n )\n const selectionIntersectsMerge = Boolean(\n activeRange &&\n mergeRegions.some((mergeRegion) =>\n rangesIntersect(activeRange, mergeRegion)\n )\n )\n\n React.useEffect(() => {\n if (\n appliedMergeRegions.length === 0 ||\n worksheetMergeRegions.length === 0\n ) {\n return\n }\n\n setAppliedMergeRegions((currentRegions) =>\n currentRegions.filter(\n (currentRegion) =>\n !worksheetMergeRegions.some((worksheetRegion) =>\n rangesIntersect(currentRegion, worksheetRegion)\n )\n )\n )\n }, [appliedMergeRegions.length, worksheetMergeRegions])\n\n React.useEffect(() => {\n setAppliedMergeRegions([])\n }, [activeSheetIndex])\n const selectionIsSingleCell = activeRange\n ? isSingleCellRange(activeRange)\n : true\n const selectionSpansMultipleColumns = activeRange\n ? activeRange.start.col !== activeRange.end.col\n : false\n const canMergeSelectedCells = Boolean(\n selection &&\n !readOnly &&\n !selectionIntersectsMerge &&\n !selectionIsSingleCell\n )\n const canMergeAcross = Boolean(\n selection &&\n !readOnly &&\n !selectionIntersectsMerge &&\n selectionSpansMultipleColumns\n )\n const canUnmergeSelectedCells = Boolean(\n selection && !readOnly && selectionIntersectsMerge\n )\n const currentZoom = Math.round(zoomScale)\n const selectedCellInputValue = selectedFormula || selectedValue\n\n React.useEffect(() => {\n if (formulaFocused) return\n setFormulaDraft(selectedCellInputValue)\n }, [formulaFocused, selectedCellInputValue, activeCellAddress])\n\n const activeCellStyle = React.useMemo(() => {\n // Worksheet style objects are mutable; revision invalidates this read after edits.\n void revision\n\n if (!activeCell) return null\n\n const worksheet = getActiveWorksheet()\n const inheritedStyle = resolveInheritedCellStyle(\n activeSheet,\n activeCell.row,\n activeCell.col\n )\n const cellStyle = worksheet?.getCellStyleAt(\n activeCell.row,\n activeCell.col\n ) as XlsxResolvedCellStyle | null | undefined\n\n return mergeResolvedCellStyle(inheritedStyle, cellStyle)\n }, [activeCell, activeSheet, getActiveWorksheet, revision])\n const fontToggleValues = React.useMemo(\n () => getFontToggleValuesFromStyle(activeCellStyle),\n [activeCellStyle]\n )\n const fontFamilyValue = getFontFamilyValue(activeCellStyle) ?? fontFamily\n const horizontalAlignmentValue = React.useMemo(\n () => getHorizontalAlignmentValue(activeCellStyle),\n [activeCellStyle]\n )\n const verticalAlignmentValue = React.useMemo(\n () => getVerticalAlignmentValue(activeCellStyle),\n [activeCellStyle]\n )\n const numberFormatValue = React.useMemo(\n () => getNumberFormatValue(activeCellStyle),\n [activeCellStyle]\n )\n\n const commitFormula = React.useCallback(() => {\n const targetCell = formulaEditCellRef.current ?? activeCell\n if (!targetCell) return\n if (formulaDraft === formulaInitialValueRef.current) return\n\n if (formulaDraft.trim().startsWith("=")) {\n setCellFormula(targetCell, formulaDraft)\n } else {\n setCellValue(targetCell, formulaDraft)\n }\n formulaInitialValueRef.current = formulaDraft\n }, [activeCell, formulaDraft, setCellFormula, setCellValue])\n\n const applyStyle = React.useCallback(\n (style: XlsxCellStyleInput) => {\n const applyRangeStyle = (range: XlsxCellRange) => {\n const normalizedRange = normalizeCellRange(range)\n const targetRanges = [\n normalizedRange,\n ...mergeRegions.filter((mergeRegion) =>\n rangesIntersect(normalizedRange, mergeRegion)\n ),\n ]\n const uniqueTargetRanges = new Map<string, XlsxCellRange>()\n\n targetRanges.forEach((targetRange) => {\n const normalizedTargetRange = normalizeCellRange(targetRange)\n uniqueTargetRanges.set(\n getRangeKey(normalizedTargetRange),\n normalizedTargetRange\n )\n })\n\n uniqueTargetRanges.forEach((targetRange) => {\n setRangeStyle(targetRange, style)\n })\n }\n\n if (selection) {\n const normalizedSelection = normalizeCellRange(selection)\n\n if (!isSingleCellRange(normalizedSelection)) {\n applyRangeStyle(normalizedSelection)\n return true\n }\n\n if (activeCell) {\n setSelectedCellStyle(style)\n return true\n }\n\n setCellStyle(normalizedSelection.start, style)\n return true\n }\n\n if (activeCell) {\n setSelectedCellStyle(style)\n return true\n }\n\n const fallbackTarget = lastStyleTargetRef.current\n const targetRange =\n fallbackTarget?.sheetIndex === activeSheetIndex &&\n fallbackTarget.workbookIdentity === workbookIdentity\n ? fallbackTarget.range\n : null\n\n if (!targetRange) return false\n\n if (isSingleCellRange(targetRange)) {\n setCellStyle(normalizeCellRange(targetRange).start, style)\n return true\n }\n\n applyRangeStyle(targetRange)\n return true\n },\n [\n activeCell,\n activeSheetIndex,\n mergeRegions,\n selection,\n setCellStyle,\n setRangeStyle,\n setSelectedCellStyle,\n workbookIdentity,\n ]\n )\n\n const applyBorderAction = React.useCallback(\n (action: XlsxBorderAction) => {\n if (!activeRange) return\n\n const normalizedRange = normalizeCellRange(activeRange)\n const edge = createBorderEdge(borderColor)\n const allBorderPatch = createBorderPatch({\n bottom: edge,\n left: edge,\n right: edge,\n top: edge,\n })\n\n if (action === "all") {\n setRangeStyle(normalizedRange, allBorderPatch)\n return\n }\n\n if (action === "none") {\n setRangeStyle(normalizedRange, createNoBorderPatch())\n return\n }\n\n if (action === "outside") {\n if (isSingleCellRange(normalizedRange)) {\n setCellStyle(normalizedRange.start, allBorderPatch)\n return\n }\n\n const outsideEdgeKeys: XlsxBorderEdgeKey[] = [\n "top",\n "bottom",\n "left",\n "right",\n ]\n\n outsideEdgeKeys.forEach((edgeKey) => {\n setRangeStyle(\n getBorderEdgeRange(normalizedRange, edgeKey),\n createBorderPatch({ [edgeKey]: edge })\n )\n })\n return\n }\n\n setRangeStyle(\n getBorderEdgeRange(normalizedRange, action),\n createBorderPatch({ [action]: edge })\n )\n },\n [activeRange, borderColor, setCellStyle, setRangeStyle]\n )\n\n const applyHorizontalAlignment = React.useCallback(\n (horizontal: HorizontalAlignmentToggleValue | undefined) => {\n if (!horizontal) return\n\n applyStyle({ alignment: { horizontal } })\n },\n [applyStyle]\n )\n\n const applyVerticalAlignment = React.useCallback(\n (vertical: VerticalAlignmentToggleValue | undefined) => {\n if (!vertical) return\n\n applyStyle({ alignment: { vertical } })\n },\n [applyStyle]\n )\n\n const mergeSelectedCells = React.useCallback(() => {\n if (!canMergeSelectedCells || !selection) return\n\n setAppliedMergeRegions([normalizeCellRange(selection)])\n mergeSelection()\n }, [canMergeSelectedCells, mergeSelection, selection])\n\n const mergeAcrossSelectedCells = React.useCallback(() => {\n if (!activeCell || !canMergeAcross || !selection) return\n\n const normalizedRange = normalizeCellRange(selection)\n const worksheet = getActiveWorksheet()\n if (!worksheet) return\n\n const formula = worksheet.getFormulaAt(activeCell.row, activeCell.col)\n const rawValue = worksheet.getCellAt(activeCell.row, activeCell.col).toJs()\n const colSpan = normalizedRange.end.col - normalizedRange.start.col + 1\n const rowSpan = normalizedRange.end.row - normalizedRange.start.row + 1\n const merges = Array.from({ length: rowSpan }, (_, rowOffset) => ({\n colOffset: normalizedRange.start.col - activeCell.col,\n colSpan,\n rowOffset: normalizedRange.start.row + rowOffset - activeCell.row,\n rowSpan: 1,\n }))\n const mergeRegionsByRow = Array.from({ length: rowSpan }, (_, rowOffset) =>\n normalizeCellRange({\n start: {\n col: normalizedRange.start.col,\n row: normalizedRange.start.row + rowOffset,\n },\n end: {\n col: normalizedRange.end.col,\n row: normalizedRange.start.row + rowOffset,\n },\n })\n )\n\n const didPaste = pasteStructuredClipboardData(\n JSON.stringify({\n cells: [\n formula\n ? { colOffset: 0, formula, rowOffset: 0 }\n : { colOffset: 0, rowOffset: 0, value: rawValue ?? "" },\n ],\n cols: colSpan,\n merges,\n rows: rowSpan,\n })\n )\n\n if (!didPaste) return\n\n setAppliedMergeRegions(mergeRegionsByRow)\n selectRange(normalizedRange)\n }, [\n activeCell,\n canMergeAcross,\n getActiveWorksheet,\n pasteStructuredClipboardData,\n selectRange,\n selection,\n ])\n\n const mergeAndCenterSelectedCells = React.useCallback(() => {\n if (!canMergeSelectedCells || !selection) return\n\n setAppliedMergeRegions([normalizeCellRange(selection)])\n setRangeStyle(selection, { alignment: { horizontal: "center" } })\n mergeSelection()\n }, [canMergeSelectedCells, mergeSelection, selection, setRangeStyle])\n\n const unmergeSelectedCells = React.useCallback(() => {\n if (!canUnmergeSelectedCells || !activeRange) return\n\n const worksheet =\n getActiveWorksheet() as XlsxWorksheetWithMergeRegions | null\n if (!worksheet?.unmergeCells) return\n\n const normalizedRange = normalizeCellRange(activeRange)\n const uniqueMergeRegions = new Map<string, XlsxMergeRegion>()\n\n ;[...worksheetMergeRegions, ...appliedMergeRegions].forEach(\n (mergeRegion) => {\n if (!rangesIntersect(normalizedRange, mergeRegion)) return\n\n uniqueMergeRegions.set(getRangeKey(mergeRegion), mergeRegion)\n }\n )\n\n let didUnmerge = false\n\n uniqueMergeRegions.forEach((mergeRegion) => {\n didUnmerge =\n worksheet.unmergeCells?.(rangeToA1(mergeRegion)) || didUnmerge\n })\n\n if (!didUnmerge) {\n unmergeSelection()\n return\n }\n\n setAppliedMergeRegions([])\n setRangeStyle(normalizedRange, {})\n selectRange(normalizedRange)\n }, [\n activeRange,\n appliedMergeRegions,\n canUnmergeSelectedCells,\n getActiveWorksheet,\n selectRange,\n setRangeStyle,\n unmergeSelection,\n worksheetMergeRegions,\n ])\n\n const applyFontToggleValues = React.useCallback(\n (nextValues: XlsxFontToggleValue[]) => {\n const previousValues = fontToggleValues\n const changedValue =\n nextValues.find((value) => !previousValues.includes(value)) ??\n previousValues.find((value) => !nextValues.includes(value))\n\n if (!changedValue) return\n\n const isPressed = nextValues.includes(changedValue)\n\n if (changedValue === "bold") {\n applyStyle({ font: { bold: isPressed } })\n } else if (changedValue === "italic") {\n applyStyle({ font: { italic: isPressed } })\n } else if (changedValue === "underline") {\n applyStyle({ font: { underline: isPressed ? "single" : "none" } })\n } else if (changedValue === "strikethrough") {\n applyStyle({ font: { strikethrough: isPressed } })\n }\n },\n [applyStyle, fontToggleValues]\n )\n\n return (\n <div className="border-b bg-background">\n <div className="flex min-h-11 items-center justify-between gap-3 border-b px-3">\n <div className="min-w-0 flex-1" />\n <TooltipProvider>\n <div className="flex shrink-0 items-center gap-1">\n {showNightRenderToggle ? (\n <>\n <ToolbarTooltip\n label={isDark ? "Use light workbook" : "Use dark workbook"}\n >\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label={\n isDark ? "Use light workbook" : "Use dark workbook"\n }\n onClick={() => onIsDarkChange(!isDark)}\n >\n {isDark ? (\n <Sun03Glyph className="size-4" />\n ) : (\n <Moon02Glyph className="size-4" />\n )}\n </Button>\n </ToolbarTooltip>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <EditorFileActionsMenu\n canExport={canExport}\n exportXlsx={exportXlsx}\n onUploadClick={onUploadClick}\n />\n </div>\n </TooltipProvider>\n </div>\n <TooltipProvider>\n <div className="flex min-h-12 flex-wrap items-center gap-2 border-b bg-background px-3 py-2">\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarTooltip label="Undo">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Undo"\n disabled={!canUndo || readOnly}\n onClick={undo}\n >\n <IconPlaceholder\n lucide="Undo2"\n tabler="IconArrowBackUp"\n hugeicons="Undo02Icon"\n phosphor="ArrowUUpLeftIcon"\n remixicon="RiArrowGoBackLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Redo">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Redo"\n disabled={!canRedo || readOnly}\n onClick={redo}\n >\n <IconPlaceholder\n lucide="Redo2"\n tabler="IconArrowForwardUp"\n hugeicons="Redo02Icon"\n phosphor="ArrowUUpRightIcon"\n remixicon="RiArrowGoForwardLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <Select\n value={fontFamilyValue}\n onValueChange={(value) => {\n if (!value) return\n\n if (applyStyle({ font: { name: value } })) {\n setFontFamily(value)\n }\n }}\n disabled={!canStyleSelection}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[132px] min-w-[132px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Font family"\n >\n <SelectValue placeholder="Font">{fontFamilyValue}</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {FONT_FAMILIES.map((option) => (\n <SelectItem key={option} value={option}>\n <span style={{ fontFamily: option }}>{option}</span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <Select\n value={String(fontSize)}\n onValueChange={(value) => {\n const nextFontSize = Number(value)\n if (!Number.isFinite(nextFontSize)) return\n\n setFontSize(nextFontSize)\n applyStyle({ font: { size: nextFontSize } })\n }}\n disabled={!canStyleSelection}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[78px] min-w-[78px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Font size"\n >\n <SelectValue placeholder="Size" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {FONT_SIZE_OPTIONS.map((size) => (\n <SelectItem key={size} value={String(size)}>\n {size} pt\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <ToolbarSeparator />\n <ToggleGroup\n className="shrink-0"\n disabled={!canStyleSelection}\n multiple\n spacing="default"\n value={fontToggleValues}\n onValueChange={(value) =>\n applyFontToggleValues(value as XlsxFontToggleValue[])\n }\n >\n <ToolbarTooltip label="Bold">\n <ToggleGroupItem aria-label="Bold" size="sm" value="bold">\n <IconPlaceholder\n lucide="Bold"\n tabler="IconBold"\n hugeicons="TextBoldIcon"\n phosphor="TextBIcon"\n remixicon="RiBold"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Italic">\n <ToggleGroupItem aria-label="Italic" size="sm" value="italic">\n <IconPlaceholder\n lucide="Italic"\n tabler="IconItalic"\n hugeicons="TextItalicIcon"\n phosphor="TextItalicIcon"\n remixicon="RiItalic"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Underline">\n <ToggleGroupItem\n aria-label="Underline"\n size="sm"\n value="underline"\n >\n <IconPlaceholder\n lucide="Underline"\n tabler="IconUnderline"\n hugeicons="TextUnderlineIcon"\n phosphor="TextUnderlineIcon"\n remixicon="RiUnderline"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Strikethrough">\n <ToggleGroupItem\n aria-label="Strikethrough"\n size="sm"\n value="strikethrough"\n >\n <IconPlaceholder\n lucide="Strikethrough"\n tabler="IconStrikethrough"\n hugeicons="TextStrikethroughIcon"\n phosphor="TextStrikethroughIcon"\n remixicon="RiStrikethrough"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n </ToggleGroup>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <ColorPicker\n label="Text color"\n icon={TextColorGlyph}\n color={textColor}\n disabled={!canStyleSelection}\n onChange={(color) => {\n const nextColor = normalizeHexColor(color)\n setTextColor(nextColor)\n applyStyle({ font: { color: toXlsxRgbColor(nextColor) } })\n }}\n />\n <ColorPicker\n label="Fill color"\n icon={PaintBucketGlyph}\n color={fillColor}\n disabled={!canStyleSelection}\n onChange={(color) => {\n const nextColor = normalizeHexColor(color, DEFAULT_FILL_COLOR)\n setFillColor(nextColor)\n applyStyle({\n fill: {\n color: toXlsxRgbColor(nextColor),\n fillType: "solid",\n },\n })\n }}\n />\n <ToolbarIconButton\n label="No fill"\n disabled={!canStyleSelection}\n onClick={() => applyStyle({ fill: { fillType: "none" } })}\n >\n <IconPlaceholder\n lucide="DropletOff"\n tabler="IconDropletOff"\n hugeicons="DropletOffIcon"\n phosphor="DropSlashIcon"\n remixicon="RiDropLine"\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <ToggleGroup\n className="shrink-0"\n disabled={!canStyleSelection}\n spacing="default"\n value={horizontalAlignmentValue}\n >\n <ToolbarTooltip label="Align left">\n <ToggleGroupItem\n aria-label="Align left"\n size="sm"\n value="left"\n onClick={() => applyHorizontalAlignment("left")}\n >\n <IconPlaceholder\n lucide="AlignLeft"\n tabler="IconAlignLeft"\n hugeicons="TextAlignLeft01Icon"\n phosphor="TextAlignLeftIcon"\n remixicon="RiAlignLeft"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Align center">\n <ToggleGroupItem\n aria-label="Align center"\n size="sm"\n value="center"\n onClick={() => applyHorizontalAlignment("center")}\n >\n <IconPlaceholder\n lucide="AlignCenter"\n tabler="IconAlignCenter"\n hugeicons="TextAlignCenterIcon"\n phosphor="TextAlignCenterIcon"\n remixicon="RiAlignCenter"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Align right">\n <ToggleGroupItem\n aria-label="Align right"\n size="sm"\n value="right"\n onClick={() => applyHorizontalAlignment("right")}\n >\n <IconPlaceholder\n lucide="AlignRight"\n tabler="IconAlignRight"\n hugeicons="TextAlignRight01Icon"\n phosphor="TextAlignRightIcon"\n remixicon="RiAlignRight"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n </ToggleGroup>\n <ToggleGroup\n className="shrink-0"\n disabled={!canStyleSelection}\n spacing="default"\n value={verticalAlignmentValue}\n >\n <ToolbarTooltip label="Align top">\n <ToggleGroupItem\n aria-label="Align top"\n size="sm"\n value="top"\n onClick={() => applyVerticalAlignment("top")}\n >\n <IconPlaceholder\n lucide="AlignVerticalJustifyStart"\n tabler="IconAlignBoxTopCenter"\n hugeicons="AlignBoxTopCenterIcon"\n phosphor="AlignTopIcon"\n remixicon="RiAlignTop"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Align middle">\n <ToggleGroupItem\n aria-label="Align middle"\n size="sm"\n value="center"\n onClick={() => applyVerticalAlignment("center")}\n >\n <IconPlaceholder\n lucide="AlignVerticalJustifyCenter"\n tabler="IconAlignBoxCenterMiddle"\n hugeicons="AlignBoxMiddleCenterIcon"\n phosphor="AlignCenterVerticalIcon"\n remixicon="RiAlignVertically"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Align bottom">\n <ToggleGroupItem\n aria-label="Align bottom"\n size="sm"\n value="bottom"\n onClick={() => applyVerticalAlignment("bottom")}\n >\n <IconPlaceholder\n lucide="AlignVerticalJustifyEnd"\n tabler="IconAlignBoxBottomCenter"\n hugeicons="AlignBoxBottomCenterIcon"\n phosphor="AlignBottomIcon"\n remixicon="RiAlignBottom"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n </ToggleGroup>\n <ToolbarIconButton\n label="Wrap text"\n disabled={!canStyleSelection}\n onClick={() => applyStyle({ alignment: { wrapText: true } })}\n >\n <IconPlaceholder\n lucide="WrapText"\n tabler="IconTextWrap"\n hugeicons="TextWrapIcon"\n phosphor="ArrowElbowDownLeftIcon"\n remixicon="RiTextWrap"\n className="size-4"\n />\n </ToolbarIconButton>\n <AlignmentMoreMenu\n disabled={!canStyleSelection}\n onApplyStyle={applyStyle}\n />\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <NumberFormatSelect\n disabled={!canStyleSelection}\n onApplyStyle={applyStyle}\n value={numberFormatValue}\n />\n <BorderMenu\n borderColor={borderColor}\n disabled={!canStyleSelection}\n onApplyBorder={applyBorderAction}\n onBorderColorChange={setBorderColor}\n />\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <MergeCellsMenu\n canMerge={canMergeSelectedCells}\n canMergeAcross={canMergeAcross}\n canUnmerge={canUnmergeSelectedCells}\n disabled={!hasSelection || readOnly}\n isMerged={selectionIntersectsMerge}\n onMergeAcross={mergeAcrossSelectedCells}\n onMergeAndCenter={mergeAndCenterSelectedCells}\n onMergeCells={mergeSelectedCells}\n onUnmergeCells={unmergeSelectedCells}\n />\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarTooltip label="Add sheet">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Add sheet"\n disabled={!hasWorkbook || readOnly}\n onClick={() => addSheet()}\n >\n <IconPlaceholder\n lucide="Plus"\n tabler="IconPlus"\n hugeicons="Add01Icon"\n phosphor="PlusIcon"\n remixicon="RiAddLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Remove active sheet">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Remove active sheet"\n disabled={sheets.length <= 1 || readOnly}\n onClick={removeActiveSheet}\n >\n <IconPlaceholder\n lucide="Trash2Icon"\n tabler="IconTrash"\n hugeicons="Delete02Icon"\n phosphor="TrashIcon"\n remixicon="RiDeleteBinLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={String(activeSheetIndex)}\n onValueChange={(value) => setActiveSheetIndex(Number(value))}\n disabled={!hasWorkbook}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[150px] min-w-[150px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Active sheet"\n >\n <SelectValue>{activeSheet?.name ?? "Sheet"}</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="start"\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {sheets.map((sheet, index) => (\n <SelectItem\n key={`${sheet.name}-${index}`}\n value={String(index)}\n >\n {sheet.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <ToolbarSeparator />\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={!hasWorkbook || !canZoomOut}\n aria-label="Zoom out"\n onClick={zoomOut}\n >\n <IconPlaceholder\n lucide="CircleMinus"\n tabler="IconCircleMinus"\n hugeicons="MinusSignCircleIcon"\n phosphor="MinusCircleIcon"\n remixicon="RiIndeterminateCircleLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={currentZoom.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={!hasWorkbook}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[84px] min-w-[84px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Zoom level"\n >\n <SelectValue>{currentZoom}%</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="end"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={!hasWorkbook || !canZoomIn}\n aria-label="Zoom in"\n onClick={zoomIn}\n >\n <IconPlaceholder\n lucide="CirclePlusIcon"\n tabler="IconCirclePlusFilled"\n hugeicons="PlusSignCircleIcon"\n phosphor="PlusCircleIcon"\n remixicon="RiAddCircleFill"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n </div>\n <div className="border-t bg-background px-2 py-1">\n <Group className="w-full">\n <Input\n className={cn(\n "h-8 w-[92px] shrink-0 font-mono text-xs",\n XLSX_EDITOR_FORMULA_INPUT_CHROME_CLASS\n )}\n readOnly\n value={activeCellAddress ?? ""}\n />\n <GroupSeparator />\n <GroupText className="h-8 w-9 shrink-0 justify-center px-0 text-[11px] font-semibold italic">\n fx\n </GroupText>\n <GroupSeparator />\n <Input\n className={cn(\n "h-8 flex-1",\n XLSX_EDITOR_FORMULA_INPUT_CHROME_CLASS\n )}\n disabled={!hasActiveCell || readOnly}\n value={formulaDraft}\n onBlur={() => {\n commitFormula()\n setFormulaFocused(false)\n }}\n onChange={(event) => setFormulaDraft(event.target.value)}\n onFocus={() => {\n formulaEditCellRef.current = activeCell\n formulaInitialValueRef.current = formulaDraft\n setFormulaFocused(true)\n }}\n onKeyDown={(event) => {\n if (event.key === "Enter") {\n event.preventDefault()\n commitFormula()\n setFormulaFocused(false)\n }\n }}\n placeholder="Select a cell, then enter a value or formula"\n />\n </Group>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nexport function XlsxEditorSurface({\n className,\n isDark,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n showNightRenderToggle,\n workbookIdentity,\n}: {\n className?: string\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n showNightRenderToggle: boolean\n workbookIdentity: string\n}) {\n const { error } = useXlsxViewer()\n\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <EditorToolbar\n isDark={isDark}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n showNightRenderToggle={showNightRenderToggle}\n workbookIdentity={workbookIdentity}\n />\n <div className="flex min-h-0 flex-1 flex-col">\n <div className="min-h-0 flex-1 bg-muted/20">\n <XlsxViewer\n allowResizeInReadOnly\n className="h-full min-h-0 min-w-0"\n height="100%"\n isDark={isDark}\n readOnly={false}\n rounded={false}\n showDefaultToolbar={false}\n showImages\n fileTooLargeState={\n <div className="grid h-full w-full min-w-full place-items-center p-6">\n <div className="max-w-sm rounded-lg border bg-background p-4 text-sm">\n <p className="font-medium">File too large for editing</p>\n <p className="mt-1 text-muted-foreground">\n This workbook exceeds the editor limit. Download it or open\n a smaller file to make changes.\n </p>\n </div>\n </div>\n }\n loadingState={<EditorLoadingSurface />}\n renderScroller={renderXlsxScroller}\n errorState={\n <div className="grid h-full w-full min-w-full place-items-center p-6 text-sm text-destructive">\n {error?.message ?? "Unable to edit workbook."}\n </div>\n }\n renderTableHeaderMenu={renderTableHeaderMenu}\n />\n </div>\n <WorkbookSheetTabs workbookIdentity={workbookIdentity} />\n </div>\n </div>\n )\n}\n\nexport function XlsxEditorPreview({\n className,\n fileName,\n isDark,\n onIsDarkChange,\n src,\n}: {\n className?: string\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n src?: string\n}) {\n return (\n <XlsxEditorContent\n className={className}\n effectiveIsDark={isDark}\n fileName={fileName}\n setNightRenderEnabled={onIsDarkChange}\n shouldRenderNightMode\n url={src}\n />\n )\n}\n\nfunction XlsxEditorContent({\n className,\n effectiveIsDark,\n fileName,\n setNightRenderEnabled,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n effectiveIsDark: boolean\n fileName?: string\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const [uploadedWorkbook, setUploadedWorkbook] =\n React.useState<UploadedWorkbook | null>(null)\n const [workbookBuffer, setWorkbookBuffer] =\n React.useState<ArrayBuffer | null>(null)\n const [loadError, setLoadError] = React.useState<string>()\n const sourceFileName = React.useMemo(\n () =>\n url ? formatWorkbookName(fileName, url) : (fileName ?? "workbook.xlsx"),\n [fileName, url]\n )\n const displayFileName = uploadedWorkbook?.fileName ?? sourceFileName\n const workbookIdentity =\n uploadedWorkbook?.identity ?? `${url ?? "empty"}::${displayFileName}`\n const shouldShowLoadingSpinner = useDelayedLoadingIndicator(\n !workbookBuffer && !loadError && !uploadedWorkbook,\n XLSX_LOADING_INDICATOR_DELAY_MS\n )\n\n React.useEffect(() => {\n let isCurrent = true\n\n if (url) {\n setUploadedWorkbook(null)\n }\n\n async function loadWorkbook(): Promise<void> {\n if (!url) {\n setWorkbookBuffer(null)\n setLoadError(undefined)\n return\n }\n\n setWorkbookBuffer(null)\n setLoadError(undefined)\n\n try {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch XLSX (${response.status})`)\n }\n\n const nextWorkbookBuffer = await response.arrayBuffer()\n if (!isCurrent) return\n\n setWorkbookBuffer(nextWorkbookBuffer)\n } catch (error) {\n if (!isCurrent) return\n\n setLoadError(\n error instanceof Error ? error.message : "Unknown XLSX load error"\n )\n }\n }\n\n void loadWorkbook()\n\n return () => {\n isCurrent = false\n }\n }, [url])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n const buffer = await file.arrayBuffer()\n setWorkbookBuffer(null)\n setLoadError(undefined)\n setUploadedWorkbook({\n buffer,\n fileName: file.name,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n const activeBuffer = uploadedWorkbook?.buffer ?? workbookBuffer\n\n if (!url && !uploadedWorkbook) {\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <div className="grid min-h-0 flex-1 place-items-center bg-muted/30 p-4">\n <div className="max-w-md rounded-lg border bg-background p-4 text-center text-sm shadow-xs">\n <p className="font-medium">Upload a workbook to edit</p>\n <p className="mt-1 text-muted-foreground">\n Pass an XLSX URL with the <code>src</code> prop or upload a local\n file.\n </p>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (loadError && !activeBuffer) {\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <div className="grid min-h-0 flex-1 place-items-center bg-muted/30 p-4">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm">\n <p className="font-medium">Unable to edit workbook</p>\n <p className="mt-1 text-muted-foreground">{loadError}</p>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (!activeBuffer) {\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <EditorLoadingSurface showSpinner={shouldShowLoadingSpinner} />\n </div>\n )\n }\n\n return (\n <div className={cn("overflow-hidden", className)}>\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <XlsxWorkbookLoadedEditor\n fileName={displayFileName}\n isDark={effectiveIsDark}\n onIsDarkChange={setNightRenderEnabled}\n onUploadClick={() => fileInputRef.current?.click()}\n renderTableHeaderMenu={(props) => (\n <WorkbookTableHeaderMenu {...props} />\n )}\n showNightRenderToggle={shouldRenderNightMode}\n workbookBuffer={activeBuffer}\n workbookIdentity={workbookIdentity}\n />\n </div>\n )\n}\n\nfunction XlsxWorkbookLoadedEditor({\n fileName,\n isDark,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n showNightRenderToggle,\n workbookBuffer,\n workbookIdentity,\n}: {\n fileName: string\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n showNightRenderToggle: boolean\n workbookBuffer: ArrayBuffer\n workbookIdentity: string\n}) {\n const controller = useXlsxViewerController(\n React.useMemo(\n () => ({\n allowResizeInReadOnly: true,\n file: workbookBuffer,\n fileName,\n readOnly: false,\n readOnlyAboveBytes: XLSX_EDITOR_READ_ONLY_THRESHOLD_BYTES,\n useWorker: true,\n }),\n [fileName, workbookBuffer]\n )\n )\n\n return (\n <XlsxViewerProvider controller={controller} isDark={isDark}>\n <XlsxEditorSurface\n isDark={isDark}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n renderTableHeaderMenu={renderTableHeaderMenu}\n showNightRenderToggle={showNightRenderToggle}\n workbookIdentity={workbookIdentity}\n />\n </XlsxViewerProvider>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport {\n useXlsxViewer,\n useXlsxViewerController,\n useXlsxViewerEditing,\n useXlsxViewerSelection,\n useXlsxViewerZoom,\n XlsxViewer,\n XlsxViewerProvider,\n type XlsxCellAlignmentInput,\n type XlsxCellBorderEdgeInput,\n type XlsxCellRange,\n type XlsxCellStyleInput,\n type XlsxSheetData,\n type XlsxTableHeaderMenuRenderProps,\n} from "@extend-ai/react-xlsx"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport { ColorPicker, ColorPickerPanel } from "@/components/ui/color-picker"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuGroup,\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuSub,\n DropdownMenuSubContent,\n DropdownMenuSubTrigger,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { Group, GroupSeparator, GroupText } from "@/components/ui/group"\nimport { Input } from "@/components/ui/input"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport {\n renderXlsxScroller,\n WorkbookSheetTabs,\n WorkbookTableHeaderMenu,\n} from "@/components/extend/xlsx-viewer"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nfunction BorderAll01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Grid2x2"\n tabler="IconBorderAll"\n hugeicons="BorderAll01Icon"\n phosphor="GridFourIcon"\n remixicon="RiGridLine"\n {...props}\n />\n )\n}\n\nfunction BorderBottom01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PanelBottom"\n tabler="IconBorderBottom"\n hugeicons="BorderBottom01Icon"\n phosphor="SquareHalfBottomIcon"\n remixicon="RiLayoutBottomLine"\n {...props}\n />\n )\n}\n\nfunction BorderLeft01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PanelLeft"\n tabler="IconBorderLeft"\n hugeicons="BorderLeft01Icon"\n phosphor="SquareHalfIcon"\n remixicon="RiLayoutLeftLine"\n {...props}\n />\n )\n}\n\nfunction BorderNone01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="SquareDashed"\n tabler="IconBorderNone"\n hugeicons="BorderNone01Icon"\n phosphor="SelectionIcon"\n remixicon="RiCheckboxBlankLine"\n {...props}\n />\n )\n}\n\nfunction BorderRight01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PanelRight"\n tabler="IconBorderRight"\n hugeicons="BorderRight01Icon"\n phosphor="SquareHalfIcon"\n remixicon="RiLayoutRightLine"\n {...props}\n />\n )\n}\n\nfunction BorderTop01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PanelTop"\n tabler="IconBorderTop"\n hugeicons="BorderTop01Icon"\n phosphor="AlignTopSimpleIcon"\n remixicon="RiLayoutTopLine"\n {...props}\n />\n )\n}\n\nfunction Calendar03Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Calendar"\n tabler="IconCalendar"\n hugeicons="Calendar03Icon"\n phosphor="CalendarIcon"\n remixicon="RiCalendarLine"\n {...props}\n />\n )\n}\n\nfunction DollarCircleGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="CircleDollarSign"\n tabler="IconCurrencyDollar"\n hugeicons="DollarCircleIcon"\n phosphor="CurrencyCircleDollarIcon"\n remixicon="RiMoneyDollarCircleLine"\n {...props}\n />\n )\n}\n\nfunction Moon02Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Moon"\n tabler="IconMoon"\n hugeicons="Moon02Icon"\n phosphor="MoonIcon"\n remixicon="RiMoonLine"\n {...props}\n />\n )\n}\n\nfunction PaintBucketGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PaintBucket"\n tabler="IconPaint"\n hugeicons="PaintBucketIcon"\n phosphor="PaintBucketIcon"\n remixicon="RiPaintFill"\n {...props}\n />\n )\n}\n\nfunction PercentGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Percent"\n tabler="IconPercentage"\n hugeicons="PercentIcon"\n phosphor="PercentIcon"\n remixicon="RiPercentLine"\n {...props}\n />\n )\n}\n\nfunction Sun03Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Sun"\n tabler="IconSun"\n hugeicons="Sun03Icon"\n phosphor="SunIcon"\n remixicon="RiSunLine"\n {...props}\n />\n )\n}\n\nfunction TextColorGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Baseline"\n tabler="IconTextColor"\n hugeicons="TextColorIcon"\n phosphor="TextAaIcon"\n remixicon="RiFontColor"\n {...props}\n />\n )\n}\n\nfunction TextNumberSignGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Hash"\n tabler="IconHash"\n hugeicons="TextNumberSignIcon"\n phosphor="HashIcon"\n remixicon="RiHashtag"\n {...props}\n />\n )\n}\n\nfunction TextWrapGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="WrapText"\n tabler="IconTextWrap"\n hugeicons="TextWrapIcon"\n phosphor="ArrowElbowDownLeftIcon"\n remixicon="RiTextWrap"\n {...props}\n />\n )\n}\n\nconst XLSX_LOADING_INDICATOR_DELAY_MS = 300\nconst XLSX_EDITOR_READ_ONLY_THRESHOLD_BYTES = 5 * 1024 * 1024\nconst XLSX_DROPDOWN_Z_INDEX_CLASS = "z-40"\nconst ZOOM_OPTIONS = [50, 75, 100, 125, 150, 200, 400] as const\nconst DEFAULT_FONT_FAMILY = "Arial"\nconst FONT_FAMILIES = [\n "Arial",\n "Times New Roman",\n "Georgia",\n "Helvetica",\n "Courier New",\n] as const\nconst FONT_SIZE_OPTIONS = [\n 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48,\n] as const\nconst DEFAULT_TEXT_COLOR = "#111827"\nconst DEFAULT_FILL_COLOR = "#fde68a"\nconst DEFAULT_BORDER_COLOR = "#111827"\nconst XLSX_EDITOR_SELECT_CHROME_CLASS =\n "shadow-none before:shadow-none not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-none dark:not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-none"\nconst XLSX_EDITOR_FORMULA_INPUT_CHROME_CLASS =\n "has-disabled:opacity-100 dark:has-disabled:before:shadow-[0_-1px_--theme(--color-white/6%)]"\n\ntype UploadedWorkbook = {\n buffer: ArrayBuffer\n fileName: string\n identity: string\n}\n\ntype NumberFormatOption = {\n formatString?: string\n formatType: NonNullable<XlsxCellStyleInput["numberFormat"]>["formatType"]\n icon: React.ComponentType<React.ComponentProps<"svg">>\n id?: number\n label: string\n value: string\n}\n\ntype BorderOption = {\n action: XlsxBorderAction\n icon: React.ComponentType<React.ComponentProps<"svg">>\n label: string\n}\n\ntype XlsxResolvedCellStyle = XlsxSheetData["styleById"][number]\ntype XlsxResolvedStyleGroup = Record<string, unknown>\n\ntype HorizontalAlignment = NonNullable<XlsxCellAlignmentInput["horizontal"]>\n\ntype VerticalAlignment = NonNullable<XlsxCellAlignmentInput["vertical"]>\n\ntype HorizontalAlignmentToggleValue = Extract<\n HorizontalAlignment,\n "left" | "center" | "right"\n>\n\ntype VerticalAlignmentToggleValue = Extract<\n VerticalAlignment,\n "top" | "center" | "bottom"\n>\n\ntype XlsxFontToggleValue = "bold" | "italic" | "underline" | "strikethrough"\n\ntype XlsxMergeRegion = XlsxCellRange\n\ntype XlsxBorderEdgeKey = "bottom" | "left" | "top" | "right"\n\ntype XlsxBorderAction = "all" | "outside" | "none" | XlsxBorderEdgeKey\n\ntype XlsxWorksheetWithMergeRegions = {\n mergedRegions?: unknown[]\n unmergeCells?: (range: string) => boolean\n}\n\nconst NUMBER_FORMAT_OPTIONS: NumberFormatOption[] = [\n {\n formatType: "general",\n icon: TextNumberSignGlyph,\n label: "General",\n value: "General",\n },\n {\n formatString: "0.00",\n formatType: "custom",\n icon: TextNumberSignGlyph,\n label: "Number",\n value: "Number",\n },\n {\n formatString: "$#,##0.00",\n formatType: "custom",\n icon: DollarCircleGlyph,\n label: "Currency",\n value: "Currency",\n },\n {\n formatString: "0.00%",\n formatType: "custom",\n icon: PercentGlyph,\n label: "Percent",\n value: "Percent",\n },\n {\n formatString: "m/d/yyyy",\n formatType: "custom",\n icon: Calendar03Glyph,\n label: "Date",\n value: "Date",\n },\n]\n\nconst GENERAL_NUMBER_FORMAT_VALUE = "General"\nconst BUILTIN_NUMBER_FORMAT_VALUE_PREFIX = "builtin:"\n\nfunction formatWorkbookName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "workbook.xlsx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\n}\n\nfunction normalizeHexColor(value: string, fallback = DEFAULT_TEXT_COLOR) {\n const trimmed = value.trim()\n const threeDigit = /^#?([0-9a-f]{3})$/i.exec(trimmed)\n if (threeDigit?.[1]) {\n const [red, green, blue] = threeDigit[1].split("")\n return `#${red}${red}${green}${green}${blue}${blue}`.toLowerCase()\n }\n\n const sixDigit = /^#?([0-9a-f]{6})$/i.exec(trimmed)\n if (sixDigit?.[1]) {\n return `#${sixDigit[1].toLowerCase()}`\n }\n\n return fallback\n}\n\nfunction toXlsxRgbColor(value: string) {\n return {\n colorType: "rgb" as const,\n hex: normalizeHexColor(value).slice(1).toUpperCase(),\n }\n}\n\nfunction asResolvedStyleGroup(\n value: unknown\n): XlsxResolvedStyleGroup | undefined {\n return value && typeof value === "object" && !Array.isArray(value)\n ? (value as XlsxResolvedStyleGroup)\n : undefined\n}\n\nfunction mergeResolvedCellStyle(\n base: XlsxResolvedCellStyle | null | undefined,\n overlay: XlsxResolvedCellStyle | null | undefined\n): XlsxResolvedCellStyle | null {\n if (!base && !overlay) return null\n\n const nextStyle = { ...(base ?? {}), ...(overlay ?? {}) }\n const baseFont = asResolvedStyleGroup(base?.font)\n const overlayFont = asResolvedStyleGroup(overlay?.font)\n\n if (baseFont || overlayFont) {\n nextStyle.font = overlayFont ?? baseFont\n }\n\n return nextStyle\n}\n\nfunction resolveInheritedCellStyle(\n sheet: XlsxSheetData | null,\n row: number,\n col: number\n): XlsxResolvedCellStyle | null {\n if (!sheet) return null\n\n const colStyleId = sheet.colStyleIds[col]\n const rowStyleId = sheet.rowStyleIds[row]\n const colStyle =\n colStyleId !== undefined ? sheet.styleById[colStyleId] : undefined\n const rowStyle =\n rowStyleId !== undefined ? sheet.styleById[rowStyleId] : undefined\n\n return mergeResolvedCellStyle(colStyle, rowStyle)\n}\n\nfunction getFontToggleValuesFromStyle(\n style: XlsxResolvedCellStyle | null\n): XlsxFontToggleValue[] {\n const font = asResolvedStyleGroup(style?.font)\n const values: XlsxFontToggleValue[] = []\n\n if (font?.bold === true) values.push("bold")\n if (font?.italic === true) values.push("italic")\n if (font?.underline && font.underline !== "none") values.push("underline")\n if (font?.strikethrough === true) values.push("strikethrough")\n\n return values\n}\n\nfunction getFontFamilyValue(style: XlsxResolvedCellStyle | null) {\n const font = asResolvedStyleGroup(style?.font)\n const fontName = font?.name\n\n return typeof fontName === "string" && fontName.trim()\n ? fontName.trim()\n : undefined\n}\n\nfunction getHorizontalAlignmentValue(\n style: XlsxResolvedCellStyle | null\n): HorizontalAlignmentToggleValue[] {\n const alignment = asResolvedStyleGroup(style?.alignment)\n const horizontal = alignment?.horizontal\n\n return horizontal === "left" ||\n horizontal === "center" ||\n horizontal === "right"\n ? [horizontal]\n : []\n}\n\nfunction getVerticalAlignmentValue(\n style: XlsxResolvedCellStyle | null\n): VerticalAlignmentToggleValue[] {\n const alignment = asResolvedStyleGroup(style?.alignment)\n const vertical = alignment?.vertical\n\n if (vertical === undefined || vertical === null) return ["bottom"]\n\n return vertical === "top" || vertical === "center" || vertical === "bottom"\n ? [vertical]\n : []\n}\n\nfunction getNumberFormatValue(style: XlsxResolvedCellStyle | null) {\n const numberFormat = asResolvedStyleGroup(style?.numberFormat)\n\n if (!numberFormat) return GENERAL_NUMBER_FORMAT_VALUE\n\n const formatType = numberFormat.formatType\n const formatString =\n typeof numberFormat.formatString === "string"\n ? numberFormat.formatString.trim()\n : ""\n const id = getNumericValue(numberFormat.id)\n\n if (formatString) {\n const matchingOption = NUMBER_FORMAT_OPTIONS.find(\n (option) => option.formatString === formatString\n )\n\n return matchingOption?.value ?? formatString\n }\n if (formatType === "builtin" && id !== undefined) {\n const matchingOption = NUMBER_FORMAT_OPTIONS.find(\n (option) => option.id === id\n )\n\n if (matchingOption) return matchingOption.value\n\n return `${BUILTIN_NUMBER_FORMAT_VALUE_PREFIX}${id}`\n }\n if (formatType === "general") return GENERAL_NUMBER_FORMAT_VALUE\n\n return GENERAL_NUMBER_FORMAT_VALUE\n}\n\nfunction getNumberFormatLabel(value: string) {\n if (value === GENERAL_NUMBER_FORMAT_VALUE) return "General"\n\n const matchingOption = NUMBER_FORMAT_OPTIONS.find(\n (option) => option.value === value\n )\n if (matchingOption) return matchingOption.label\n\n if (value.startsWith(BUILTIN_NUMBER_FORMAT_VALUE_PREFIX)) {\n return `Builtin ${value.slice(BUILTIN_NUMBER_FORMAT_VALUE_PREFIX.length)}`\n }\n\n return value\n}\n\nfunction getNumberFormatIcon(value: string) {\n return (\n NUMBER_FORMAT_OPTIONS.find((option) => option.value === value)?.icon ??\n TextNumberSignGlyph\n )\n}\n\nfunction createNumberFormatStyle(value: string): XlsxCellStyleInput {\n const matchingOption = NUMBER_FORMAT_OPTIONS.find(\n (option) => option.value === value\n )\n\n if (matchingOption) {\n return {\n numberFormat: {\n formatString: matchingOption.formatString,\n formatType: matchingOption.formatType,\n id: matchingOption.id,\n },\n }\n }\n\n if (value.startsWith(BUILTIN_NUMBER_FORMAT_VALUE_PREFIX)) {\n const id = Number(value.slice(BUILTIN_NUMBER_FORMAT_VALUE_PREFIX.length))\n\n if (Number.isFinite(id)) {\n return {\n numberFormat: {\n formatType: "builtin",\n id: Math.max(0, Math.trunc(id)),\n },\n }\n }\n }\n\n return {\n numberFormat: {\n formatString: value,\n formatType: "custom",\n },\n }\n}\n\nfunction normalizeCellRange(range: XlsxCellRange): XlsxCellRange {\n return {\n start: {\n row: Math.min(range.start.row, range.end.row),\n col: Math.min(range.start.col, range.end.col),\n },\n end: {\n row: Math.max(range.start.row, range.end.row),\n col: Math.max(range.start.col, range.end.col),\n },\n }\n}\n\nfunction getNumericValue(value: unknown) {\n return typeof value === "number" && Number.isFinite(value)\n ? Math.max(0, Math.trunc(value))\n : undefined\n}\n\nfunction getWorksheetMergeRegions(\n worksheet: XlsxWorksheetWithMergeRegions | null\n): XlsxMergeRegion[] {\n if (!Array.isArray(worksheet?.mergedRegions)) return []\n\n return worksheet.mergedRegions.flatMap((entry) => {\n if (!entry || typeof entry !== "object") return []\n\n const region = entry as Record<string, unknown>\n const start = asResolvedStyleGroup(region.start)\n const end = asResolvedStyleGroup(region.end)\n const startRow = getNumericValue(region.startRow ?? start?.row)\n const startCol = getNumericValue(region.startCol ?? start?.col)\n const endRow = getNumericValue(region.endRow ?? end?.row)\n const endCol = getNumericValue(region.endCol ?? end?.col)\n\n if (\n startRow === undefined ||\n startCol === undefined ||\n endRow === undefined ||\n endCol === undefined\n ) {\n return []\n }\n\n return [\n normalizeCellRange({\n start: { row: startRow, col: startCol },\n end: { row: endRow, col: endCol },\n }),\n ]\n })\n}\n\nfunction rangesIntersect(\n firstRange: XlsxCellRange,\n secondRange: XlsxCellRange\n) {\n const first = normalizeCellRange(firstRange)\n const second = normalizeCellRange(secondRange)\n\n return (\n first.start.row <= second.end.row &&\n first.end.row >= second.start.row &&\n first.start.col <= second.end.col &&\n first.end.col >= second.start.col\n )\n}\n\nfunction isSingleCellRange(range: XlsxCellRange) {\n const normalizedRange = normalizeCellRange(range)\n\n return (\n normalizedRange.start.row === normalizedRange.end.row &&\n normalizedRange.start.col === normalizedRange.end.col\n )\n}\n\nfunction getCellColumnLabel(col: number) {\n let label = ""\n let value = col\n\n do {\n label = String.fromCharCode(65 + (value % 26)) + label\n value = Math.floor(value / 26) - 1\n } while (value >= 0)\n\n return label\n}\n\nfunction cellAddressToA1(cell: XlsxCellRange["start"]) {\n return `${getCellColumnLabel(cell.col)}${cell.row + 1}`\n}\n\nfunction rangeToA1(range: XlsxCellRange) {\n const normalizedRange = normalizeCellRange(range)\n\n return `${cellAddressToA1(normalizedRange.start)}:${cellAddressToA1(\n normalizedRange.end\n )}`\n}\n\nfunction getRangeKey(range: XlsxCellRange) {\n const normalizedRange = normalizeCellRange(range)\n\n return `${normalizedRange.start.row}:${normalizedRange.start.col}:${normalizedRange.end.row}:${normalizedRange.end.col}`\n}\n\nfunction createBorderEdge(\n color = DEFAULT_BORDER_COLOR\n): XlsxCellBorderEdgeInput {\n return {\n color: toXlsxRgbColor(color),\n style: "thin",\n }\n}\n\nfunction createBorderPatch(\n entries: Partial<Record<XlsxBorderEdgeKey, XlsxCellBorderEdgeInput>>\n): XlsxCellStyleInput {\n return {\n border: entries,\n }\n}\n\nfunction createNoBorderPatch(): XlsxCellStyleInput {\n return {\n border: {\n bottom: { style: "none" },\n left: { style: "none" },\n right: { style: "none" },\n top: { style: "none" },\n },\n }\n}\n\nfunction createBorderOptions(): BorderOption[] {\n return [\n {\n action: "bottom",\n icon: BorderBottom01Glyph,\n label: "Bottom border",\n },\n {\n action: "left",\n icon: BorderLeft01Glyph,\n label: "Left border",\n },\n {\n action: "top",\n icon: BorderTop01Glyph,\n label: "Top border",\n },\n {\n action: "right",\n icon: BorderRight01Glyph,\n label: "Right border",\n },\n {\n action: "all",\n icon: BorderAll01Glyph,\n label: "All borders",\n },\n {\n action: "outside",\n icon: BorderAll01Glyph,\n label: "Outside border",\n },\n {\n action: "none",\n icon: BorderNone01Glyph,\n label: "No border",\n },\n ]\n}\n\nfunction getBorderEdgeRange(\n range: XlsxCellRange,\n edgeKey: XlsxBorderEdgeKey\n): XlsxCellRange {\n const normalizedRange = normalizeCellRange(range)\n\n if (edgeKey === "top") {\n return {\n start: normalizedRange.start,\n end: { row: normalizedRange.start.row, col: normalizedRange.end.col },\n }\n }\n\n if (edgeKey === "bottom") {\n return {\n start: { row: normalizedRange.end.row, col: normalizedRange.start.col },\n end: normalizedRange.end,\n }\n }\n\n if (edgeKey === "left") {\n return {\n start: normalizedRange.start,\n end: { row: normalizedRange.end.row, col: normalizedRange.start.col },\n }\n }\n\n return {\n start: { row: normalizedRange.start.row, col: normalizedRange.end.col },\n end: normalizedRange.end,\n }\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction EditorLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 w-full min-w-full place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction ToolbarIconButton({\n active,\n children,\n label,\n ...props\n}: React.ComponentProps<typeof Button> & {\n active?: boolean\n label: string\n}) {\n return (\n <ToolbarTooltip label={label}>\n <Button\n type="button"\n variant={active ? "secondary" : "ghost"}\n size="icon-sm"\n aria-label={label}\n data-pressed={active ? "" : undefined}\n {...props}\n >\n {children}\n </Button>\n </ToolbarTooltip>\n )\n}\n\nfunction ToolbarSeparator() {\n return <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n}\n\nfunction StyleDropdownItem({\n children,\n icon,\n onClick,\n}: {\n children: React.ReactNode\n icon: React.ComponentType<React.ComponentProps<"svg">>\n onClick: () => void\n}) {\n const IconComponent = icon\n return (\n <DropdownMenuItem onClick={onClick}>\n <IconComponent className="size-4" />\n {children}\n </DropdownMenuItem>\n )\n}\n\nfunction MergeCellsMenu({\n canMerge,\n canMergeAcross,\n canUnmerge,\n disabled,\n isMerged,\n onMergeAcross,\n onMergeAndCenter,\n onMergeCells,\n onUnmergeCells,\n}: {\n canMerge: boolean\n canMergeAcross: boolean\n canUnmerge: boolean\n disabled: boolean\n isMerged: boolean\n onMergeAcross: () => void\n onMergeAndCenter: () => void\n onMergeCells: () => void\n onUnmergeCells: () => void\n}) {\n return (\n <DropdownMenu>\n <div\n className={cn(\n "inline-flex shrink-0 overflow-hidden rounded-lg border border-transparent"\n )}\n >\n <ToolbarTooltip\n label={isMerged ? "Unmerge cells from the menu" : "Merge & Center"}\n >\n <Button\n type="button"\n variant={isMerged ? "secondary" : "ghost"}\n size="sm"\n aria-label="Merge & Center"\n className="h-7 rounded-r-none border-0 px-2.5 before:rounded-r-none"\n data-pressed={isMerged ? "" : undefined}\n disabled={disabled || !canMerge}\n onClick={onMergeAndCenter}\n >\n <IconPlaceholder\n lucide="TableCellsMerge"\n tabler="IconArrowMerge"\n hugeicons="PathfinderMergeIcon"\n phosphor="ArrowsMergeIcon"\n remixicon="RiMergeCellsVertical"\n className="size-4"\n />\n <span className="hidden text-xs font-medium lg:inline">\n Merge & Center\n </span>\n </Button>\n </ToolbarTooltip>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant={isMerged ? "secondary" : "ghost"}\n size="icon-sm"\n aria-label="Merge cells options"\n className="h-7 w-6 rounded-l-none border-0 px-0 before:rounded-l-none"\n data-pressed={isMerged ? "" : undefined}\n disabled={disabled}\n >\n <IconPlaceholder\n lucide="ChevronDown"\n tabler="IconChevronDown"\n hugeicons="ChevronDownIcon"\n phosphor="CaretDownIcon"\n remixicon="RiArrowDownSLine"\n className="size-3.5 opacity-100"\n />\n </Button>\n </DropdownMenuTrigger>\n </div>\n <DropdownMenuContent\n align="start"\n className={cn("w-56", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <DropdownMenuItem disabled={!canMerge} onClick={onMergeAndCenter}>\n <IconPlaceholder\n lucide="TableCellsMerge"\n tabler="IconArrowMerge"\n hugeicons="PathfinderMergeIcon"\n phosphor="ArrowsMergeIcon"\n remixicon="RiMergeCellsVertical"\n className="size-4"\n />\n Merge & Center\n </DropdownMenuItem>\n <DropdownMenuItem disabled={!canMergeAcross} onClick={onMergeAcross}>\n <IconPlaceholder\n lucide="TableRowsSplit"\n tabler="IconArrowsSplit"\n hugeicons="TableRowsSplitIcon"\n phosphor="ArrowsSplitIcon"\n remixicon="RiSplitCellsVertical"\n className="size-4"\n />\n Merge Across\n </DropdownMenuItem>\n <DropdownMenuItem disabled={!canMerge} onClick={onMergeCells}>\n <IconPlaceholder\n lucide="Grid3x3"\n tabler="IconGrid4x4"\n hugeicons="CellsIcon"\n phosphor="GridNineIcon"\n remixicon="RiMergeCellsHorizontal"\n className="size-4"\n />\n Merge Cells\n </DropdownMenuItem>\n <DropdownMenuSeparator />\n <DropdownMenuItem disabled={!canUnmerge} onClick={onUnmergeCells}>\n <IconPlaceholder\n lucide="Grid2x2X"\n tabler="IconTableMinus"\n hugeicons="Grid2X2XIcon"\n phosphor="SelectionSlashIcon"\n remixicon="RiSplitCellsHorizontal"\n className="size-4"\n />\n Unmerge Cells\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction NumberFormatSelect({\n disabled,\n onApplyStyle,\n value,\n}: {\n disabled: boolean\n onApplyStyle: (style: XlsxCellStyleInput) => void\n value: string\n}) {\n const hasMatchingOption = NUMBER_FORMAT_OPTIONS.some(\n (option) => option.value === value\n )\n const currentLabel = getNumberFormatLabel(value)\n const currentIcon = React.createElement(getNumberFormatIcon(value), {\n className: "size-4",\n })\n\n return (\n <Select\n value={value}\n onValueChange={(nextValue) => {\n if (!nextValue) return\n onApplyStyle(createNumberFormatStyle(nextValue))\n }}\n disabled={disabled}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[132px] min-w-[132px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Number format"\n >\n {currentIcon}\n <SelectValue placeholder="General" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {NUMBER_FORMAT_OPTIONS.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n <span className="flex min-w-0 items-center gap-2">\n <option.icon className="size-4" />\n <span className="truncate">{option.label}</span>\n </span>\n </SelectItem>\n ))}\n {!hasMatchingOption && value !== GENERAL_NUMBER_FORMAT_VALUE ? (\n <SelectItem value={value}>\n <span className="flex min-w-0 items-center gap-2">\n {currentIcon}\n <span className="truncate">{currentLabel}</span>\n </span>\n </SelectItem>\n ) : null}\n </SelectContent>\n </Select>\n )\n}\n\nfunction BorderMenu({\n borderColor,\n disabled,\n onApplyBorder,\n onBorderColorChange,\n}: {\n borderColor: string\n disabled: boolean\n onApplyBorder: (action: XlsxBorderAction) => void\n onBorderColorChange: (color: string) => void\n}) {\n const borderOptions = React.useMemo(() => createBorderOptions(), [])\n const edgeBorderOptions = borderOptions.filter(\n (option) =>\n option.action === "bottom" ||\n option.action === "left" ||\n option.action === "top" ||\n option.action === "right"\n )\n const groupedBorderOptions = borderOptions.filter(\n (option) =>\n option.action === "all" ||\n option.action === "outside" ||\n option.action === "none"\n )\n\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={disabled}\n aria-label="Cell borders"\n className="relative"\n >\n <IconPlaceholder\n lucide="Grid2x2"\n tabler="IconBorderAll"\n hugeicons="BorderAll01Icon"\n phosphor="GridFourIcon"\n remixicon="RiGridLine"\n className="size-4"\n />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: borderColor }}\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align="start"\n className={cn("w-48", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n {edgeBorderOptions.map((option) => (\n <StyleDropdownItem\n key={option.label}\n icon={option.icon}\n onClick={() => onApplyBorder(option.action)}\n >\n {option.label}\n </StyleDropdownItem>\n ))}\n <DropdownMenuSeparator />\n <DropdownMenuGroup>\n {groupedBorderOptions.map((option) => (\n <StyleDropdownItem\n key={option.label}\n icon={option.icon}\n onClick={() => onApplyBorder(option.action)}\n >\n {option.label}\n </StyleDropdownItem>\n ))}\n </DropdownMenuGroup>\n <DropdownMenuSeparator />\n <DropdownMenuSub>\n <DropdownMenuSubTrigger>\n <IconPlaceholder\n lucide="Baseline"\n tabler="IconTextColor"\n hugeicons="TextColorIcon"\n phosphor="TextAaIcon"\n remixicon="RiFontColor"\n className="size-4 text-muted-foreground"\n />\n Border color\n <span\n className="h-3 w-5 rounded-full border border-border"\n style={{ backgroundColor: borderColor }}\n />\n </DropdownMenuSubTrigger>\n <DropdownMenuSubContent\n className={cn("w-auto p-3", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <ColorPickerPanel\n label="Border color"\n color={borderColor}\n onChange={(color) =>\n onBorderColorChange(normalizeHexColor(color))\n }\n />\n </DropdownMenuSubContent>\n </DropdownMenuSub>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction AlignmentMoreMenu({\n disabled,\n onApplyStyle,\n}: {\n disabled: boolean\n onApplyStyle: (style: XlsxCellStyleInput) => void\n}) {\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={disabled}\n aria-label="More alignment"\n >\n <IconPlaceholder\n lucide="Ellipsis"\n tabler="IconDots"\n hugeicons="MoreHorizontalIcon"\n phosphor="DotsThreeIcon"\n remixicon="RiMoreLine"\n className="size-4"\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align="start"\n className={cn("w-48", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <StyleDropdownItem\n icon={TextWrapGlyph}\n onClick={() => onApplyStyle({ alignment: { wrapText: false } })}\n >\n Do not wrap\n </StyleDropdownItem>\n <StyleDropdownItem\n icon={TextWrapGlyph}\n onClick={() => onApplyStyle({ alignment: { shrinkToFit: true } })}\n >\n Shrink to fit\n </StyleDropdownItem>\n <StyleDropdownItem\n icon={TextWrapGlyph}\n onClick={() => onApplyStyle({ alignment: { shrinkToFit: false } })}\n >\n Do not shrink\n </StyleDropdownItem>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction EditorFileActionsMenu({\n canExport,\n exportXlsx,\n onUploadClick,\n}: {\n canExport: boolean\n exportXlsx: () => void\n onUploadClick: () => void\n}) {\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Open workbook actions"\n >\n <IconPlaceholder\n lucide="Ellipsis"\n tabler="IconDots"\n hugeicons="MoreHorizontalIcon"\n phosphor="DotsThreeIcon"\n remixicon="RiMoreLine"\n className="size-4"\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align="end"\n className={cn("w-40", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <DropdownMenuItem disabled={!canExport} onClick={exportXlsx}>\n <IconPlaceholder\n lucide="Download"\n tabler="IconDownload"\n hugeicons="Download01Icon"\n phosphor="DownloadSimpleIcon"\n remixicon="RiDownload2Line"\n className="size-4"\n />\n Download\n </DropdownMenuItem>\n <DropdownMenuItem onClick={onUploadClick}>\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction EditorToolbar({\n isDark,\n onIsDarkChange,\n onUploadClick,\n showNightRenderToggle,\n workbookIdentity,\n}: {\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n showNightRenderToggle: boolean\n workbookIdentity: string\n}) {\n const {\n activeSheet,\n activeSheetIndex,\n canExport,\n exportXlsx,\n getActiveWorksheet,\n revision,\n setActiveSheetIndex,\n sheets,\n } = useXlsxViewer()\n const { activeCell, activeCellAddress, selectRange, selection } =\n useXlsxViewerSelection()\n const {\n addSheet,\n canRedo,\n canUndo,\n mergeSelection,\n pasteStructuredClipboardData,\n readOnly,\n redo,\n removeActiveSheet,\n selectedFormula,\n selectedValue,\n setCellStyle,\n setCellFormula,\n setCellValue,\n setRangeStyle,\n setSelectedCellStyle,\n undo,\n unmergeSelection,\n } = useXlsxViewerEditing()\n const { canZoomIn, canZoomOut, setZoomScale, zoomIn, zoomOut, zoomScale } =\n useXlsxViewerZoom()\n const [formulaDraft, setFormulaDraft] = React.useState("")\n const [formulaFocused, setFormulaFocused] = React.useState(false)\n const [fontFamily, setFontFamily] = React.useState(DEFAULT_FONT_FAMILY)\n const [fontSize, setFontSize] = React.useState(11)\n const [textColor, setTextColor] = React.useState(DEFAULT_TEXT_COLOR)\n const [fillColor, setFillColor] = React.useState(DEFAULT_FILL_COLOR)\n const [borderColor, setBorderColor] = React.useState(DEFAULT_BORDER_COLOR)\n const [appliedMergeRegions, setAppliedMergeRegions] = React.useState<\n XlsxMergeRegion[]\n >([])\n const lastStyleTargetRef = React.useRef<{\n range: XlsxCellRange\n sheetIndex: number\n workbookIdentity: string\n } | null>(null)\n const formulaEditCellRef = React.useRef<typeof activeCell>(null)\n const formulaInitialValueRef = React.useRef("")\n const hasWorkbook = sheets.length > 0\n const hasSelection = Boolean(selection)\n const hasActiveCell = Boolean(activeCell)\n const canStyleSelection = (hasSelection || hasActiveCell) && !readOnly\n const activeRange = React.useMemo<XlsxCellRange | null>(() => {\n if (selection) return normalizeCellRange(selection)\n if (!activeCell) return null\n\n return {\n start: activeCell,\n end: activeCell,\n }\n }, [activeCell, selection])\n\n React.useEffect(() => {\n if (!activeRange) return\n\n lastStyleTargetRef.current = {\n range: activeRange,\n sheetIndex: activeSheetIndex,\n workbookIdentity,\n }\n }, [activeRange, activeSheetIndex, workbookIdentity])\n const worksheetMergeRegions = React.useMemo(() => {\n void revision\n\n return getWorksheetMergeRegions(\n getActiveWorksheet() as XlsxWorksheetWithMergeRegions | null\n )\n }, [getActiveWorksheet, revision])\n const mergeRegions = React.useMemo(\n () => [...worksheetMergeRegions, ...appliedMergeRegions],\n [appliedMergeRegions, worksheetMergeRegions]\n )\n const selectionIntersectsMerge = Boolean(\n activeRange &&\n mergeRegions.some((mergeRegion) =>\n rangesIntersect(activeRange, mergeRegion)\n )\n )\n\n React.useEffect(() => {\n if (\n appliedMergeRegions.length === 0 ||\n worksheetMergeRegions.length === 0\n ) {\n return\n }\n\n setAppliedMergeRegions((currentRegions) =>\n currentRegions.filter(\n (currentRegion) =>\n !worksheetMergeRegions.some((worksheetRegion) =>\n rangesIntersect(currentRegion, worksheetRegion)\n )\n )\n )\n }, [appliedMergeRegions.length, worksheetMergeRegions])\n\n React.useEffect(() => {\n setAppliedMergeRegions([])\n }, [activeSheetIndex])\n const selectionIsSingleCell = activeRange\n ? isSingleCellRange(activeRange)\n : true\n const selectionSpansMultipleColumns = activeRange\n ? activeRange.start.col !== activeRange.end.col\n : false\n const canMergeSelectedCells = Boolean(\n selection &&\n !readOnly &&\n !selectionIntersectsMerge &&\n !selectionIsSingleCell\n )\n const canMergeAcross = Boolean(\n selection &&\n !readOnly &&\n !selectionIntersectsMerge &&\n selectionSpansMultipleColumns\n )\n const canUnmergeSelectedCells = Boolean(\n selection && !readOnly && selectionIntersectsMerge\n )\n const currentZoom = Math.round(zoomScale)\n const selectedCellInputValue = selectedFormula || selectedValue\n\n React.useEffect(() => {\n if (formulaFocused) return\n setFormulaDraft(selectedCellInputValue)\n }, [formulaFocused, selectedCellInputValue, activeCellAddress])\n\n const activeCellStyle = React.useMemo(() => {\n // Worksheet style objects are mutable; revision invalidates this read after edits.\n void revision\n\n if (!activeCell) return null\n\n const worksheet = getActiveWorksheet()\n const inheritedStyle = resolveInheritedCellStyle(\n activeSheet,\n activeCell.row,\n activeCell.col\n )\n const cellStyle = worksheet?.getCellStyleAt(\n activeCell.row,\n activeCell.col\n ) as XlsxResolvedCellStyle | null | undefined\n\n return mergeResolvedCellStyle(inheritedStyle, cellStyle)\n }, [activeCell, activeSheet, getActiveWorksheet, revision])\n const fontToggleValues = React.useMemo(\n () => getFontToggleValuesFromStyle(activeCellStyle),\n [activeCellStyle]\n )\n const fontFamilyValue = getFontFamilyValue(activeCellStyle) ?? fontFamily\n const horizontalAlignmentValue = React.useMemo(\n () => getHorizontalAlignmentValue(activeCellStyle),\n [activeCellStyle]\n )\n const verticalAlignmentValue = React.useMemo(\n () => getVerticalAlignmentValue(activeCellStyle),\n [activeCellStyle]\n )\n const numberFormatValue = React.useMemo(\n () => getNumberFormatValue(activeCellStyle),\n [activeCellStyle]\n )\n\n const commitFormula = React.useCallback(() => {\n const targetCell = formulaEditCellRef.current ?? activeCell\n if (!targetCell) return\n if (formulaDraft === formulaInitialValueRef.current) return\n\n if (formulaDraft.trim().startsWith("=")) {\n setCellFormula(targetCell, formulaDraft)\n } else {\n setCellValue(targetCell, formulaDraft)\n }\n formulaInitialValueRef.current = formulaDraft\n }, [activeCell, formulaDraft, setCellFormula, setCellValue])\n\n const applyStyle = React.useCallback(\n (style: XlsxCellStyleInput) => {\n const applyRangeStyle = (range: XlsxCellRange) => {\n const normalizedRange = normalizeCellRange(range)\n const targetRanges = [\n normalizedRange,\n ...mergeRegions.filter((mergeRegion) =>\n rangesIntersect(normalizedRange, mergeRegion)\n ),\n ]\n const uniqueTargetRanges = new Map<string, XlsxCellRange>()\n\n targetRanges.forEach((targetRange) => {\n const normalizedTargetRange = normalizeCellRange(targetRange)\n uniqueTargetRanges.set(\n getRangeKey(normalizedTargetRange),\n normalizedTargetRange\n )\n })\n\n uniqueTargetRanges.forEach((targetRange) => {\n setRangeStyle(targetRange, style)\n })\n }\n\n if (selection) {\n const normalizedSelection = normalizeCellRange(selection)\n\n if (!isSingleCellRange(normalizedSelection)) {\n applyRangeStyle(normalizedSelection)\n return true\n }\n\n if (activeCell) {\n setSelectedCellStyle(style)\n return true\n }\n\n setCellStyle(normalizedSelection.start, style)\n return true\n }\n\n if (activeCell) {\n setSelectedCellStyle(style)\n return true\n }\n\n const fallbackTarget = lastStyleTargetRef.current\n const targetRange =\n fallbackTarget?.sheetIndex === activeSheetIndex &&\n fallbackTarget.workbookIdentity === workbookIdentity\n ? fallbackTarget.range\n : null\n\n if (!targetRange) return false\n\n if (isSingleCellRange(targetRange)) {\n setCellStyle(normalizeCellRange(targetRange).start, style)\n return true\n }\n\n applyRangeStyle(targetRange)\n return true\n },\n [\n activeCell,\n activeSheetIndex,\n mergeRegions,\n selection,\n setCellStyle,\n setRangeStyle,\n setSelectedCellStyle,\n workbookIdentity,\n ]\n )\n\n const applyBorderAction = React.useCallback(\n (action: XlsxBorderAction) => {\n if (!activeRange) return\n\n const normalizedRange = normalizeCellRange(activeRange)\n const edge = createBorderEdge(borderColor)\n const allBorderPatch = createBorderPatch({\n bottom: edge,\n left: edge,\n right: edge,\n top: edge,\n })\n\n if (action === "all") {\n setRangeStyle(normalizedRange, allBorderPatch)\n return\n }\n\n if (action === "none") {\n setRangeStyle(normalizedRange, createNoBorderPatch())\n return\n }\n\n if (action === "outside") {\n if (isSingleCellRange(normalizedRange)) {\n setCellStyle(normalizedRange.start, allBorderPatch)\n return\n }\n\n const outsideEdgeKeys: XlsxBorderEdgeKey[] = [\n "top",\n "bottom",\n "left",\n "right",\n ]\n\n outsideEdgeKeys.forEach((edgeKey) => {\n setRangeStyle(\n getBorderEdgeRange(normalizedRange, edgeKey),\n createBorderPatch({ [edgeKey]: edge })\n )\n })\n return\n }\n\n setRangeStyle(\n getBorderEdgeRange(normalizedRange, action),\n createBorderPatch({ [action]: edge })\n )\n },\n [activeRange, borderColor, setCellStyle, setRangeStyle]\n )\n\n const applyHorizontalAlignment = React.useCallback(\n (horizontal: HorizontalAlignmentToggleValue | undefined) => {\n if (!horizontal) return\n\n applyStyle({ alignment: { horizontal } })\n },\n [applyStyle]\n )\n\n const applyVerticalAlignment = React.useCallback(\n (vertical: VerticalAlignmentToggleValue | undefined) => {\n if (!vertical) return\n\n applyStyle({ alignment: { vertical } })\n },\n [applyStyle]\n )\n\n const mergeSelectedCells = React.useCallback(() => {\n if (!canMergeSelectedCells || !selection) return\n\n setAppliedMergeRegions([normalizeCellRange(selection)])\n mergeSelection()\n }, [canMergeSelectedCells, mergeSelection, selection])\n\n const mergeAcrossSelectedCells = React.useCallback(() => {\n if (!activeCell || !canMergeAcross || !selection) return\n\n const normalizedRange = normalizeCellRange(selection)\n const worksheet = getActiveWorksheet()\n if (!worksheet) return\n\n const formula = worksheet.getFormulaAt(activeCell.row, activeCell.col)\n const rawValue = worksheet.getCellAt(activeCell.row, activeCell.col).toJs()\n const colSpan = normalizedRange.end.col - normalizedRange.start.col + 1\n const rowSpan = normalizedRange.end.row - normalizedRange.start.row + 1\n const merges = Array.from({ length: rowSpan }, (_, rowOffset) => ({\n colOffset: normalizedRange.start.col - activeCell.col,\n colSpan,\n rowOffset: normalizedRange.start.row + rowOffset - activeCell.row,\n rowSpan: 1,\n }))\n const mergeRegionsByRow = Array.from({ length: rowSpan }, (_, rowOffset) =>\n normalizeCellRange({\n start: {\n col: normalizedRange.start.col,\n row: normalizedRange.start.row + rowOffset,\n },\n end: {\n col: normalizedRange.end.col,\n row: normalizedRange.start.row + rowOffset,\n },\n })\n )\n\n const didPaste = pasteStructuredClipboardData(\n JSON.stringify({\n cells: [\n formula\n ? { colOffset: 0, formula, rowOffset: 0 }\n : { colOffset: 0, rowOffset: 0, value: rawValue ?? "" },\n ],\n cols: colSpan,\n merges,\n rows: rowSpan,\n })\n )\n\n if (!didPaste) return\n\n setAppliedMergeRegions(mergeRegionsByRow)\n selectRange(normalizedRange)\n }, [\n activeCell,\n canMergeAcross,\n getActiveWorksheet,\n pasteStructuredClipboardData,\n selectRange,\n selection,\n ])\n\n const mergeAndCenterSelectedCells = React.useCallback(() => {\n if (!canMergeSelectedCells || !selection) return\n\n setAppliedMergeRegions([normalizeCellRange(selection)])\n setRangeStyle(selection, { alignment: { horizontal: "center" } })\n mergeSelection()\n }, [canMergeSelectedCells, mergeSelection, selection, setRangeStyle])\n\n const unmergeSelectedCells = React.useCallback(() => {\n if (!canUnmergeSelectedCells || !activeRange) return\n\n const worksheet =\n getActiveWorksheet() as XlsxWorksheetWithMergeRegions | null\n if (!worksheet?.unmergeCells) return\n\n const normalizedRange = normalizeCellRange(activeRange)\n const uniqueMergeRegions = new Map<string, XlsxMergeRegion>()\n\n ;[...worksheetMergeRegions, ...appliedMergeRegions].forEach(\n (mergeRegion) => {\n if (!rangesIntersect(normalizedRange, mergeRegion)) return\n\n uniqueMergeRegions.set(getRangeKey(mergeRegion), mergeRegion)\n }\n )\n\n let didUnmerge = false\n\n uniqueMergeRegions.forEach((mergeRegion) => {\n didUnmerge =\n worksheet.unmergeCells?.(rangeToA1(mergeRegion)) || didUnmerge\n })\n\n if (!didUnmerge) {\n unmergeSelection()\n return\n }\n\n setAppliedMergeRegions([])\n setRangeStyle(normalizedRange, {})\n selectRange(normalizedRange)\n }, [\n activeRange,\n appliedMergeRegions,\n canUnmergeSelectedCells,\n getActiveWorksheet,\n selectRange,\n setRangeStyle,\n unmergeSelection,\n worksheetMergeRegions,\n ])\n\n const applyFontToggleValues = React.useCallback(\n (nextValues: XlsxFontToggleValue[]) => {\n const previousValues = fontToggleValues\n const changedValue =\n nextValues.find((value) => !previousValues.includes(value)) ??\n previousValues.find((value) => !nextValues.includes(value))\n\n if (!changedValue) return\n\n const isPressed = nextValues.includes(changedValue)\n\n if (changedValue === "bold") {\n applyStyle({ font: { bold: isPressed } })\n } else if (changedValue === "italic") {\n applyStyle({ font: { italic: isPressed } })\n } else if (changedValue === "underline") {\n applyStyle({ font: { underline: isPressed ? "single" : "none" } })\n } else if (changedValue === "strikethrough") {\n applyStyle({ font: { strikethrough: isPressed } })\n }\n },\n [applyStyle, fontToggleValues]\n )\n\n return (\n <div className="border-b bg-background">\n <div className="flex min-h-11 items-center justify-between gap-3 border-b px-3">\n <div className="min-w-0 flex-1" />\n <TooltipProvider>\n <div className="flex shrink-0 items-center gap-1">\n {showNightRenderToggle ? (\n <>\n <ToolbarTooltip\n label={isDark ? "Use light workbook" : "Use dark workbook"}\n >\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label={\n isDark ? "Use light workbook" : "Use dark workbook"\n }\n onClick={() => onIsDarkChange(!isDark)}\n >\n {isDark ? (\n <Sun03Glyph className="size-4" />\n ) : (\n <Moon02Glyph className="size-4" />\n )}\n </Button>\n </ToolbarTooltip>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <EditorFileActionsMenu\n canExport={canExport}\n exportXlsx={exportXlsx}\n onUploadClick={onUploadClick}\n />\n </div>\n </TooltipProvider>\n </div>\n <TooltipProvider>\n <div className="flex min-h-12 flex-wrap items-center gap-2 border-b bg-background px-3 py-2">\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarTooltip label="Undo">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Undo"\n disabled={!canUndo || readOnly}\n onClick={undo}\n >\n <IconPlaceholder\n lucide="Undo2"\n tabler="IconArrowBackUp"\n hugeicons="Undo02Icon"\n phosphor="ArrowUUpLeftIcon"\n remixicon="RiArrowGoBackLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Redo">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Redo"\n disabled={!canRedo || readOnly}\n onClick={redo}\n >\n <IconPlaceholder\n lucide="Redo2"\n tabler="IconArrowForwardUp"\n hugeicons="Redo02Icon"\n phosphor="ArrowUUpRightIcon"\n remixicon="RiArrowGoForwardLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <Select\n value={fontFamilyValue}\n onValueChange={(value) => {\n if (!value) return\n\n if (applyStyle({ font: { name: value } })) {\n setFontFamily(value)\n }\n }}\n disabled={!canStyleSelection}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[132px] min-w-[132px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Font family"\n >\n <SelectValue placeholder="Font">{fontFamilyValue}</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {FONT_FAMILIES.map((option) => (\n <SelectItem key={option} value={option}>\n <span style={{ fontFamily: option }}>{option}</span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <Select\n value={String(fontSize)}\n onValueChange={(value) => {\n const nextFontSize = Number(value)\n if (!Number.isFinite(nextFontSize)) return\n\n setFontSize(nextFontSize)\n applyStyle({ font: { size: nextFontSize } })\n }}\n disabled={!canStyleSelection}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[78px] min-w-[78px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Font size"\n >\n <SelectValue placeholder="Size" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {FONT_SIZE_OPTIONS.map((size) => (\n <SelectItem key={size} value={String(size)}>\n {size} pt\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <ToolbarSeparator />\n <ToggleGroup\n className="shrink-0"\n disabled={!canStyleSelection}\n multiple\n spacing="default"\n value={fontToggleValues}\n onValueChange={(value) =>\n applyFontToggleValues(value as XlsxFontToggleValue[])\n }\n >\n <ToolbarTooltip label="Bold">\n <ToggleGroupItem aria-label="Bold" size="sm" value="bold">\n <IconPlaceholder\n lucide="Bold"\n tabler="IconBold"\n hugeicons="TextBoldIcon"\n phosphor="TextBIcon"\n remixicon="RiBold"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Italic">\n <ToggleGroupItem aria-label="Italic" size="sm" value="italic">\n <IconPlaceholder\n lucide="Italic"\n tabler="IconItalic"\n hugeicons="TextItalicIcon"\n phosphor="TextItalicIcon"\n remixicon="RiItalic"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Underline">\n <ToggleGroupItem\n aria-label="Underline"\n size="sm"\n value="underline"\n >\n <IconPlaceholder\n lucide="Underline"\n tabler="IconUnderline"\n hugeicons="TextUnderlineIcon"\n phosphor="TextUnderlineIcon"\n remixicon="RiUnderline"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Strikethrough">\n <ToggleGroupItem\n aria-label="Strikethrough"\n size="sm"\n value="strikethrough"\n >\n <IconPlaceholder\n lucide="Strikethrough"\n tabler="IconStrikethrough"\n hugeicons="TextStrikethroughIcon"\n phosphor="TextStrikethroughIcon"\n remixicon="RiStrikethrough"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n </ToggleGroup>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <ColorPicker\n label="Text color"\n icon={TextColorGlyph}\n color={textColor}\n disabled={!canStyleSelection}\n onChange={(color) => {\n const nextColor = normalizeHexColor(color)\n setTextColor(nextColor)\n applyStyle({ font: { color: toXlsxRgbColor(nextColor) } })\n }}\n />\n <ColorPicker\n label="Fill color"\n icon={PaintBucketGlyph}\n color={fillColor}\n disabled={!canStyleSelection}\n onChange={(color) => {\n const nextColor = normalizeHexColor(color, DEFAULT_FILL_COLOR)\n setFillColor(nextColor)\n applyStyle({\n fill: {\n color: toXlsxRgbColor(nextColor),\n fillType: "solid",\n },\n })\n }}\n />\n <ToolbarIconButton\n label="No fill"\n disabled={!canStyleSelection}\n onClick={() => applyStyle({ fill: { fillType: "none" } })}\n >\n <IconPlaceholder\n lucide="DropletOff"\n tabler="IconDropletOff"\n hugeicons="DropletOffIcon"\n phosphor="DropSlashIcon"\n remixicon="RiDropLine"\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <ToggleGroup\n className="shrink-0"\n disabled={!canStyleSelection}\n spacing="default"\n value={horizontalAlignmentValue}\n >\n <ToolbarTooltip label="Align left">\n <ToggleGroupItem\n aria-label="Align left"\n size="sm"\n value="left"\n onClick={() => applyHorizontalAlignment("left")}\n >\n <IconPlaceholder\n lucide="AlignLeft"\n tabler="IconAlignLeft"\n hugeicons="TextAlignLeft01Icon"\n phosphor="TextAlignLeftIcon"\n remixicon="RiAlignLeft"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Align center">\n <ToggleGroupItem\n aria-label="Align center"\n size="sm"\n value="center"\n onClick={() => applyHorizontalAlignment("center")}\n >\n <IconPlaceholder\n lucide="AlignCenter"\n tabler="IconAlignCenter"\n hugeicons="TextAlignCenterIcon"\n phosphor="TextAlignCenterIcon"\n remixicon="RiAlignCenter"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Align right">\n <ToggleGroupItem\n aria-label="Align right"\n size="sm"\n value="right"\n onClick={() => applyHorizontalAlignment("right")}\n >\n <IconPlaceholder\n lucide="AlignRight"\n tabler="IconAlignRight"\n hugeicons="TextAlignRight01Icon"\n phosphor="TextAlignRightIcon"\n remixicon="RiAlignRight"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n </ToggleGroup>\n <ToggleGroup\n className="shrink-0"\n disabled={!canStyleSelection}\n spacing="default"\n value={verticalAlignmentValue}\n >\n <ToolbarTooltip label="Align top">\n <ToggleGroupItem\n aria-label="Align top"\n size="sm"\n value="top"\n onClick={() => applyVerticalAlignment("top")}\n >\n <IconPlaceholder\n lucide="AlignVerticalJustifyStart"\n tabler="IconAlignBoxTopCenter"\n hugeicons="AlignBoxTopCenterIcon"\n phosphor="AlignTopIcon"\n remixicon="RiAlignTop"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Align middle">\n <ToggleGroupItem\n aria-label="Align middle"\n size="sm"\n value="center"\n onClick={() => applyVerticalAlignment("center")}\n >\n <IconPlaceholder\n lucide="AlignVerticalJustifyCenter"\n tabler="IconAlignBoxCenterMiddle"\n hugeicons="AlignBoxMiddleCenterIcon"\n phosphor="AlignCenterVerticalIcon"\n remixicon="RiAlignVertically"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Align bottom">\n <ToggleGroupItem\n aria-label="Align bottom"\n size="sm"\n value="bottom"\n onClick={() => applyVerticalAlignment("bottom")}\n >\n <IconPlaceholder\n lucide="AlignVerticalJustifyEnd"\n tabler="IconAlignBoxBottomCenter"\n hugeicons="AlignBoxBottomCenterIcon"\n phosphor="AlignBottomIcon"\n remixicon="RiAlignBottom"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n </ToggleGroup>\n <ToolbarIconButton\n label="Wrap text"\n disabled={!canStyleSelection}\n onClick={() => applyStyle({ alignment: { wrapText: true } })}\n >\n <IconPlaceholder\n lucide="WrapText"\n tabler="IconTextWrap"\n hugeicons="TextWrapIcon"\n phosphor="ArrowElbowDownLeftIcon"\n remixicon="RiTextWrap"\n className="size-4"\n />\n </ToolbarIconButton>\n <AlignmentMoreMenu\n disabled={!canStyleSelection}\n onApplyStyle={applyStyle}\n />\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <NumberFormatSelect\n disabled={!canStyleSelection}\n onApplyStyle={applyStyle}\n value={numberFormatValue}\n />\n <BorderMenu\n borderColor={borderColor}\n disabled={!canStyleSelection}\n onApplyBorder={applyBorderAction}\n onBorderColorChange={setBorderColor}\n />\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <MergeCellsMenu\n canMerge={canMergeSelectedCells}\n canMergeAcross={canMergeAcross}\n canUnmerge={canUnmergeSelectedCells}\n disabled={!hasSelection || readOnly}\n isMerged={selectionIntersectsMerge}\n onMergeAcross={mergeAcrossSelectedCells}\n onMergeAndCenter={mergeAndCenterSelectedCells}\n onMergeCells={mergeSelectedCells}\n onUnmergeCells={unmergeSelectedCells}\n />\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarTooltip label="Add sheet">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Add sheet"\n disabled={!hasWorkbook || readOnly}\n onClick={() => addSheet()}\n >\n <IconPlaceholder\n lucide="Plus"\n tabler="IconPlus"\n hugeicons="Add01Icon"\n phosphor="PlusIcon"\n remixicon="RiAddLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Remove active sheet">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Remove active sheet"\n disabled={sheets.length <= 1 || readOnly}\n onClick={removeActiveSheet}\n >\n <IconPlaceholder\n lucide="Trash2Icon"\n tabler="IconTrash"\n hugeicons="Delete02Icon"\n phosphor="TrashIcon"\n remixicon="RiDeleteBinLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={String(activeSheetIndex)}\n onValueChange={(value) => setActiveSheetIndex(Number(value))}\n disabled={!hasWorkbook}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[150px] min-w-[150px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Active sheet"\n >\n <SelectValue>{activeSheet?.name ?? "Sheet"}</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="start"\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {sheets.map((sheet, index) => (\n <SelectItem\n key={`${sheet.name}-${index}`}\n value={String(index)}\n >\n {sheet.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <ToolbarSeparator />\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={!hasWorkbook || !canZoomOut}\n aria-label="Zoom out"\n onClick={zoomOut}\n >\n <IconPlaceholder\n lucide="CircleMinus"\n tabler="IconCircleMinus"\n hugeicons="MinusSignCircleIcon"\n phosphor="MinusCircleIcon"\n remixicon="RiIndeterminateCircleLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={currentZoom.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={!hasWorkbook}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[84px] min-w-[84px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Zoom level"\n >\n <SelectValue>{currentZoom}%</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="end"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={!hasWorkbook || !canZoomIn}\n aria-label="Zoom in"\n onClick={zoomIn}\n >\n <IconPlaceholder\n lucide="CirclePlusIcon"\n tabler="IconCirclePlusFilled"\n hugeicons="PlusSignCircleIcon"\n phosphor="PlusCircleIcon"\n remixicon="RiAddCircleFill"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n </div>\n <div className="border-t bg-background px-2 py-1">\n <Group className="w-full">\n <Input\n className={cn(\n "h-8 w-[92px] shrink-0 font-mono text-xs",\n XLSX_EDITOR_FORMULA_INPUT_CHROME_CLASS\n )}\n readOnly\n value={activeCellAddress ?? ""}\n />\n <GroupSeparator />\n <GroupText className="h-8 w-9 shrink-0 justify-center px-0 text-[11px] font-semibold italic">\n fx\n </GroupText>\n <GroupSeparator />\n <Input\n className={cn(\n "h-8 flex-1",\n XLSX_EDITOR_FORMULA_INPUT_CHROME_CLASS\n )}\n disabled={!hasActiveCell || readOnly}\n value={formulaDraft}\n onBlur={() => {\n commitFormula()\n setFormulaFocused(false)\n }}\n onChange={(event) => setFormulaDraft(event.target.value)}\n onFocus={() => {\n formulaEditCellRef.current = activeCell\n formulaInitialValueRef.current = formulaDraft\n setFormulaFocused(true)\n }}\n onKeyDown={(event) => {\n if (event.key === "Enter") {\n event.preventDefault()\n commitFormula()\n setFormulaFocused(false)\n }\n }}\n placeholder="Select a cell, then enter a value or formula"\n />\n </Group>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nexport function XlsxEditorSurface({\n className,\n isDark,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n showNightRenderToggle,\n workbookIdentity,\n}: {\n className?: string\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n showNightRenderToggle: boolean\n workbookIdentity: string\n}) {\n const { error } = useXlsxViewer()\n\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <EditorToolbar\n isDark={isDark}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n showNightRenderToggle={showNightRenderToggle}\n workbookIdentity={workbookIdentity}\n />\n <div className="flex min-h-0 flex-1 flex-col">\n <div className="min-h-0 flex-1 bg-muted/20">\n <XlsxViewer\n allowResizeInReadOnly\n className="h-full min-h-0 min-w-0"\n height="100%"\n isDark={isDark}\n readOnly={false}\n rounded={false}\n showDefaultToolbar={false}\n showImages\n fileTooLargeState={\n <div className="grid h-full w-full min-w-full place-items-center p-6">\n <div className="max-w-sm rounded-lg border bg-background p-4 text-sm">\n <p className="font-medium">File too large for editing</p>\n <p className="mt-1 text-muted-foreground">\n This workbook exceeds the editor limit. Download it or open\n a smaller file to make changes.\n </p>\n </div>\n </div>\n }\n loadingState={<EditorLoadingSurface />}\n renderScroller={renderXlsxScroller}\n errorState={\n <div className="grid h-full w-full min-w-full place-items-center p-6 text-sm text-destructive">\n {error?.message ?? "Unable to edit workbook."}\n </div>\n }\n renderTableHeaderMenu={renderTableHeaderMenu}\n />\n </div>\n <WorkbookSheetTabs workbookIdentity={workbookIdentity} />\n </div>\n </div>\n )\n}\n\nexport function XlsxEditorPreview({\n className,\n fileName,\n isDark,\n onIsDarkChange,\n src,\n}: {\n className?: string\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n src?: string\n}) {\n return (\n <XlsxEditorContent\n className={className}\n effectiveIsDark={isDark}\n fileName={fileName}\n setNightRenderEnabled={onIsDarkChange}\n shouldRenderNightMode\n url={src}\n />\n )\n}\n\nfunction XlsxEditorContent({\n className,\n effectiveIsDark,\n fileName,\n setNightRenderEnabled,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n effectiveIsDark: boolean\n fileName?: string\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const [uploadedWorkbook, setUploadedWorkbook] =\n React.useState<UploadedWorkbook | null>(null)\n const [workbookBuffer, setWorkbookBuffer] =\n React.useState<ArrayBuffer | null>(null)\n const [loadError, setLoadError] = React.useState<string>()\n const sourceFileName = React.useMemo(\n () =>\n url ? formatWorkbookName(fileName, url) : (fileName ?? "workbook.xlsx"),\n [fileName, url]\n )\n const displayFileName = uploadedWorkbook?.fileName ?? sourceFileName\n const workbookIdentity =\n uploadedWorkbook?.identity ?? `${url ?? "empty"}::${displayFileName}`\n const shouldShowLoadingSpinner = useDelayedLoadingIndicator(\n !workbookBuffer && !loadError && !uploadedWorkbook,\n XLSX_LOADING_INDICATOR_DELAY_MS\n )\n\n React.useEffect(() => {\n let isCurrent = true\n\n if (url) {\n setUploadedWorkbook(null)\n }\n\n async function loadWorkbook(): Promise<void> {\n if (!url) {\n setWorkbookBuffer(null)\n setLoadError(undefined)\n return\n }\n\n setWorkbookBuffer(null)\n setLoadError(undefined)\n\n try {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch XLSX (${response.status})`)\n }\n\n const nextWorkbookBuffer = await response.arrayBuffer()\n if (!isCurrent) return\n\n setWorkbookBuffer(nextWorkbookBuffer)\n } catch (error) {\n if (!isCurrent) return\n\n setLoadError(\n error instanceof Error ? error.message : "Unknown XLSX load error"\n )\n }\n }\n\n void loadWorkbook()\n\n return () => {\n isCurrent = false\n }\n }, [url])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n const buffer = await file.arrayBuffer()\n setWorkbookBuffer(null)\n setLoadError(undefined)\n setUploadedWorkbook({\n buffer,\n fileName: file.name,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n const activeBuffer = uploadedWorkbook?.buffer ?? workbookBuffer\n\n if (!url && !uploadedWorkbook) {\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <div className="grid min-h-0 flex-1 place-items-center bg-muted/30 p-4">\n <div className="max-w-md rounded-lg border bg-background p-4 text-center text-sm shadow-xs">\n <p className="font-medium">Upload a workbook to edit</p>\n <p className="mt-1 text-muted-foreground">\n Pass an XLSX URL with the <code>src</code> prop or upload a local\n file.\n </p>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (loadError && !activeBuffer) {\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <div className="grid min-h-0 flex-1 place-items-center bg-muted/30 p-4">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm">\n <p className="font-medium">Unable to edit workbook</p>\n <p className="mt-1 text-muted-foreground">{loadError}</p>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (!activeBuffer) {\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <EditorLoadingSurface showSpinner={shouldShowLoadingSpinner} />\n </div>\n )\n }\n\n return (\n <div className={cn("overflow-hidden", className)}>\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <XlsxWorkbookLoadedEditor\n fileName={displayFileName}\n isDark={effectiveIsDark}\n onIsDarkChange={setNightRenderEnabled}\n onUploadClick={() => fileInputRef.current?.click()}\n renderTableHeaderMenu={(props) => (\n <WorkbookTableHeaderMenu {...props} />\n )}\n showNightRenderToggle={shouldRenderNightMode}\n workbookBuffer={activeBuffer}\n workbookIdentity={workbookIdentity}\n />\n </div>\n )\n}\n\nfunction XlsxWorkbookLoadedEditor({\n fileName,\n isDark,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n showNightRenderToggle,\n workbookBuffer,\n workbookIdentity,\n}: {\n fileName: string\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n showNightRenderToggle: boolean\n workbookBuffer: ArrayBuffer\n workbookIdentity: string\n}) {\n const controller = useXlsxViewerController(\n React.useMemo(\n () => ({\n allowResizeInReadOnly: true,\n file: workbookBuffer,\n fileName,\n readOnly: false,\n readOnlyAboveBytes: XLSX_EDITOR_READ_ONLY_THRESHOLD_BYTES,\n useWorker: true,\n }),\n [fileName, workbookBuffer]\n )\n )\n\n return (\n <XlsxViewerProvider controller={controller} isDark={isDark}>\n <XlsxEditorSurface\n isDark={isDark}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n renderTableHeaderMenu={renderTableHeaderMenu}\n showNightRenderToggle={showNightRenderToggle}\n workbookIdentity={workbookIdentity}\n />\n </XlsxViewerProvider>\n )\n}\n'export function XlsxEditorSource() {return (diff --git a/apps/v4/content/docs/components/meta.json b/apps/v4/content/docs/components/meta.jsonindex 649920d..17ef506 100644--- a/apps/v4/content/docs/components/meta.json+++ b/apps/v4/content/docs/components/meta.json@@ -3,6 +3,7 @@"pages": ["index","[PDF Viewer](/docs/components/pdf-viewer)",+ "[PDF Editor](/docs/components/pdf-editor)","[DOCX Viewer](/docs/components/docx-viewer)","[DOCX Editor](/docs/components/docx-editor)","[Excel Viewer](/docs/components/xlsx-viewer)",diff --git a/apps/v4/content/docs/components/pdf-editor.mdx b/apps/v4/content/docs/components/pdf-editor.mdxnew file mode 100644index 0000000..c1824d3--- /dev/null+++ b/apps/v4/content/docs/components/pdf-editor.mdx@@ -0,0 +1,203 @@+---+title: React PDF Editor+description: A React PDF editor with annotations, comments, redaction, form filling and design, signatures, rubber stamps, page organization, security, printing, and export, built on EmbedPDF.+component: true+featured: true+---++The React PDF Editor extends the PDF Viewer into a complete editing surface. It wires up every stable EmbedPDF plugin behind a shadcn-style toolbar, contextual side panels, and selection menus, and leaves persistence to your app through annotation JSON, form values, and PDF bytes.++<PdfEditorDemo />++## About++PDF rendering and editing are powered by [EmbedPDF](https://www.embedpdf.com/). The editor registers the annotation, redaction, form, signature, stamp, history, bookmark, attachment, capture, print, export, fullscreen, pan, spread, rotate, search, selection, thumbnail, and zoom plugins on top of the shared PDFium engine used by the viewer.++## Installation++<CodeTabs>++<TabsList>+ <TabsTrigger value="cli">Command</TabsTrigger>+ <TabsTrigger value="manual">Manual</TabsTrigger>+</TabsList>+<TabsContent value="cli">++```bash+npx shadcn@latest add @extend/pdf-editor+```++</TabsContent>++<TabsContent value="manual">++<Steps className="mb-0 pt-2">++<Step>Install the following dependencies:</Step>++```bash+npm install @embedpdf/core@^2.15.0 @embedpdf/engines@^2.15.0 @embedpdf/models@^2.15.0 @embedpdf/plugin-annotation@^2.15.0 @embedpdf/plugin-attachment@^2.15.0 @embedpdf/plugin-bookmark@^2.15.0 @embedpdf/plugin-capture@^2.15.0 @embedpdf/plugin-document-manager@^2.15.0 @embedpdf/plugin-export@^2.15.0 @embedpdf/plugin-form@^2.15.0 @embedpdf/plugin-fullscreen@^2.15.0 @embedpdf/plugin-history@^2.15.0 @embedpdf/plugin-interaction-manager@^2.15.0 @embedpdf/plugin-pan@^2.15.0 @embedpdf/plugin-print@^2.15.0 @embedpdf/plugin-redaction@^2.15.0 @embedpdf/plugin-render@^2.15.0 @embedpdf/plugin-rotate@^2.15.0 @embedpdf/plugin-scroll@^2.15.0 @embedpdf/plugin-search@^2.15.0 @embedpdf/plugin-selection@^2.15.0 @embedpdf/plugin-signature@^2.15.0 @embedpdf/plugin-spread@^2.15.0 @embedpdf/plugin-stamp@^2.15.0 @embedpdf/plugin-thumbnail@^2.15.0 @embedpdf/plugin-tiling@^2.15.0 @embedpdf/plugin-viewport@^2.15.0 @embedpdf/plugin-zoom@^2.15.0 pdf-lib@^1.17.1+```++<Step>Install the icon library configured in your `components.json`:</Step>++The component source references icons through the shadcn CLI's+`IconPlaceholder`, which supports every `iconLibrary` the CLI does: `lucide`,+`tabler`, `hugeicons`, `phosphor`, and `remixicon`. Installing with the CLI+replaces each placeholder with the matching icon from your configured library,+so make sure that library's package is installed. When copying the source+manually, replace each `IconPlaceholder` element with the icon named by the+prop for your library.++<Step>+ Install the Color Picker and Document Viewer Sidebar components because the+ editor reuses them for the style panel and thumbnail rail.+</Step>++```bash+npx shadcn@latest add @extend/color-picker @extend/document-viewer-sidebar+```++<Step>Copy and paste the following files into your project.</Step>++<PdfEditorSource />++<Step>Update the import paths to match your project setup.</Step>++</Steps>++</TabsContent>++</CodeTabs>++## Modes++The ribbon below the main toolbar switches between five modes. Each mode exposes its own tools and opens a matching side panel.++| Mode | Tools |+| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `view` | Select, hand (pan), zoom to area, capture area as image, single or two-page spreads, vertical or horizontal scrolling. |+| `annotate` | Highlight, underline, strikethrough, squiggly, pen, highlighter pen, text box, callout, sticky note, rectangle, ellipse, line, arrow, polyline, polygon, image, link area, insert-text and replace-text marks, rubber stamps, and the style panel. |+| `sign` | Draw, type, or upload signatures and initials, then click to place them. Includes quick text, date, and freehand tools. |+| `forms` | Fill existing AcroForm fields, or switch to design mode to add and configure text fields, checkboxes, radio buttons, dropdowns, and list boxes. Import, export, and clear values as JSON. |+| `redact` | Mark text or areas for redaction, review pending marks, change their colors and overlay text, then permanently apply them. |++## Useful behaviors++- Text selection opens a floating menu with copy, markup, comment, link, and redaction actions plus any custom `selectionActions` you pass in. Custom actions receive the selected text and page-relative coordinates in PDF points and percentages.+- Selected annotations get a contextual menu for comments, styling, links, locking, saving as a stamp, and deletion. Multi-selections can be grouped and ungrouped.+- Undo and redo cover annotations, form edits, and redaction marks through the history plugin.+- The left sidebar hosts thumbnails, the bookmark outline, embedded attachments, and a page organizer that rotates, reorders, inserts, deletes, extracts, and appends pages.+- The right panel hosts annotation properties, comment threads, pending redactions, rubber stamp libraries, saved signatures, and form fields.+- The document menu covers download, print, capture, full screen, document properties, password protection and permissions, flattening, and annotation JSON import and export.+- Uploaded files replace the current document. Page operations, flattening, and encryption changes are written into the PDF bytes returned by `getDocumentBuffer` and `download`.++## API Reference++### PDFEditor++| Prop | Type | Default | Required |+| ----------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------ | -------- |+| `src` | `string \| ArrayBuffer \| Uint8Array \| Blob` | `-` | No |+| `fileName` | `string` | Derived from `src` | No |+| `className` | `string` | `-` | No |+| `defaultZoom` | `number \| "fit-page" \| "fit-width" \| "automatic"` | `"fit-width"` | No |+| `defaultMode` | `"view" \| "annotate" \| "sign" \| "forms" \| "redact"` | `"view"` | No |+| `annotationAuthor` | `string` | `"Guest"` | No |+| `colorPresets` | `string[]` | Eleven hex colors | No |+| `features` | `PdfEditorFeatureFlags` | Everything enabled | No |+| `showToolbar` | `boolean` | `true` | No |+| `showUpload` | `boolean` | `true` | No |+| `showDownload` | `boolean` | `true` | No |+| `toolbarActions` | `React.ReactNode` | `-` | No |+| `selectionActions` | `PdfEditorSelectionAction[]` | `[]` | No |+| `persistSignatures` | `boolean \| string` | `true` (localStorage) | No |+| `stampManifests` | `string[]` | EmbedPDF default stamps | No |+| `signatureFontsStylesheetUrl` | `string \| null` | Google Fonts handwriting styles | No |+| `resolveScrollAreaViewport` | `(container: HTMLDivElement) => HTMLDivElement \| null` | Finds `[data-slot="scroll-area-viewport"]` | No |+| `renderPageOverlay` | `(props: PDFEditorPageOverlayProps) => React.ReactNode` | `-` | No |+| `onDocumentLoadSuccess` | `(info: { numPages: number; documentId: string; fileName: string }) => void` | `-` | No |+| `onDocumentLoadError` | `(message: string) => void` | `-` | No |+| `onActivePageChange` | `(pageNumber: number) => void` | `-` | No |+| `onModeChange` | `(mode: PdfEditorMode) => void` | `-` | No |+| `onAnnotationEvent` | `(event: AnnotationEvent) => void` | `-` | No |+| `onAnnotationsChange` | `(items: AnnotationTransferItem[]) => void` | `-` | No |+| `onFormValuesChange` | `(values: Record<string, string>) => void` | `-` | No |+| `onRedactionsApplied` | `() => void` | `-` | No |+| `onSave` | `(result: { buffer: ArrayBuffer; fileName: string }) => void` | `-` | No |+| `onCapture` | `(event: CaptureAreaEvent) => void` | `-` | No |+| `onPdfUpload` | `(file: File) => void` | `-` | No |+| `onToast` | `(toast: { message: string; tone: "info" \| "success" \| "error" }) => void` | Built-in bottom-right toast | No |+| `onSelectionAction` | `(actionId: string, payload: PdfEditorSelectionPayload) => void` | `-` | No |++`features` accepts booleans for `annotate`, `redact`, `forms`, `sign`, `stamps`, `pages`, `security`, `print`, `capture`, `outline`, `attachments`, `comments`, and `fullscreen`. Disabled features disappear from the toolbar, menus, and panels.++The built-in toast viewport is scoped to the bottom-right corner of the editor. Pass `onToast` to route notices into an existing shadcn-compatible toast setup instead; when provided, the built-in toast is skipped.++### Imperative handle++Pass a `ref` to call into the editor from your own UI.++| Method | Description |+| ------------------------------- | ------------------------------------------------------------------------------------------------ |+| `getDocumentBuffer()` | Resolves the current PDF bytes including annotations, form values, and pending security changes. |+| `download(fileName?)` | Saves the document through the browser. |+| `print(options?)` | Opens the print dialog with optional `pageRange` and `includeAnnotations`. |+| `exportAnnotations()` | Resolves every annotation as `AnnotationTransferItem[]` (stamps include their image data). |+| `importAnnotations(items)` | Adds previously exported annotations to the document. |+| `getFormValues()` | Returns a `Record<string, string>` of field names and values. |+| `setFormValues(values)` | Fills form fields by name. |+| `applyRedactions()` | Permanently applies every pending redaction mark. |+| `setMode(mode)` | Switches the editing mode. |+| `setActiveTool(toolId \| null)` | Activates an EmbedPDF tool id such as `highlight`, `ink`, or `formTextField`. |+| `scrollToPage(pageNumber)` | Scrolls to a page. |+| `undo()` / `redo()` | Steps through the history stack. |+| `getViewportElement()` | Returns the scrolling viewport element. |++### Selection actions++Custom selection actions turn the editor into a review surface. Each action receives the selected text along with the bounding box in PDF points and as percentages of the page, so the host app can create citations, extract fields, or file approvals without touching the PDF.++```tsx+<PDFEditor+ src="/contracts/msa.pdf"+ selectionActions={[+ {+ id: "cite",+ label: "Create citation",+ onSelect: ({ pageNumber, text, normalizedRect }) => {+ createCitation({ pageNumber, text, ...normalizedRect })+ },+ },+ {+ id: "extract",+ label: "Extract as field",+ keepSelection: true,+ onSelect: (payload) => openFieldPicker(payload),+ },+ ]}+/>+```++`PdfEditorSelectionPayload` contains `documentId`, `pageIndex`, `pageNumber`, `pageSize`, `text`, `rect`, `rects`, `normalizedRect`, `normalizedRects`, and a `pages` array for selections that span multiple pages.++### Keyboard shortcuts++| Keys | Action |+| ------------------- | ------------------------------------------- |+| `⌘ S` / `Ctrl S` | Download |+| `⌘ P` / `Ctrl P` | Print |+| `⌘ F` / `Ctrl F` | Search |+| `⌘ Z`, `⇧ ⌘ Z` | Undo, redo |+| `⌘ =`, `⌘ -`, `⌘ 0` | Zoom in, zoom out, fit page |+| `V`, `H` | Select tool, hand tool |+| `Esc` | Cancel the active tool and clear selection |+| `Delete` | Delete the selected annotations |+| `⌘ A` / `Ctrl A` | Select every annotation on the current page |++## Notes++- Redaction, flattening, and page deletion are destructive. The editor asks for confirmation and, once applied, the removed content cannot be restored with undo.+- Password protection and permission restrictions are staged in memory and written into the PDF when it is downloaded or read through `getDocumentBuffer`.+- Page organization rewrites and reopens the document, which clears the undo history. Protected documents must have their protection removed before pages can be reorganized.+- Saved signatures persist in `localStorage` under `pdf-editor:signatures` unless `persistSignatures` is `false` or set to a custom key.diff --git a/apps/v4/content/docs/components/pdf-viewer.mdx b/apps/v4/content/docs/components/pdf-viewer.mdxindex 6f63686..98c9e05 100644--- a/apps/v4/content/docs/components/pdf-viewer.mdx+++ b/apps/v4/content/docs/components/pdf-viewer.mdx@@ -36,7 +36,7 @@ npx shadcn@latest add @extend/pdf-viewer<Step>Install the following dependencies:</Step>```bash-npm install @embedpdf/core@^2.14.4 @embedpdf/engines@^2.14.4 @embedpdf/models@^2.14.4 @embedpdf/plugin-document-manager@^2.14.4 @embedpdf/plugin-interaction-manager@^2.14.4 @embedpdf/plugin-render@^2.14.4 @embedpdf/plugin-rotate@^2.14.4 @embedpdf/plugin-scroll@^2.14.4 @embedpdf/plugin-search@^2.14.4 @embedpdf/plugin-selection@^2.14.4 @embedpdf/plugin-thumbnail@^2.14.4 @embedpdf/plugin-tiling@^2.14.4 @embedpdf/plugin-viewport@^2.14.4 @embedpdf/plugin-zoom@^2.14.4 pdf-lib@^1.17.1+npm install @embedpdf/core@^2.15.0 @embedpdf/engines@^2.15.0 @embedpdf/models@^2.15.0 @embedpdf/plugin-document-manager@^2.15.0 @embedpdf/plugin-interaction-manager@^2.15.0 @embedpdf/plugin-render@^2.15.0 @embedpdf/plugin-rotate@^2.15.0 @embedpdf/plugin-scroll@^2.15.0 @embedpdf/plugin-search@^2.15.0 @embedpdf/plugin-selection@^2.15.0 @embedpdf/plugin-thumbnail@^2.15.0 @embedpdf/plugin-tiling@^2.15.0 @embedpdf/plugin-viewport@^2.15.0 @embedpdf/plugin-zoom@^2.15.0 pdf-lib@^1.17.1```<Step>Install the icon library configured in your `components.json`:</Step>diff --git a/apps/v4/lib/block-code-samples.ts b/apps/v4/lib/block-code-samples.tsindex 92d78bb..6901df5 100644--- a/apps/v4/lib/block-code-samples.ts+++ b/apps/v4/lib/block-code-samples.ts@@ -31,6 +31,7 @@ export const blockIds = ["document-splits","excel-editor","docx-editor-block",+ "pdf-editor-block","file-system",]@@ -54,6 +55,7 @@ const blockCodeDependencies: Record<string, string[]> = {],"excel-editor": ["xlsx-editor"],"docx-editor-block": ["docx-editor", "file-thumbnail"],+ "pdf-editor-block": ["pdf-editor", "document-viewer-sidebar", "color-picker"],"file-system": ["file-system","file-thumbnail",diff --git a/apps/v4/lib/color-picker-utils.ts b/apps/v4/lib/color-picker-utils.tsnew file mode 100644index 0000000..2d0681c--- /dev/null+++ b/apps/v4/lib/color-picker-utils.ts@@ -0,0 +1,763 @@+export type ColorFormat = "oklch" | "hsl" | "rgb" | "hex"++/** 0-255 floats. */+export interface RgbColor {+ r: number+ g: number+ b: number+}++/** h in 0-360, s/l in 0-100. */+export interface HslColor {+ h: number+ s: number+ l: number+}++/** h in 0-360, s/v in 0-100. */+export interface HsvColor {+ h: number+ s: number+ v: number+}++/** L: 0-1; C: >= 0; H: 0-360. */+export interface OklchColor {+ l: number+ c: number+ h: number+}++export interface ParsedColor {+ rgb: RgbColor+ alpha: number | null+ format: ColorFormat | null+}++export interface ColorParts {+ rgb: RgbColor+ hsl: HslColor+ oklch: OklchColor+ alpha: number+}++export function clamp(value: number, min: number, max: number): number {+ return Math.min(max, Math.max(min, value))+}++export function normalizeHue(value: number): number {+ return ((value % 360) + 360) % 360+}++export function hsvToRgb({ h, s, v }: HsvColor): RgbColor {+ const hue = normalizeHue(h) / 60+ const sat = clamp(s, 0, 100) / 100+ const val = clamp(v, 0, 100) / 100+ const sector = Math.floor(hue) % 6+ const f = hue - Math.floor(hue)+ const p = val * (1 - sat)+ const q = val * (1 - f * sat)+ const t = val * (1 - (1 - f) * sat)+ const pick: [number, number, number] =+ sector === 0+ ? [val, t, p]+ : sector === 1+ ? [q, val, p]+ : sector === 2+ ? [p, val, t]+ : sector === 3+ ? [p, q, val]+ : sector === 4+ ? [t, p, val]+ : [val, p, q]++ return { r: pick[0] * 255, g: pick[1] * 255, b: pick[2] * 255 }+}++export function rgbToHsv(rgb: RgbColor, fallbackHue = 0): HsvColor {+ const r = clamp(rgb.r, 0, 255) / 255+ const g = clamp(rgb.g, 0, 255) / 255+ const b = clamp(rgb.b, 0, 255) / 255+ const max = Math.max(r, g, b)+ const min = Math.min(r, g, b)+ const delta = max - min+ const v = max * 100+ const s = max === 0 ? 0 : (delta / max) * 100++ if (delta === 0) return { h: normalizeHue(fallbackHue), s, v }++ let h: number+ if (max === r) h = (g - b) / delta + (g < b ? 6 : 0)+ else if (max === g) h = (b - r) / delta + 2+ else h = (r - g) / delta + 4++ return { h: normalizeHue(h * 60), s, v }+}++export function hsvToHsl({ h, s, v }: HsvColor): HslColor {+ const sat = clamp(s, 0, 100) / 100+ const val = clamp(v, 0, 100) / 100+ const l = val * (1 - sat / 2)+ const hslSat = l === 0 || l === 1 ? 0 : (val - l) / Math.min(l, 1 - l)++ return {+ h: normalizeHue(h),+ s: clamp(hslSat * 100, 0, 100),+ l: clamp(l * 100, 0, 100),+ }+}++export function hslToHsv({ h, s, l }: HslColor): HsvColor {+ const sat = clamp(s, 0, 100) / 100+ const light = clamp(l, 0, 100) / 100+ const v = light + sat * Math.min(light, 1 - light)+ const hsvSat = v === 0 ? 0 : 2 * (1 - light / v)++ return {+ h: normalizeHue(h),+ s: clamp(hsvSat * 100, 0, 100),+ v: clamp(v * 100, 0, 100),+ }+}++export function hslToRgb(hsl: HslColor): RgbColor {+ return hsvToRgb(hslToHsv(hsl))+}++function srgbToLinear(channel: number): number {+ const c = channel / 255+ return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4)+}++function linearToSrgb(channel: number): number {+ const c =+ channel <= 0.0031308+ ? channel * 12.92+ : 1.055 * Math.pow(channel, 1 / 2.4) - 0.055+ return c * 255+}++interface OklabColor {+ l: number+ a: number+ b: number+}++function rgbToOklab(rgb: RgbColor): OklabColor {+ const r = srgbToLinear(clamp(rgb.r, 0, 255))+ const g = srgbToLinear(clamp(rgb.g, 0, 255))+ const b = srgbToLinear(clamp(rgb.b, 0, 255))++ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b)+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b)+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b)++ return {+ l: 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,+ a: 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,+ b: 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,+ }+}++function oklchToOklab({ l, c, h }: OklchColor): OklabColor {+ const hueRad = (normalizeHue(h) * Math.PI) / 180+ return { l, a: c * Math.cos(hueRad), b: c * Math.sin(hueRad) }+}++export function rgbToOklch(rgb: RgbColor, fallbackHue = 0): OklchColor {+ const lab = rgbToOklab(rgb)+ const c = Math.sqrt(lab.a * lab.a + lab.b * lab.b)+ if (c < 1e-6)+ return { l: clamp(lab.l, 0, 1), c: 0, h: normalizeHue(fallbackHue) }++ return {+ l: clamp(lab.l, 0, 1),+ c,+ h: normalizeHue((Math.atan2(lab.b, lab.a) * 180) / Math.PI),+ }+}++function oklabToLinearSrgb({ l, a, b }: OklabColor): {+ r: number+ g: number+ b: number+} {+ const lp = l + 0.3963377774 * a + 0.2158037573 * b+ const mp = l - 0.1055613458 * a - 0.0638541728 * b+ const sp = l - 0.0894841775 * a - 1.291485548 * b++ const lc = lp * lp * lp+ const mc = mp * mp * mp+ const sc = sp * sp * sp++ return {+ r: 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc,+ g: -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc,+ b: -0.0041960863 * lc - 0.7034186147 * mc + 1.707614701 * sc,+ }+}++function oklabToRgbRaw(lab: OklabColor): RgbColor {+ const linear = oklabToLinearSrgb(lab)+ return {+ r: linearToSrgb(linear.r),+ g: linearToSrgb(linear.g),+ b: linearToSrgb(linear.b),+ }+}++function oklchToRgbRaw(oklch: OklchColor): RgbColor {+ return oklabToRgbRaw(oklchToOklab(oklch))+}++function isInSrgbGamut(rgb: RgbColor): boolean {+ const eps = 0.001+ return (+ rgb.r >= -eps &&+ rgb.r <= 255 + eps &&+ rgb.g >= -eps &&+ rgb.g <= 255 + eps &&+ rgb.b >= -eps &&+ rgb.b <= 255 + eps+ )+}++function clampRgb(rgb: RgbColor): RgbColor {+ return {+ r: clamp(rgb.r, 0, 255),+ g: clamp(rgb.g, 0, 255),+ b: clamp(rgb.b, 0, 255),+ }+}++function deltaEok(first: OklabColor, second: OklabColor): number {+ const dl = first.l - second.l+ const da = first.a - second.a+ const db = first.b - second.b+ return Math.sqrt(dl * dl + da * da + db * db)+}++/** CSS Color 4 local-MINDE gamut mapping. */+export function oklchToRgb(oklch: OklchColor): RgbColor {+ const target: OklchColor = {+ l: clamp(oklch.l, 0, 1),+ c: Math.max(0, oklch.c),+ h: oklch.h,+ }+ if (target.l >= 1) return { r: 255, g: 255, b: 255 }+ if (target.l <= 0) return { r: 0, g: 0, b: 0 }++ const raw = oklchToRgbRaw(target)+ if (isInSrgbGamut(raw)) return clampRgb(raw)++ const jnd = 0.02+ const epsilon = 0.0001++ let clipped = clampRgb(raw)+ if (deltaEok(rgbToOklab(clipped), oklchToOklab(target)) < jnd) return clipped++ let min = 0+ let max = target.c+ let minInGamut = true++ while (max - min > epsilon) {+ const chroma = (min + max) / 2+ const candidate: OklchColor = { ...target, c: chroma }+ const candidateRaw = oklchToRgbRaw(candidate)++ if (minInGamut && isInSrgbGamut(candidateRaw)) {+ min = chroma+ continue+ }++ clipped = clampRgb(candidateRaw)+ const distance = deltaEok(rgbToOklab(clipped), oklchToOklab(candidate))+ if (distance < jnd) {+ if (jnd - distance < epsilon) return clipped+ minInGamut = false+ min = chroma+ } else {+ max = chroma+ }+ }++ return clipped+}++// OKHSV cusp math: https://bottosson.github.io/posts/colorpicker/++function computeMaxSaturation(a: number, b: number): number {+ let k0: number, k1: number, k2: number, k3: number, k4: number+ let wl: number, wm: number, ws: number++ if (-1.88170328 * a - 0.80936493 * b > 1) {+ k0 = 1.19086277+ k1 = 1.76576728+ k2 = 0.59662641+ k3 = 0.75515197+ k4 = 0.56771245+ wl = 4.0767416621+ wm = -3.3077115913+ ws = 0.2309699292+ } else if (1.81444104 * a - 1.19445276 * b > 1) {+ k0 = 0.73956515+ k1 = -0.45954404+ k2 = 0.08285427+ k3 = 0.1254107+ k4 = 0.14503204+ wl = -1.2684380046+ wm = 2.6097574011+ ws = -0.3413193965+ } else {+ k0 = 1.35733652+ k1 = -0.00915799+ k2 = -1.1513021+ k3 = -0.50559606+ k4 = 0.00692167+ wl = -0.0041960863+ wm = -0.7034186147+ ws = 1.707614701+ }++ let s = k0 + k1 * a + k2 * b + k3 * a * a + k4 * a * b++ // Refine the gamut boundary.+ const kl = 0.3963377774 * a + 0.2158037573 * b+ const km = -0.1055613458 * a - 0.0638541728 * b+ const ks = -0.0894841775 * a - 1.291485548 * b+ const lp = 1 + s * kl+ const mp = 1 + s * km+ const sp = 1 + s * ks+ const l = lp * lp * lp+ const m = mp * mp * mp+ const s3 = sp * sp * sp+ const lds = 3 * kl * lp * lp+ const mds = 3 * km * mp * mp+ const sds = 3 * ks * sp * sp+ const lds2 = 6 * kl * kl * lp+ const mds2 = 6 * km * km * mp+ const sds2 = 6 * ks * ks * sp+ const f = wl * l + wm * m + ws * s3+ const f1 = wl * lds + wm * mds + ws * sds+ const f2 = wl * lds2 + wm * mds2 + ws * sds2+ s = s - (f * f1) / (f1 * f1 - 0.5 * f * f2)++ return s+}++function findCusp(a: number, b: number): { l: number; c: number } {+ const sCusp = computeMaxSaturation(a, b)+ const rgbAtMax = oklabToLinearSrgb({ l: 1, a: sCusp * a, b: sCusp * b })+ const lCusp = Math.cbrt(1 / Math.max(rgbAtMax.r, rgbAtMax.g, rgbAtMax.b))+ return { l: lCusp, c: lCusp * sCusp }+}++export function maxChromaForHue(hue: number): number {+ const hueRad = (normalizeHue(hue) * Math.PI) / 180+ return findCusp(Math.cos(hueRad), Math.sin(hueRad)).c+}++export function cuspColorForHue(hue: number): RgbColor {+ const hueRad = (normalizeHue(hue) * Math.PI) / 180+ const aUnit = Math.cos(hueRad)+ const bUnit = Math.sin(hueRad)+ const cusp = findCusp(aUnit, bUnit)+ return clampRgb(+ oklabToRgbRaw({ l: cusp.l, a: cusp.c * aUnit, b: cusp.c * bUnit })+ )+}++// Lift saturated dark colors above black.+const PLANE_MIN_L = 0.25++function planeLightnessFloor(chromaFraction: number): number {+ return PLANE_MIN_L * chromaFraction+}++export function oklchPlaneToRgb({ h, s, v }: HsvColor): RgbColor {+ const s01 = clamp(s, 0, 100) / 100+ const floor = planeLightnessFloor(s01)+ const lightness = floor + (clamp(v, 0, 100) / 100) * (1 - floor)+ return clampRgb(+ oklchToRgbRaw({ l: lightness, c: s01 * maxChromaForHue(h), h })+ )+}++export function rgbToOklchPlane(rgb: RgbColor, fallbackHue = 0): HsvColor {+ const oklch = rgbToOklch(rgb, fallbackHue)+ // Preserve hue below the reliable chroma threshold.+ const hue = oklch.c < 0.004 ? normalizeHue(fallbackHue) : oklch.h+ const cMax = maxChromaForHue(hue)+ const s01 = cMax > 0 ? clamp(oklch.c / cMax, 0, 1) : 0+ const floor = planeLightnessFloor(s01)+ return {+ h: hue,+ s: s01 * 100,+ v: clamp((oklch.l - floor) / (1 - floor), 0, 1) * 100,+ }+}++/** RGBA pixels for the picker plane. */+export function getOklchPlanePixels(+ width: number,+ height: number,+ hue: number+): Uint8ClampedArray {+ const data = new Uint8ClampedArray(width * height * 4)+ const hueRad = (normalizeHue(hue) * Math.PI) / 180+ const aUnit = Math.cos(hueRad)+ const bUnit = Math.sin(hueRad)+ const cMax = findCusp(aUnit, bUnit).c++ for (let x = 0; x < width; x += 1) {+ const s01 = width === 1 ? 0 : x / (width - 1)+ const chroma = s01 * cMax+ const aChroma = chroma * aUnit+ const bChroma = chroma * bUnit+ const floor = planeLightnessFloor(s01)+ for (let y = 0; y < height; y += 1) {+ const v01 = height === 1 ? 1 : 1 - y / (height - 1)+ const linear = oklabToLinearSrgb({+ l: floor + v01 * (1 - floor),+ a: aChroma,+ b: bChroma,+ })+ const i = (y * width + x) * 4+ data[i] = linearToSrgb(linear.r)+ data[i + 1] = linearToSrgb(linear.g)+ data[i + 2] = linearToSrgb(linear.b)+ data[i + 3] = 255+ }+ }++ return data+}++export function formatNumber(value: number, maxDecimals: number): string {+ const fixed = value.toFixed(maxDecimals)+ if (!fixed.includes(".")) return fixed+ const trimmed = fixed.replace(/0+$/, "").replace(/\.$/, "")+ return trimmed === "-0" ? "0" : trimmed+}++function toHexPair(channel: number): string {+ return clamp(Math.round(channel), 0, 255)+ .toString(16)+ .padStart(2, "0")+ .toUpperCase()+}++export function rgbaToHex(rgb: RgbColor, alpha = 1): string {+ const base = `#${toHexPair(rgb.r)}${toHexPair(rgb.g)}${toHexPair(rgb.b)}`+ return alpha >= 1 ? base : `${base}${toHexPair(alpha * 255)}`+}++export function formatColorValue(+ format: ColorFormat,+ parts: ColorParts+): string {+ const { rgb, hsl, oklch } = parts+ switch (format) {+ case "hex":+ return rgbaToHex(rgb).slice(1)+ case "rgb":+ return `${Math.round(clamp(rgb.r, 0, 255))} ${Math.round(clamp(rgb.g, 0, 255))} ${Math.round(+ clamp(rgb.b, 0, 255)+ )}`+ case "hsl":+ return `${formatNumber(hsl.h, 1)}° ${formatNumber(hsl.s, 1)}% ${formatNumber(hsl.l, 1)}%`+ case "oklch":+ return `${formatNumber(oklch.l * 100, 1)}% ${formatNumber(oklch.c, 3)} ${formatNumber(oklch.h, 1)}`+ }+}++export function formatCssColor(+ format: ColorFormat,+ parts: ColorParts,+ options?: { includeAlpha?: boolean }+): string {+ const includeAlpha = (options?.includeAlpha ?? true) && parts.alpha < 1+ const alphaNumber = formatNumber(clamp(parts.alpha, 0, 1), 3)++ switch (format) {+ case "hex":+ return rgbaToHex(parts.rgb, includeAlpha ? parts.alpha : 1)+ case "rgb": {+ const channels = `${Math.round(clamp(parts.rgb.r, 0, 255))}, ${Math.round(+ clamp(parts.rgb.g, 0, 255)+ )}, ${Math.round(clamp(parts.rgb.b, 0, 255))}`+ return includeAlpha+ ? `rgba(${channels}, ${alphaNumber})`+ : `rgb(${channels})`+ }+ case "hsl": {+ const channels = `${formatNumber(parts.hsl.h, 2)}, ${formatNumber(parts.hsl.s, 2)}%, ${formatNumber(+ parts.hsl.l,+ 2+ )}%`+ return includeAlpha+ ? `hsla(${channels}, ${alphaNumber})`+ : `hsl(${channels})`+ }+ case "oklch": {+ const channels = `${formatNumber(parts.oklch.l * 100, 2)}% ${formatNumber(parts.oklch.c, 4)} ${formatNumber(+ parts.oklch.h,+ 2+ )}`+ return includeAlpha+ ? `oklch(${channels} / ${alphaNumber})`+ : `oklch(${channels})`+ }+ }+}++interface NumericToken {+ value: number+ percent: boolean+}++function parseNumericToken(token: string): NumericToken | null {+ const match = /^([+-]?\d*\.?\d+)(%|deg|°)?$/i.exec(token.trim())+ if (!match) return null+ const value = Number.parseFloat(match[1] ?? "")+ if (!Number.isFinite(value)) return null+ return { value, percent: match[2] === "%" }+}++function parseAlphaToken(token: string): number | null {+ const parsed = parseNumericToken(token)+ if (!parsed) return null+ const value =+ parsed.percent || parsed.value > 1 ? parsed.value / 100 : parsed.value+ return clamp(value, 0, 1)+}++function rgbFromTokens(+ tokens: NumericToken[],+ allowUnitScale: boolean+): RgbColor | null {+ if (tokens.length !== 3) return null+ const scaleUnit =+ allowUnitScale &&+ tokens.every(+ (token) => !token.percent && token.value >= 0 && token.value <= 1+ )+ const channels = tokens.map((token) => {+ if (token.percent) return (token.value / 100) * 255+ return scaleUnit ? token.value * 255 : token.value+ })++ return clampRgb({+ r: channels[0] ?? 0,+ g: channels[1] ?? 0,+ b: channels[2] ?? 0,+ })+}++function hslFromTokens(tokens: NumericToken[]): RgbColor | null {+ if (tokens.length !== 3) return null+ return hslToRgb({+ h: normalizeHue(tokens[0]?.value ?? 0),+ s: clamp(tokens[1]?.value ?? 0, 0, 100),+ l: clamp(tokens[2]?.value ?? 0, 0, 100),+ })+}++function oklchFromTokens(tokens: NumericToken[]): RgbColor | null {+ if (tokens.length !== 3) return null+ const [lToken, cToken, hToken] = tokens+ if (!lToken || !cToken || !hToken) return null+ const l =+ lToken.percent || lToken.value > 1 ? lToken.value / 100 : lToken.value+ const c = cToken.percent ? (cToken.value / 100) * 0.4 : cToken.value++ return oklchToRgb({+ l: clamp(l, 0, 1),+ c: Math.max(0, c),+ h: normalizeHue(hToken.value),+ })+}++function splitAlpha(+ body: string+): { main: string; alpha: number | null } | null {+ const slashParts = body.split("/")+ if (slashParts.length > 2) return null+ if (slashParts.length === 2) {+ const alpha = parseAlphaToken(slashParts[1] ?? "")+ if (alpha === null) return null+ return { main: slashParts[0] ?? "", alpha }+ }+ return { main: body, alpha: null }+}++function tokenize(main: string): NumericToken[] | null {+ const rawTokens = main+ .split(/[\s,]+/)+ .map((token) => token.trim())+ .filter(Boolean)+ const tokens: NumericToken[] = []+ for (const raw of rawTokens) {+ const parsed = parseNumericToken(raw)+ if (!parsed) return null+ tokens.push(parsed)+ }+ return tokens+}++function parseHexBody(raw: string): ParsedColor | null {+ const body = raw.startsWith("#") ? raw.slice(1) : raw+ if (!/^[0-9a-f]+$/i.test(body)) return null++ let expanded: string+ if (body.length === 3 || body.length === 4) {+ expanded = body+ .split("")+ .map((char) => char + char)+ .join("")+ } else if (body.length === 6 || body.length === 8) {+ expanded = body+ } else {+ return null+ }++ const channels: number[] = []+ for (let i = 0; i < expanded.length; i += 2) {+ channels.push(Number.parseInt(expanded.slice(i, i + 2), 16))+ }++ return {+ rgb: { r: channels[0] ?? 0, g: channels[1] ?? 0, b: channels[2] ?? 0 },+ alpha: channels.length === 4 ? (channels[3] ?? 255) / 255 : null,+ format: "hex",+ }+}++function parseFunctional(name: string, body: string): ParsedColor | null {+ const withAlpha = splitAlpha(body)+ if (!withAlpha) return null+ const tokens = tokenize(withAlpha.main)+ if (!tokens) return null++ let alpha = withAlpha.alpha+ let componentTokens = tokens+ if (tokens.length === 4 && alpha === null) {+ componentTokens = tokens.slice(0, 3)+ const last = tokens[3]+ if (!last) return null+ alpha = clamp(last.percent ? last.value / 100 : last.value, 0, 1)+ }++ let rgb: RgbColor | null = null+ let format: ColorFormat | null = null+ if (name === "rgb" || name === "rgba") {+ rgb = rgbFromTokens(componentTokens, false)+ format = "rgb"+ } else if (name === "hsl" || name === "hsla") {+ rgb = hslFromTokens(componentTokens)+ format = "hsl"+ } else if (name === "oklch") {+ rgb = oklchFromTokens(componentTokens)+ format = "oklch"+ }++ return rgb ? { rgb, alpha, format } : null+}++let cssParserContext: CanvasRenderingContext2D | null | undefined++function parseWithBrowser(raw: string): ParsedColor | null {+ if (typeof document === "undefined") return null+ if (cssParserContext === undefined) {+ try {+ cssParserContext = document.createElement("canvas").getContext("2d")+ } catch {+ cssParserContext = null+ }+ }+ if (!cssParserContext) return null++ const sentinels = ["#010203", "#030201"]+ let normalized: string | null = null+ for (const sentinel of sentinels) {+ cssParserContext.fillStyle = sentinel+ cssParserContext.fillStyle = raw+ const result = cssParserContext.fillStyle+ if (typeof result !== "string" || result === sentinel) return null+ normalized = result+ }+ if (!normalized) return null++ // Browser fallback should not change the selected format.+ if (normalized.startsWith("#")) {+ const hex = parseHexBody(normalized)+ return hex ? { ...hex, format: null } : null+ }+ const functional = /^(rgba?)\(\s*(.+?)\s*\)$/i.exec(normalized)+ if (functional) {+ const parsed = parseFunctional(+ (functional[1] ?? "").toLowerCase(),+ functional[2] ?? ""+ )+ return parsed ? { ...parsed, format: null } : null+ }+ return null+}++/** Parses supported color syntax, then falls back to the browser parser. */+export function parseColorInput(+ input: string,+ assumeFormat: ColorFormat = "hex"+): ParsedColor | null {+ const raw = input.trim()+ if (!raw) return null++ const functional = /^([a-z]+)\(\s*(.+?)\s*\)$/i.exec(raw)+ if (functional) {+ const name = (functional[1] ?? "").toLowerCase()+ if (["rgb", "rgba", "hsl", "hsla", "oklch"].includes(name)) {+ return parseFunctional(name, functional[2] ?? "")+ }+ return parseWithBrowser(raw)+ }++ const withAlpha = splitAlpha(raw)+ if (withAlpha) {+ const main = withAlpha.main.trim()++ if (/^#?[0-9a-f]{3,8}$/i.test(main)) {+ const hex = parseHexBody(main)+ if (hex)+ return {+ rgb: hex.rgb,+ alpha: withAlpha.alpha ?? hex.alpha,+ format: "hex",+ }+ }++ const tokens = tokenize(main)+ if (tokens && tokens.length === 3) {+ let rgb: RgbColor | null = null+ if (assumeFormat === "hsl") rgb = hslFromTokens(tokens)+ else if (assumeFormat === "oklch") rgb = oklchFromTokens(tokens)+ else rgb = rgbFromTokens(tokens, true)+ if (rgb) return { rgb, alpha: withAlpha.alpha, format: null }+ }+ }++ return parseWithBrowser(raw)+}++export function rgbTupleToHex(tuple: [number, number, number]): string {+ return rgbaToHex({ r: tuple[0], g: tuple[1], b: tuple[2] })+}++export function hexToRgbTuple(value: string): [number, number, number] | null {+ const parsed = parseColorInput(value, "hex")+ if (!parsed) return null+ return [+ Math.round(parsed.rgb.r),+ Math.round(parsed.rgb.g),+ Math.round(parsed.rgb.b),+ ]+}diff --git a/apps/v4/lib/pdf-thumbnail-utils.ts b/apps/v4/lib/pdf-thumbnail-utils.tsindex f51dd69..5e83fc7 100644--- a/apps/v4/lib/pdf-thumbnail-utils.ts+++ b/apps/v4/lib/pdf-thumbnail-utils.ts@@ -1,6 +1,6 @@import type { PdfDocumentObject, PdfEngine } from "@embedpdf/models"-const PDFIUM_VERSION = "2.14.4"+const PDFIUM_VERSION = "2.15.0"const PDFIUM_WASM_URL = `https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@${PDFIUM_VERSION}/dist/pdfium.wasm`let sharedEnginePromise: Promise<PdfEngine> | null = nulldiff --git a/apps/v4/lib/pdf-viewer-blocks.ts b/apps/v4/lib/pdf-viewer-blocks.tsindex 7f17a84..17df9ea 100644--- a/apps/v4/lib/pdf-viewer-blocks.ts+++ b/apps/v4/lib/pdf-viewer-blocks.ts@@ -80,6 +80,17 @@ export const PDF_VIEWER_BLOCKS = [docsHref: "/docs/components/xlsx-editor",viewHref: "/view/blocks/excel-editor",},+ {+ id: "pdf-editor-block",+ title: "PDF Editor",+ badge: "New",+ description:+ "A full PDF editor with annotations, comments, redaction, forms, signatures, stamps, page organization, security, print, and export.",+ command: getRegistryAddCommand("pdf-editor-block"),+ docsHref: "/docs/components/pdf-editor",+ viewHref: "/view/blocks/pdf-editor-block",+ previewHeightClassName: "h-[760px]",+ },{id: "docx-editor-block",title: "DOCX Editor",diff --git a/apps/v4/mdx-components.tsx b/apps/v4/mdx-components.tsxindex e523e0a..08fef4f 100644--- a/apps/v4/mdx-components.tsx+++ b/apps/v4/mdx-components.tsx@@ -49,6 +49,7 @@ import {import { FileUploadDemo, FileUploadSource } from "@/components/file-upload-docs"import { getIconForLanguageExtension } from "@/components/icons"import { OcrBlocksDemo, OcrBlocksSource } from "@/components/layout-blocks-docs"+import { PdfEditorDemo, PdfEditorSource } from "@/components/pdf-editor-docs"import { PdfViewerDemo, PdfViewerSource } from "@/components/pdf-viewer-docs"import { PptxViewerDemo, PptxViewerSource } from "@/components/pptx-viewer-docs"import {@@ -406,6 +407,8 @@ export const mdxComponents = {SchemaBuilderSource,OcrBlocksDemo,OcrBlocksSource,+ PdfEditorDemo,+ PdfEditorSource,PdfViewerDemo,PdfViewerSource,PptxViewerDemo,diff --git a/apps/v4/package.json b/apps/v4/package.jsonindex c8209fe..3183e6c 100644--- a/apps/v4/package.json+++ b/apps/v4/package.json@@ -22,20 +22,37 @@"@dnd-kit/core": "^6.3.1","@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2",- "@embedpdf/core": "^2.14.4",- "@embedpdf/engines": "^2.14.4",- "@embedpdf/models": "^2.14.4",- "@embedpdf/plugin-document-manager": "^2.14.4",- "@embedpdf/plugin-interaction-manager": "^2.14.4",- "@embedpdf/plugin-render": "^2.14.4",- "@embedpdf/plugin-rotate": "^2.14.4",- "@embedpdf/plugin-scroll": "^2.14.4",- "@embedpdf/plugin-search": "^2.14.4",- "@embedpdf/plugin-selection": "^2.14.4",- "@embedpdf/plugin-thumbnail": "^2.14.4",- "@embedpdf/plugin-tiling": "^2.14.4",- "@embedpdf/plugin-viewport": "^2.14.4",- "@embedpdf/plugin-zoom": "^2.14.4",+ "@embedpdf/core": "^2.15.0",+ "@embedpdf/default-stamps": "0.0.1",+ "@embedpdf/engines": "^2.15.0",+ "@embedpdf/models": "^2.15.0",+ "@embedpdf/plugin-annotation": "2.15.0",+ "@embedpdf/plugin-attachment": "2.15.0",+ "@embedpdf/plugin-bookmark": "2.15.0",+ "@embedpdf/plugin-capture": "2.15.0",+ "@embedpdf/plugin-document-manager": "^2.15.0",+ "@embedpdf/plugin-export": "2.15.0",+ "@embedpdf/plugin-form": "2.15.0",+ "@embedpdf/plugin-fullscreen": "2.15.0",+ "@embedpdf/plugin-history": "2.15.0",+ "@embedpdf/plugin-interaction-manager": "^2.15.0",+ "@embedpdf/plugin-pan": "2.15.0",+ "@embedpdf/plugin-print": "2.15.0",+ "@embedpdf/plugin-redaction": "2.15.0",+ "@embedpdf/plugin-render": "^2.15.0",+ "@embedpdf/plugin-rotate": "^2.15.0",+ "@embedpdf/plugin-scroll": "^2.15.0",+ "@embedpdf/plugin-search": "^2.15.0",+ "@embedpdf/plugin-selection": "^2.15.0",+ "@embedpdf/plugin-signature": "2.15.0",+ "@embedpdf/plugin-spread": "2.15.0",+ "@embedpdf/plugin-stamp": "2.15.0",+ "@embedpdf/plugin-thumbnail": "^2.15.0",+ "@embedpdf/plugin-tiling": "^2.15.0",+ "@embedpdf/plugin-view-manager": "2.15.0",+ "@embedpdf/plugin-viewport": "^2.15.0",+ "@embedpdf/plugin-zoom": "^2.15.0",+ "@embedpdf/utils": "2.15.0","@extend-ai/react-docx": "0.8.4","@extend-ai/react-pptx": "0.1.2","@extend-ai/react-xlsx": "0.16.1",@@ -54,6 +71,7 @@"cmdk": "^1.1.1","fumadocs-core": "16.0.5","fumadocs-mdx": "13.0.2",+ "html-to-image": "^1.11.13","jotai": "^2.15.0","lodash": "^4.18.1","lru-cache": "^11.2.4",diff --git a/apps/v4/registry.json b/apps/v4/registry.jsonindex 4b9d621..3d51d63 100644--- a/apps/v4/registry.json+++ b/apps/v4/registry.json@@ -173,10 +173,9 @@"name": "color-picker","type": "registry:ui","title": "Color Picker",- "description": "A compact popover color picker with hex, RGB, CSS, and HSL input formats.",+ "description": "An OKLCH-aware popover color picker with OKLCH, HSL, RGB, and hex input formats.","registryDependencies": ["button",- "input","popover","select","tooltip",@@ -187,6 +186,11 @@"path": "components/ui/color-picker.tsx","type": "registry:ui","target": "@ui/color-picker.tsx"+ },+ {+ "path": "lib/color-picker-utils.ts",+ "type": "registry:lib",+ "target": "@/lib/color-picker-utils.ts"}]},@@ -428,6 +432,21 @@}]},+ {+ "name": "switch",+ "type": "registry:ui",+ "title": "Switch",+ "description": "A binary toggle control built on Base UI.",+ "dependencies": ["@base-ui/react@^1.4.1"],+ "registryDependencies": ["utils"],+ "files": [+ {+ "path": "registry/new-york-v4/ui/switch.tsx",+ "type": "registry:ui",+ "target": "@ui/switch.tsx"+ }+ ]+ },{"name": "tabs","type": "registry:ui",@@ -443,6 +462,21 @@}]},+ {+ "name": "toast",+ "type": "registry:ui",+ "title": "Toast",+ "description": "A toast provider built on Base UI.",+ "dependencies": ["@base-ui/react@^1.4.1"],+ "registryDependencies": ["button", "utils"],+ "files": [+ {+ "path": "registry/new-york-v4/ui/toast.tsx",+ "type": "registry:ui",+ "target": "@ui/toast.tsx"+ }+ ]+ },{"name": "tooltip","type": "registry:ui",@@ -587,20 +621,20 @@"title": "PDF Viewer","description": "A PDF viewer with page virtualization, thumbnails, search, zoom, rotation, upload, and page overlay hooks.","dependencies": [- "@embedpdf/core@^2.14.4",- "@embedpdf/engines@^2.14.4",- "@embedpdf/models@^2.14.4",- "@embedpdf/plugin-document-manager@^2.14.4",- "@embedpdf/plugin-interaction-manager@^2.14.4",- "@embedpdf/plugin-render@^2.14.4",- "@embedpdf/plugin-rotate@^2.14.4",- "@embedpdf/plugin-scroll@^2.14.4",- "@embedpdf/plugin-search@^2.14.4",- "@embedpdf/plugin-selection@^2.14.4",- "@embedpdf/plugin-thumbnail@^2.14.4",- "@embedpdf/plugin-tiling@^2.14.4",- "@embedpdf/plugin-viewport@^2.14.4",- "@embedpdf/plugin-zoom@^2.14.4",+ "@embedpdf/core@^2.15.0",+ "@embedpdf/engines@^2.15.0",+ "@embedpdf/models@^2.15.0",+ "@embedpdf/plugin-document-manager@^2.15.0",+ "@embedpdf/plugin-interaction-manager@^2.15.0",+ "@embedpdf/plugin-render@^2.15.0",+ "@embedpdf/plugin-rotate@^2.15.0",+ "@embedpdf/plugin-scroll@^2.15.0",+ "@embedpdf/plugin-search@^2.15.0",+ "@embedpdf/plugin-selection@^2.15.0",+ "@embedpdf/plugin-thumbnail@^2.15.0",+ "@embedpdf/plugin-tiling@^2.15.0",+ "@embedpdf/plugin-viewport@^2.15.0",+ "@embedpdf/plugin-zoom@^2.15.0","pdf-lib@^1.17.1"],"registryDependencies": [@@ -631,6 +665,95 @@}]},+ {+ "name": "pdf-editor",+ "type": "registry:ui",+ "title": "PDF Editor",+ "description": "A PDF editor with annotations, comments, redaction, form filling and design, signatures, rubber stamps, page organization, security, printing, and export.",+ "dependencies": [+ "@embedpdf/core@^2.15.0",+ "@embedpdf/engines@^2.15.0",+ "@embedpdf/models@^2.15.0",+ "@embedpdf/plugin-annotation@^2.15.0",+ "@embedpdf/plugin-attachment@^2.15.0",+ "@embedpdf/plugin-bookmark@^2.15.0",+ "@embedpdf/plugin-capture@^2.15.0",+ "@embedpdf/plugin-document-manager@^2.15.0",+ "@embedpdf/plugin-export@^2.15.0",+ "@embedpdf/plugin-form@^2.15.0",+ "@embedpdf/plugin-fullscreen@^2.15.0",+ "@embedpdf/plugin-history@^2.15.0",+ "@embedpdf/plugin-interaction-manager@^2.15.0",+ "@embedpdf/plugin-pan@^2.15.0",+ "@embedpdf/plugin-print@^2.15.0",+ "@embedpdf/plugin-redaction@^2.15.0",+ "@embedpdf/plugin-render@^2.15.0",+ "@embedpdf/plugin-rotate@^2.15.0",+ "@embedpdf/plugin-scroll@^2.15.0",+ "@embedpdf/plugin-search@^2.15.0",+ "@embedpdf/plugin-selection@^2.15.0",+ "@embedpdf/plugin-signature@^2.15.0",+ "@embedpdf/plugin-spread@^2.15.0",+ "@embedpdf/plugin-stamp@^2.15.0",+ "@embedpdf/plugin-thumbnail@^2.15.0",+ "@embedpdf/plugin-tiling@^2.15.0",+ "@embedpdf/plugin-viewport@^2.15.0",+ "@embedpdf/plugin-zoom@^2.15.0",+ "pdf-lib@^1.17.1"+ ],+ "registryDependencies": [+ "badge",+ "button",+ "@extend/color-picker",+ "dialog",+ "@extend/document-viewer-sidebar",+ "dropdown-menu",+ "input",+ "kbd",+ "popover",+ "scroll-area",+ "select",+ "spinner",+ "switch",+ "toast",+ "toggle",+ "tooltip",+ "utils"+ ],+ "categories": ["documents"],+ "files": [+ {+ "path": "components/extend/pdf-editor.tsx",+ "type": "registry:ui",+ "target": "@components/extend/pdf-editor.tsx"+ },+ {+ "path": "components/extend/pdf-editor-shared.tsx",+ "type": "registry:ui",+ "target": "@components/extend/pdf-editor-shared.tsx"+ },+ {+ "path": "components/extend/pdf-editor-dialogs.tsx",+ "type": "registry:ui",+ "target": "@components/extend/pdf-editor-dialogs.tsx"+ },+ {+ "path": "components/extend/pdf-editor-properties.tsx",+ "type": "registry:ui",+ "target": "@components/extend/pdf-editor-properties.tsx"+ },+ {+ "path": "components/extend/pdf-editor-panels.tsx",+ "type": "registry:ui",+ "target": "@components/extend/pdf-editor-panels.tsx"+ },+ {+ "path": "lib/pdf-thumbnail-utils.ts",+ "type": "registry:lib",+ "target": "@lib/pdf-thumbnail-utils.ts"+ }+ ]+ },{"name": "docx-viewer","type": "registry:ui",@@ -1046,6 +1169,21 @@}]},+ {+ "name": "pdf-editor-block",+ "type": "registry:block",+ "title": "PDF Editor",+ "description": "A full PDF editor block with annotation, redaction, form, signature, stamp, page organization, security, print, and export tools.",+ "registryDependencies": ["@extend/pdf-editor"],+ "categories": ["documents", "blocks"],+ "files": [+ {+ "path": "registry/new-york-v4/blocks/pdf-editor-block.tsx",+ "type": "registry:component",+ "target": "@components/blocks/pdf-editor-block.tsx"+ }+ ]+ },{"name": "document-viewer-sidebar","type": "registry:ui",diff --git a/apps/v4/registry/new-york-v4/blocks/pdf-editor-block.tsx b/apps/v4/registry/new-york-v4/blocks/pdf-editor-block.tsxnew file mode 100644index 0000000..a46ea94--- /dev/null+++ b/apps/v4/registry/new-york-v4/blocks/pdf-editor-block.tsx@@ -0,0 +1,28 @@+"use client"++import * as React from "react"++import { PDFEditor, type PdfEditorMode } from "@/components/extend/pdf-editor"++export function PdfEditorBlock({+ file,+ fileName,+ defaultMode = "annotate",+}: {+ file?: string+ fileName?: string+ defaultMode?: PdfEditorMode+}) {+ return (+ <div className="h-full min-h-0 bg-background">+ <PDFEditor+ src={file ?? "/samples/attention.pdf"}+ fileName={fileName}+ className="h-full"+ defaultZoom="fit-width"+ defaultMode={defaultMode}+ annotationAuthor="Reviewer"+ />+ </div>+ )+}diff --git a/apps/v4/registry/new-york-v4/ui/dropdown-menu.tsx b/apps/v4/registry/new-york-v4/ui/dropdown-menu.tsxindex f640a5c..a66f083 100644--- a/apps/v4/registry/new-york-v4/ui/dropdown-menu.tsx+++ b/apps/v4/registry/new-york-v4/ui/dropdown-menu.tsx@@ -220,7 +220,7 @@ function DropdownMenuRadioItem({data-slot="dropdown-menu-radio-item"{...props}>- <span className="pointer-events-none absolute start-2 flex size-4 items-center justify-center">+ <span className="pointer-events-none absolute start-2 flex size-4 items-center justify-center rounded-full border border-input"><DropdownMenuPrimitive.RadioItemIndicator><span className="size-2 rounded-full bg-current" /></DropdownMenuPrimitive.RadioItemIndicator>diff --git a/apps/v4/registry/new-york-v4/ui/scroll-area.tsx b/apps/v4/registry/new-york-v4/ui/scroll-area.tsxindex fcca196..c0662b0 100644--- a/apps/v4/registry/new-york-v4/ui/scroll-area.tsx+++ b/apps/v4/registry/new-york-v4/ui/scroll-area.tsx@@ -49,8 +49,8 @@ export function ScrollArea({"transition-shadows h-full rounded-[inherit] outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-has-overflow-x:overscroll-x-contain data-has-overflow-y:overscroll-y-contain",scrollFade &&"mask-t-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-start)))] mask-r-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-end)))] mask-b-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-end)))] mask-l-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-start)))] [--fade-size:1.5rem]",- scrollbarGutter &&- "data-has-overflow-x:pb-2.5 data-has-overflow-y:pe-2.5",+ scrollbarGutter && orientation !== "vertical" && "pb-3.5",+ scrollbarGutter && orientation !== "horizontal" && "pe-3.5",viewportPropsClassName,viewportClassName)}diff --git a/apps/v4/registry/new-york-v4/ui/switch.tsx b/apps/v4/registry/new-york-v4/ui/switch.tsxnew file mode 100644index 0000000..ddf583f--- /dev/null+++ b/apps/v4/registry/new-york-v4/ui/switch.tsx@@ -0,0 +1,29 @@+"use client"++import type * as React from "react"+import { Switch as SwitchPrimitive } from "@base-ui/react/switch"++import { cn } from "@/lib/utils"++export function Switch({+ className,+ ...props+}: SwitchPrimitive.Root.Props): React.ReactElement {+ return (+ <SwitchPrimitive.Root+ className={cn(+ "inline-flex h-[calc(var(--thumb-size)+2px)] w-[calc(var(--thumb-size)*2-2px)] shrink-0 items-center rounded-full p-px transition-[background-color,box-shadow] duration-200 outline-none [--thumb-size:--spacing(5)] focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background sm:[--thumb-size:--spacing(4)] data-checked:bg-primary data-unchecked:bg-input data-disabled:cursor-not-allowed data-disabled:opacity-64",+ className+ )}+ data-slot="switch"+ {...props}+ >+ <SwitchPrimitive.Thumb+ className="pointer-events-none block aspect-square h-full origin-left rounded-(--thumb-size) bg-background shadow-sm/5 will-change-transform [transition:translate_.15s,border-radius_.15s,scale_.1s_.1s,transform-origin_.15s] in-[[role=switch]:active,[data-slot=label]:active,[data-slot=field-label]:active]:not-data-disabled:scale-x-110 in-[[role=switch]:active,[data-slot=label]:active,[data-slot=field-label]:active]:not-data-disabled:rounded-[var(--thumb-size)/calc(var(--thumb-size)*1.1)] data-checked:origin-[var(--thumb-size)_50%] data-checked:translate-x-[calc(var(--thumb-size)-4px)]"+ data-slot="switch-thumb"+ />+ </SwitchPrimitive.Root>+ )+}++export { SwitchPrimitive }diff --git a/apps/v4/registry/new-york-v4/ui/toast.tsx b/apps/v4/registry/new-york-v4/ui/toast.tsxnew file mode 100644index 0000000..a86268c--- /dev/null+++ b/apps/v4/registry/new-york-v4/ui/toast.tsx@@ -0,0 +1,377 @@+"use client"++import type * as React from "react"+import { Toast } from "@base-ui/react/toast"++import { cn } from "@/lib/utils"+import { buttonVariants } from "@/components/ui/button"+import { IconPlaceholder } from "@/components/icon-placeholder"++type SwipeDirection = "up" | "down" | "left" | "right"++type ToastData = {+ rootProps?: Omit<+ React.ComponentProps<typeof Toast.Root>,+ "children" | "className" | "swipeDirection" | "toast"+ >+ tooltipStyle?: boolean+}++function ToastIcon({ type }: { type?: string }) {+ const className = cn(+ "size-4 shrink-0",+ type === "loading" && "animate-spin opacity-80",+ type === "error" && "text-destructive",+ type === "info" && "text-info",+ type === "success" && "text-success",+ type === "warning" && "text-warning"+ )++ switch (type) {+ case "error":+ return (+ <IconPlaceholder+ lucide="CircleAlertIcon"+ tabler="IconAlertCircle"+ hugeicons="Alert01Icon"+ phosphor="WarningCircleIcon"+ remixicon="RiErrorWarningLine"+ className={className}+ />+ )+ case "info":+ return (+ <IconPlaceholder+ lucide="InfoIcon"+ tabler="IconInfoCircle"+ hugeicons="InformationCircleIcon"+ phosphor="InfoIcon"+ remixicon="RiInformationLine"+ className={className}+ />+ )+ case "loading":+ return (+ <IconPlaceholder+ lucide="LoaderCircleIcon"+ tabler="IconLoader2"+ hugeicons="Loading03Icon"+ phosphor="SpinnerGapIcon"+ remixicon="RiLoaderLine"+ className={className}+ />+ )+ case "success":+ return (+ <IconPlaceholder+ lucide="CircleCheckIcon"+ tabler="IconCircleCheck"+ hugeicons="CheckmarkCircle01Icon"+ phosphor="CheckCircleIcon"+ remixicon="RiCheckboxCircleLine"+ className={className}+ />+ )+ case "warning":+ return (+ <IconPlaceholder+ lucide="TriangleAlertIcon"+ tabler="IconAlertTriangle"+ hugeicons="Alert01Icon"+ phosphor="WarningIcon"+ remixicon="RiAlertLine"+ className={className}+ />+ )+ default:+ return null+ }+}++function ToastClose() {+ return (+ <Toast.Close+ aria-label="Dismiss"+ className={buttonVariants({+ className: "-my-1 -mr-1 ml-1",+ size: "icon-xs",+ variant: "ghost",+ })}+ >+ <IconPlaceholder+ lucide="XIcon"+ tabler="IconX"+ hugeicons="Cancel01Icon"+ phosphor="XIcon"+ remixicon="RiCloseLine"+ />+ </Toast.Close>+ )+}++function getSwipeDirection(position: ToastPosition): SwipeDirection[] {+ const verticalDirection: SwipeDirection = position.startsWith("top")+ ? "up"+ : "down"++ if (position.includes("center")) return [verticalDirection]+ if (position.includes("left")) return ["left", verticalDirection]+ return ["right", verticalDirection]+}++function upsertReplayClassName(toast: {+ type?: string+ updateKey?: number+}): string | undefined {+ const key = toast.updateKey ?? 0+ if (key <= 0) return undefined+ const isEven = key % 2 === 0+ if (toast.type === "error") {+ return isEven ? "animate-toast-error-even" : "animate-toast-error-odd"+ }+ return isEven ? "animate-toast-success-even" : "animate-toast-success-odd"+}++function Toasts({+ position,+ portalProps,+ viewportProps,+}: {+ position: ToastPosition+ portalProps?: React.ComponentProps<typeof Toast.Portal>+ viewportProps?: React.ComponentProps<typeof Toast.Viewport>+}) {+ const { toasts } = Toast.useToastManager()+ const swipeDirection = getSwipeDirection(position)++ return (+ <Toast.Portal data-slot="toast-portal" {...portalProps}>+ <Toast.Viewport+ {...viewportProps}+ className={cn(+ "fixed z-60 mx-auto flex w-[calc(100%-var(--toast-inset)*2)] max-w-90 [--toast-inset:--spacing(4)] sm:[--toast-inset:--spacing(8)]",+ "data-[position*=top]:top-(--toast-inset)",+ "data-[position*=bottom]:bottom-(--toast-inset)",+ "data-[position*=left]:left-(--toast-inset)",+ "data-[position*=right]:right-(--toast-inset)",+ "data-[position*=center]:left-1/2 data-[position*=center]:-translate-x-1/2",+ viewportProps?.className+ )}+ data-position={position}+ data-slot="toast-viewport"+ >+ {toasts.map((toast) => {+ const toastData = toast.data as ToastData | undefined+ return (+ <Toast.Root+ key={toast.id}+ className={cn(+ "absolute z-[calc(9999-var(--toast-index))] h-(--toast-calc-height) w-full rounded-lg border bg-[color-mix(in_srgb,var(--popover),var(--color-black)_calc(1%*max(0,var(--toast-index,0))))] text-popover-foreground shadow-lg/5 select-none [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s,background-color_.5s] not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-expanded:bg-popover dark:bg-[color-mix(in_srgb,var(--popover),var(--color-black)_calc(6%*max(0,var(--toast-index,0))))] dark:before:shadow-[0_-1px_--theme(--color-white/6%)] dark:data-expanded:bg-popover",+ "data-[position*=right]:right-0 data-[position*=right]:left-auto",+ "data-[position*=left]:right-auto data-[position*=left]:left-0",+ "data-[position*=center]:right-0 data-[position*=center]:left-0",+ "data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-[50%_calc(50%-50%*min(var(--toast-index,0),1))]",+ "data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-[50%_calc(50%+50%*min(var(--toast-index,0),1))]",+ "after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",+ "data-[position*=top]:after:top-full",+ "data-[position*=bottom]:after:bottom-full",+ "[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",+ "data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",+ "data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",+ "data-[position*=top]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--toast-peek))+(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",+ "data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",+ "data-limited:opacity-0",+ "data-expanded:h-(--toast-height)",+ "data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",+ "data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",+ "data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",+ "data-ending-style:opacity-0",+ "data-[position*=top]:data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(-100%-var(--toast-inset)))]",+ "data-[position*=bottom]:data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",+ "data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",+ "data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",+ "data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",+ "data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",+ "data-expanded:data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",+ "data-expanded:data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",+ "data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",+ "data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",+ upsertReplayClassName(toast)+ )}+ {...toastData?.rootProps}+ data-position={position}+ swipeDirection={swipeDirection}+ toast={toast}+ >+ <Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-250 data-behind:opacity-0 data-behind:not-data-expanded:pointer-events-none data-expanded:opacity-100">+ <div className="flex min-w-0 gap-2">+ <ToastIcon type={toast.type} />+ <div className="flex min-w-0 flex-col gap-0.5">+ <Toast.Title+ className="font-medium"+ data-slot="toast-title"+ />+ <Toast.Description+ className="text-muted-foreground"+ data-slot="toast-description"+ />+ </div>+ </div>+ <div className="flex shrink-0 items-center gap-1">+ {toast.actionProps ? (+ <Toast.Action+ className={buttonVariants({ size: "xs" })}+ data-slot="toast-action"+ >+ {toast.actionProps.children}+ </Toast.Action>+ ) : null}+ <ToastClose />+ </div>+ </Toast.Content>+ </Toast.Root>+ )+ })}+ </Toast.Viewport>+ </Toast.Portal>+ )+}++function AnchoredToasts({+ portalProps,+}: {+ portalProps?: React.ComponentProps<typeof Toast.Portal>+}) {+ const { toasts } = Toast.useToastManager()+ return (+ <Toast.Portal data-slot="toast-portal-anchored" {...portalProps}>+ <Toast.Viewport+ className="outline-none"+ data-slot="toast-viewport-anchored"+ >+ {toasts.map((toast) => {+ const toastData = toast.data as ToastData | undefined+ const tooltipStyle = toastData?.tooltipStyle ?? false+ const positionerProps = toast.positionerProps+ if (!positionerProps?.anchor) return null++ return (+ <Toast.Positioner+ key={toast.id}+ className="z-50 max-w-[min(--spacing(64),var(--available-width))]"+ data-slot="toast-positioner"+ sideOffset={positionerProps.sideOffset ?? 4}+ toast={toast}+ >+ <Toast.Root+ className={cn(+ "relative border bg-popover text-xs text-balance text-popover-foreground transition-[scale,opacity] not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:scale-98 data-ending-style:opacity-0 data-starting-style:scale-98 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",+ tooltipStyle+ ? "rounded-md shadow-md/5 before:rounded-[calc(var(--radius-md)-1px)]"+ : "rounded-lg shadow-lg/5 before:rounded-[calc(var(--radius-lg)-1px)]",+ upsertReplayClassName(toast)+ )}+ {...toastData?.rootProps}+ data-slot="toast-popup"+ toast={toast}+ >+ {tooltipStyle ? (+ <Toast.Content className="pointer-events-auto px-2 py-1">+ <Toast.Title data-slot="toast-title" />+ </Toast.Content>+ ) : (+ <Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm">+ <div className="flex min-w-0 gap-2">+ <ToastIcon type={toast.type} />+ <div className="flex min-w-0 flex-col gap-0.5">+ <Toast.Title+ className="font-medium"+ data-slot="toast-title"+ />+ <Toast.Description+ className="text-muted-foreground"+ data-slot="toast-description"+ />+ </div>+ </div>+ <div className="flex shrink-0 items-center gap-1">+ {toast.actionProps ? (+ <Toast.Action+ className={buttonVariants({ size: "xs" })}+ data-slot="toast-action"+ >+ {toast.actionProps.children}+ </Toast.Action>+ ) : null}+ <ToastClose />+ </div>+ </Toast.Content>+ )}+ </Toast.Root>+ </Toast.Positioner>+ )+ })}+ </Toast.Viewport>+ </Toast.Portal>+ )+}++export const toastManager: ReturnType<typeof Toast.createToastManager> =+ Toast.createToastManager()++export const anchoredToastManager: ReturnType<typeof Toast.createToastManager> =+ Toast.createToastManager()++export type ToastPosition =+ | "top-left"+ | "top-center"+ | "top-right"+ | "bottom-left"+ | "bottom-center"+ | "bottom-right"++export interface ToastProviderProps extends Toast.Provider.Props {+ position?: ToastPosition+ portalProps?: React.ComponentProps<typeof Toast.Portal>+ viewportProps?: React.ComponentProps<typeof Toast.Viewport>+}++export function ToastProvider({+ children,+ position = "bottom-right",+ portalProps,+ viewportProps,+ toastManager: manager = toastManager,+ ...props+}: ToastProviderProps) {+ return (+ <Toast.Provider toastManager={manager} {...props}>+ {children}+ <Toasts+ portalProps={portalProps}+ position={position}+ viewportProps={viewportProps}+ />+ </Toast.Provider>+ )+}++export interface AnchoredToastProviderProps extends Toast.Provider.Props {+ portalProps?: React.ComponentProps<typeof Toast.Portal>+}++export function AnchoredToastProvider({+ children,+ portalProps,+ toastManager: manager = anchoredToastManager,+ ...props+}: AnchoredToastProviderProps) {+ return (+ <Toast.Provider toastManager={manager} {...props}>+ {children}+ <AnchoredToasts portalProps={portalProps} />+ </Toast.Provider>+ )+}++export { Toast as ToastPrimitive }diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 3bc9767..b4b8cb8 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -31,47 +31,98 @@ importers:specifier: ^3.2.2version: 3.2.2([email protected])'@embedpdf/core':- specifier: ^2.14.4- version: 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ specifier: ^2.15.0+ version: 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/default-stamps':+ specifier: 0.0.1+ version: 0.0.1'@embedpdf/engines':- specifier: ^2.14.4- version: 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ specifier: ^2.15.0+ version: 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'@embedpdf/models':- specifier: ^2.14.4- version: 2.14.4+ specifier: ^2.15.0+ version: 2.15.0+ '@embedpdf/plugin-annotation':+ specifier: 2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-attachment':+ specifier: 2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-bookmark':+ specifier: 2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-capture':+ specifier: 2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'@embedpdf/plugin-document-manager':- specifier: ^2.14.4- version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ specifier: ^2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-export':+ specifier: 2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-form':+ specifier: 2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-fullscreen':+ specifier: 2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-history':+ specifier: 2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'@embedpdf/plugin-interaction-manager':- specifier: ^2.14.4- version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ specifier: ^2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-pan':+ specifier: 2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-print':+ specifier: 2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-redaction':+ specifier: 2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'@embedpdf/plugin-render':- specifier: ^2.14.4- version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ specifier: ^2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'@embedpdf/plugin-rotate':- specifier: ^2.14.4- version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ specifier: ^2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'@embedpdf/plugin-scroll':- specifier: ^2.14.4- version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ specifier: ^2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'@embedpdf/plugin-search':- specifier: ^2.14.4- version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ specifier: ^2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'@embedpdf/plugin-selection':- specifier: ^2.14.4- version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ specifier: ^2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-signature':+ specifier: 2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-spread':+ specifier: 2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-stamp':+ specifier: 2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'@embedpdf/plugin-thumbnail':- specifier: ^2.14.4- version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ specifier: ^2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'@embedpdf/plugin-tiling':- specifier: ^2.14.4- version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ specifier: ^2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-view-manager':+ specifier: 2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'@embedpdf/plugin-viewport':- specifier: ^2.14.4- version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ specifier: ^2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'@embedpdf/plugin-zoom':- specifier: ^2.14.4- version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ specifier: ^2.15.0+ version: 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/utils':+ specifier: 2.15.0+ version: 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'@extend-ai/react-docx':specifier: 0.8.4@@ -126,6 +177,9 @@ importers:fumadocs-mdx:specifier: 13.0.2version: 13.0.2([email protected](@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ html-to-image:+ specifier: ^1.11.13+ version: 1.11.13jotai:specifier: ^2.15.0version: 2.15.0(@babel/[email protected])(@babel/[email protected])(@types/[email protected])([email protected])@@ -521,8 +575,8 @@ packages:peerDependencies:'@noble/ciphers': ^1.0.0- '@embedpdf/[email protected]':- resolution: {integrity: sha512-trrFhKePk1JnAS8Vd+NWrS1fU2SIj3sifwawho/MeWKTkferLLuBay96ccA4S/Q5D7glKNH//M58VRgns09P3A==}+ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-0yaPCgvbE5/cBf+5rHBUsRUm8i6hSl894xjC19HTOmb8DqrhxOxbOQSyjiTbJTQK52zZrNL79SigsPgGHPrYWA==}peerDependencies:preact: ^10.26.4react: '>=16.8.0'@@ -530,8 +584,11 @@ packages:svelte: '>=5 <6'vue: '>=3.2.0'- '@embedpdf/[email protected]':- resolution: {integrity: sha512-1kWYvrxjpKr5QUt16r93pLQOLoWEuzD447OViwZyRECsZ8ePoTnErlNlxHiTkeAWBgwr4DD7Xd+2VkTdMAacNA==}+ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-qNIhYQlbWRZ0W9XMNYaRWGTTTlO/HtrcHvNJDyoPp4Gxf6qVSHTMY9JCdHCyoW6aUP2tp2/wteh5wgJoO4t+nw==}++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-fW5UoqpDRkAWDbGMl3y6ril3l2qXzoYz+klt4O2P8gWzYzhG3fmr0L2+qzjD+BPO+QfYMNNvmBI+teT/nYjm/g==}peerDependencies:preact: ^10.26.4react: '>=16.8.0'@@ -560,132 +617,309 @@ packages:'@embedpdf/[email protected]':resolution: {integrity: sha512-rGZJbVD6DYS5BbXdpEMnWkpVF0Knar+bsiyb2o3+YRx7O8eyFubEBQUSUInirQk69HA6fc3GhYCg7TyC/oD76Q==}- '@embedpdf/[email protected]':- resolution: {integrity: sha512-RlxazYdS1ObWe3Rt78pVUXSqQEMeOb1oHFA0CT3aolwtVooZyop9XO3WTDWpEaGvGrHXvuSv7WQgcCLZ2zKyaQ==}+ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-gHr+hAN094kmzCB+6J2zaiHS8o4tKeY0IfTOxVEGwqntgKk8LCWD3s+P7dlVY3V8XUVmdyFWhFt7zwm0uw+VMg==}++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-KgpRND2MYcdbhzb2EMb4WzWcJYrR0A6JXvhMv4WthEHKt6qmNo2v/MC68bpYvpveYT9GNnUnY/+TG5MpXY3pRw==}++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-1g7Ls9ak/TLaRY42H1GxLriH91yBxaP3ezFDbyGSfW/nV1V5tLJ8d1OZG7Dm1HbhAcnzSt7nOXOZRqFnmhpjyQ==}+ peerDependencies:+ '@embedpdf/core': 2.15.0+ '@embedpdf/plugin-history': 2.15.0+ '@embedpdf/plugin-interaction-manager': 2.15.0+ '@embedpdf/plugin-scroll': 2.15.0+ '@embedpdf/plugin-selection': 2.15.0+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-vv8uzyqNSujrXKsmIKyV9D/8UnWfyo/MLY5lSQFoFy8Egecbqlbe8LTFcyHYA3fNhvKds+JFLV1khxnnp6tBoA==}+ peerDependencies:+ '@embedpdf/core': 2.15.0+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-pioAUfmKWiM0uc1PkGL3um7SPpcSrtcNhzdV6sgKDtLYxNBzObaCRbsQzGr0vFRayMNkDIlsRsx2yiLK6D+JcQ==}+ peerDependencies:+ '@embedpdf/core': 2.15.0+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-uPmO/U1WMitYQMbXnMj+H4lla4bTj+mtxLPbu4Ck2P/f5MK4Id1LT+AGo8zvVRELYLWyWrkS/R/5FIhB+xpAIA==}+ peerDependencies:+ '@embedpdf/core': 2.15.0+ '@embedpdf/plugin-interaction-manager': 2.15.0+ '@embedpdf/plugin-render': 2.15.0+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-M8EwOuonICSHfOklTMwk0XfyPhG9v9EMDRU9Pvz0zAe1DJzUPtIxUh+CgxtFSSnUeKSfxE7JpTRryrbUW0XcGg==}+ peerDependencies:+ '@embedpdf/core': 2.15.0+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-GFmC4nkZZnH1swivfSwLako2YV6d60QPSPUqvozQaMWDuE8rNq/ElYISVihkEAxbhI4h3q5AkhDKyCVFeJJVbg==}+ peerDependencies:+ '@embedpdf/core': 2.15.0+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-0kUqf/BHsNeHhUAdcSz3Dsqy5qNvDgQP6IhhMq5KLH+mtMoUuYiEyOGwHSY97V4vxAG9MF/UexT+CP4LfL3Yvg==}+ peerDependencies:+ '@embedpdf/core': 2.15.0+ '@embedpdf/plugin-annotation': 2.15.0+ '@embedpdf/plugin-history': 2.15.0+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-DYyoUrWD9E6NkPCaeGZQH/qpKUgJ20rXi9tOtZIc/cRAvynfcjWNCamwWXd7cDbLwrkbo+5rJIwTponKLXh5oQ==}+ peerDependencies:+ '@embedpdf/core': 2.15.0+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-3Dk4Atc5vdHsTjC8tJ8MOGPcUJLkCWbMzt3sTllmyNc534qTZtUvFHDeaaB65u50EJGjFRpUJ6Xcnp9A81lMdg==}+ peerDependencies:+ '@embedpdf/core': 2.15.0+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-xSbkJcj1Fc7dKyV7lhBU9d0xuH4wGKcPwRmkMxOvi3KJ/XD3zgfqdFMazDICN+rzth40gHSeRNhyCKZpXeYkuQ==}+ peerDependencies:+ '@embedpdf/core': 2.15.0+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-YCMvTvu4Fm1KNuEhj+CftzG+T6F1+/QhI7eaYft9Lp5xm3CYSXdR3pNfGwNFy5XkDUDwB1IscLTiU0q75viMCw==}+ peerDependencies:+ '@embedpdf/core': 2.15.0+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-bgFM7xTJRNzkFs5CH9apv5USR7Db2fdbNVbHq/U1GanEyz/71gZGoDWUN9FF/FbNvBfSfvPYZDv9DLJYLbeoBQ==}+ peerDependencies:+ '@embedpdf/core': 2.15.0+ '@embedpdf/plugin-interaction-manager': 2.15.0+ '@embedpdf/plugin-viewport': 2.15.0+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-IS6Wvi7zY0iozdYmVwfZXSjKURBe4AqhuyV1QtbcUS1hZxe0ASRETGiHe9ONpuokWemZmYDHNyTrdF7+5hdLEw==}+ peerDependencies:+ '@embedpdf/core': 2.15.0+ preact: ^10.26.4+ react: '>=18.0.0'+ react-dom: '>=18.0.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-H4WgRSSqBlWtP7sgDbAqWW/w6HAyjA3RS6lMuEmCMF19trDyQMdeAC8ZyQkFCYudFk9L+ydradSbNBYK18PfDw==}+ peerDependencies:+ '@embedpdf/core': 2.15.0+ '@embedpdf/plugin-annotation': 2.15.0+ '@embedpdf/plugin-history': 2.15.0+ '@embedpdf/plugin-interaction-manager': 2.15.0+ '@embedpdf/plugin-selection': 2.15.0+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-EVfn8XsdU10VgrSs9qKo8nqjfUyt2/NWFJtlW3nX4sZ74Pi9xSvEa7/B99/LYZZMa0ENzi+4HKAXiQ6NUXisDg==}+ peerDependencies:+ '@embedpdf/core': 2.15.0+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'- '@embedpdf/[email protected]':- resolution: {integrity: sha512-0tDPQEH1WtfXcASNVp5U3dqfzZboNvcE4rDok/P4JCN+DCTaJDG2E9lYHGMo9FtuS2IdHgrzkmPRpOo5WV9MKQ==}+ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-mhfDC8NCQ8H6ati3O6smA6ZxZoMgPGtloEeY6gs61+zoxPKyXiuCpxZKJctRfYdrTdoRgXpFa3fKflwStMcgFg==}+ peerDependencies:+ '@embedpdf/core': 2.15.0+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'- '@embedpdf/[email protected]':- resolution: {integrity: sha512-1qUKu/RAN9LV+Ih7geig0X/2i4jIn8P1D0I0nQUwSMM9hJmitcyDJ/9SK/eOSsdEs4SulIqt+a2W2IMZOY2Vew==}+ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-UqjLH3lafrpqN1qcxIpfd1MfWW5Fdf6/4LjneUabHt+3gxy1qd2KU9oPR5wwinsh3vmjn90qURsnqIHL5jnaOg==}peerDependencies:- '@embedpdf/core': 2.14.4+ '@embedpdf/core': 2.15.0+ '@embedpdf/plugin-viewport': 2.15.0preact: ^10.26.4react: '>=16.8.0'react-dom: '>=16.8.0'svelte: '>=5 <6'vue: '>=3.2.0'- '@embedpdf/[email protected]':- resolution: {integrity: sha512-y4MeHBy5s/SR5ma4rezYADIUujViAZSQe8A/CKehve4eU6Z9YF2AflL/M6KG24gCsUyW4D04AxAn3bvsXLR3nw==}+ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-mMzy8uo3xvDMjSc+xuBMgdI/mmmpgbZ6xKTmNxpF0d8BcaWu6Zp9a4ewamfjBwg8WF/qUW49U6HYZsiRr3NUEQ==}peerDependencies:- '@embedpdf/core': 2.14.4+ '@embedpdf/core': 2.15.0preact: ^10.26.4react: '>=16.8.0'react-dom: '>=16.8.0'svelte: '>=5 <6'vue: '>=3.2.0'- '@embedpdf/[email protected]':- resolution: {integrity: sha512-KNY3EGYf9SRqtDBOEO9mR3Hyv9mN8TaC3ztERj0BX8zra7mkjkQnhGQlMxif1dGOoTD9XIcPqJvaw8o7PWDJDw==}+ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-iEnhx0jeQrbze7WHkHhZtF21yfGBuqF2B+V2efLHT2O0a2fnof+PEVaQQRgERSfrwRvLvyEJL9ud54E41ahsRQ==}peerDependencies:- '@embedpdf/core': 2.14.4+ '@embedpdf/core': 2.15.0+ '@embedpdf/plugin-interaction-manager': 2.15.0preact: ^10.26.4react: '>=16.8.0'react-dom: '>=16.8.0'svelte: '>=5 <6'vue: '>=3.2.0'- '@embedpdf/[email protected]':- resolution: {integrity: sha512-+bBBHfoSMBMjHubDgPkCCu3o2NZn5vv8l/2gmzH6D8k90UVLB2AOei9VTmfy5xqoit+eoY6iSl7w3qyijNfB0A==}+ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-aFD6sHExivqdCK3U2Xns/nsZxS9jhMAgdJTrumc3eenCzGbXAHhX7wkzgIDfZs3AyKRepbUnz9wmM6lNG+IKoQ==}peerDependencies:- '@embedpdf/core': 2.14.4+ '@embedpdf/core': 2.15.0+ '@embedpdf/plugin-annotation': 2.15.0preact: ^10.26.4react: '>=16.8.0'react-dom: '>=16.8.0'svelte: '>=5 <6'vue: '>=3.2.0'- '@embedpdf/[email protected]':- resolution: {integrity: sha512-0JgPwnQqB9THKJt/mOubgFkiTcCkOI6kFCZz8zlwl88DAJcUbdhJoTwCJZ2STYSfECTLB4ZFjb5fZ9AXyfkf0g==}+ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-Gj1Nl9E/T92MkaBxL+BCH8WHfzvfM+Vb9vgTPi0gnV7Jr1SaWrtIQpMlYom21f4p9pT/m7KuBVz3xA+NV8r39A==}peerDependencies:- '@embedpdf/core': 2.14.4- '@embedpdf/plugin-viewport': 2.14.4+ '@embedpdf/core': 2.15.0preact: ^10.26.4react: '>=16.8.0'react-dom: '>=16.8.0'svelte: '>=5 <6'vue: '>=3.2.0'- '@embedpdf/[email protected]':- resolution: {integrity: sha512-ErRlg0MKLxZ0c4OKk5RjPOV8f8yCaqFi6zqUxBI49/3yN6wDINKvm8dxt5Q2QGUa740n/XylT5BTbjH6lAjCzQ==}+ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-QjrzwCUVYoRX/zp8FpMByGgmUxvovARmd+xSaMtH70iHAPZxpvSLJ9DpoV2sbtEiwnQYrIZJry6TzCtB2bNvXQ==}peerDependencies:- '@embedpdf/core': 2.14.4+ '@embedpdf/core': 2.15.0+ '@embedpdf/plugin-annotation': 2.15.0+ '@embedpdf/plugin-i18n': 2.15.0preact: ^10.26.4react: '>=16.8.0'react-dom: '>=16.8.0'svelte: '>=5 <6'vue: '>=3.2.0'- '@embedpdf/[email protected]':- resolution: {integrity: sha512-8w6ZUdwRcBhNCQjlS8mFvsMXI/wr1Q7DljwlFmKaEQyM9vXm2rI9WGN0z9ffjKHlsYn0yg98pqyPLtTevH1P7Q==}+ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-39EojqobHmvSvk2ejKeh58m43ApGS3cie/sVZP+pkXr6MRogX6+ivMa5GfoqBzh9wdZAZ3l4XTd+RQ4kFZ4aqQ==}peerDependencies:- '@embedpdf/core': 2.14.4- '@embedpdf/plugin-interaction-manager': 2.14.4+ '@embedpdf/core': 2.15.0+ '@embedpdf/plugin-render': 2.15.0preact: ^10.26.4react: '>=16.8.0'react-dom: '>=16.8.0'svelte: '>=5 <6'vue: '>=3.2.0'- '@embedpdf/[email protected]':- resolution: {integrity: sha512-80D+R2uXoTsmQXFpGGhtapv3I45WNzTSIkcD3VvLywjS2MHwgCNY51RQsn5bc3HINZW9d/SX1F39qiv4HzPp6A==}+ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-zBjKCToAkL1tYvkIjFCjsbfUzZ0QBPczL3wRy/IdNZ9CQuZrqqqp3xEFrI4Nz2o9XQd9heBlMA9Zo/yieuazqA==}peerDependencies:- '@embedpdf/core': 2.14.4- '@embedpdf/plugin-render': 2.14.4+ '@embedpdf/core': 2.15.0+ '@embedpdf/plugin-render': 2.15.0+ '@embedpdf/plugin-scroll': 2.15.0+ '@embedpdf/plugin-viewport': 2.15.0preact: ^10.26.4react: '>=16.8.0'react-dom: '>=16.8.0'svelte: '>=5 <6'vue: '>=3.2.0'- '@embedpdf/[email protected]':- resolution: {integrity: sha512-++1bzvU0Xqi6a1XeUOLAHU7D/FVUNobC/behSSn3WZnY/wIpYG3dXs5NbhNzeomIGXYHC4jCXbKGBPe5TNdoSw==}+ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-BmPI3LeqBgHzHjEIBUBuKBAVuq2z3L5feOyrUPgXnrcDthcuzr/kgIQQm1hBvBQG3GbjBVHtojupKeUDb+YUzA==}peerDependencies:- '@embedpdf/core': 2.14.4- '@embedpdf/plugin-render': 2.14.4- '@embedpdf/plugin-scroll': 2.14.4- '@embedpdf/plugin-viewport': 2.14.4+ '@embedpdf/core': 2.15.0preact: ^10.26.4react: '>=16.8.0'react-dom: '>=16.8.0'svelte: '>=5 <6'vue: '>=3.2.0'- '@embedpdf/[email protected]':- resolution: {integrity: sha512-ZhbDITPZ/h1Vd9cUbCPShSbH5RXd/biCw9w6fneTItruMauYIcTNUS2eWLJC0Yovhw7nu0TjRVYuTQ71jzs0dg==}+ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-MXNBQOitr1cAoCoBKwAR3O78eLtHBbIngOkWqgm6EpWTdoYDBVhZlvVcmwmjheZKjMJFnU3sFr98w6Qwix3Cjg==}peerDependencies:- '@embedpdf/core': 2.14.4+ '@embedpdf/core': 2.15.0preact: ^10.26.4react: '>=16.8.0'react-dom: '>=16.8.0'svelte: '>=5 <6'vue: '>=3.2.0'- '@embedpdf/[email protected]':- resolution: {integrity: sha512-a5kUjbG9sKMyO8qqDTrtL30VJ3dSEyNHHvszhfbvKtv4hppz/fSKS78vieu3lw48K11BoioImzCAF6Y3R0LMiw==}+ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-d+YhwqcQNZaaHczVGe4pbaAYQXWO4MEoivcW7jOpE31VnKqEAdjCMye8F0ctcF5OjgbXeb6AKCk4L4fDdLF4mg==}peerDependencies:- '@embedpdf/core': 2.14.4- '@embedpdf/plugin-scroll': 2.14.4- '@embedpdf/plugin-viewport': 2.14.4+ '@embedpdf/core': 2.15.0+ '@embedpdf/plugin-scroll': 2.15.0+ '@embedpdf/plugin-viewport': 2.15.0preact: ^10.26.4react: '>=16.8.0'react-dom: '>=16.8.0'svelte: '>=5 <6'vue: '>=3.2.0'- '@embedpdf/[email protected]':- resolution: {integrity: sha512-W7BZSNAQeUPQhi6l96Q4oFtg8Vgbt622LQL5ql0oZjyJNJRbYqCJIiJpR+5ZvK6S/x2MadZnYSzBJ/ekL6394A==}+ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-13UEMPpu5XrxmYI/MPiLtJC3R3b1g8ii3zfhQ3g1WpECybnwTuhBgwqaOvqw3rVCKCnXEgNMs4PBCzLyFpZZTw==}peerDependencies:preact: ^10.26.4react: '>=16.8.0'@@ -3608,6 +3842,9 @@ packages:resolution: {integrity: sha512-UrRKgp5sQmRnDy4TEwAUsu14XBUlzKB8U3hjIYDjcZ3Hbp86Jtftzxfgrv6E/ii/h78tsaZwAnAE8HwnHr0dPA==}+ resolution: {integrity: sha512-cuOPoI7WApyhBElTTb9oqsawRvZ0rHhaHwghRLlTuffoD1B2aDemlCruLeZrUIIdvG7gs9xeELEPm6PhuASqrg==}+resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}@@ -5954,17 +6191,19 @@ snapshots:dependencies:'@noble/ciphers': 1.3.0- '@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ '@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':dependencies:- '@embedpdf/engines': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))- '@embedpdf/models': 2.14.4+ '@embedpdf/engines': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0preact: 11.0.0-beta.0react: 19.2.3react-dom: 19.2.3([email protected])svelte: 5.56.3(@typescript-eslint/[email protected])vue: 3.5.38([email protected])- '@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ '@embedpdf/[email protected]': {}++ '@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':dependencies:'@embedpdf/fonts-arabic': 1.0.0'@embedpdf/fonts-hebrew': 1.0.0@@ -5973,8 +6212,8 @@ snapshots:'@embedpdf/fonts-latin': 1.0.0'@embedpdf/fonts-sc': 1.0.0'@embedpdf/fonts-tc': 1.0.0- '@embedpdf/models': 2.14.4- '@embedpdf/pdfium': 2.14.4+ '@embedpdf/models': 2.15.0+ '@embedpdf/pdfium': 2.15.0preact: 11.0.0-beta.0react: 19.2.3react-dom: 19.2.3([email protected])@@ -5995,130 +6234,310 @@ snapshots:'@embedpdf/[email protected]': {}- '@embedpdf/[email protected]': {}+ '@embedpdf/[email protected]': {}- '@embedpdf/[email protected]': {}+ '@embedpdf/[email protected]': {}- '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ ? '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'+ : dependencies:+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0+ '@embedpdf/plugin-history': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-interaction-manager': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-scroll': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-selection': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/utils': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':dependencies:- '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))- '@embedpdf/models': 2.14.4+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0preact: 11.0.0-beta.0react: 19.2.3react-dom: 19.2.3([email protected])svelte: 5.56.3(@typescript-eslint/[email protected])vue: 3.5.38([email protected])- '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':dependencies:- '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))- '@embedpdf/models': 2.14.4+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0preact: 11.0.0-beta.0react: 19.2.3react-dom: 19.2.3([email protected])svelte: 5.56.3(@typescript-eslint/[email protected])vue: 3.5.38([email protected])- '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ ? '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'+ : dependencies:+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0+ '@embedpdf/plugin-interaction-manager': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-render': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':dependencies:- '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))- '@embedpdf/models': 2.14.4+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0preact: 11.0.0-beta.0react: 19.2.3react-dom: 19.2.3([email protected])svelte: 5.56.3(@typescript-eslint/[email protected])vue: 3.5.38([email protected])- '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':dependencies:- '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))- '@embedpdf/models': 2.14.4+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0preact: 11.0.0-beta.0react: 19.2.3react-dom: 19.2.3([email protected])svelte: 5.56.3(@typescript-eslint/[email protected])vue: 3.5.38([email protected])- '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ ? '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'+ : dependencies:+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0+ '@embedpdf/plugin-annotation': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-history': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/utils': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':dependencies:- '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))- '@embedpdf/models': 2.14.4- '@embedpdf/plugin-viewport': 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0preact: 11.0.0-beta.0react: 19.2.3react-dom: 19.2.3([email protected])svelte: 5.56.3(@typescript-eslint/[email protected])vue: 3.5.38([email protected])- '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':dependencies:- '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))- '@embedpdf/models': 2.14.4+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0preact: 11.0.0-beta.0react: 19.2.3react-dom: 19.2.3([email protected])svelte: 5.56.3(@typescript-eslint/[email protected])vue: 3.5.38([email protected])- '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':dependencies:- '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))- '@embedpdf/models': 2.14.4- '@embedpdf/plugin-interaction-manager': 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))- '@embedpdf/utils': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0preact: 11.0.0-beta.0react: 19.2.3react-dom: 19.2.3([email protected])svelte: 5.56.3(@typescript-eslint/[email protected])vue: 3.5.38([email protected])- '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':dependencies:- '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))- '@embedpdf/models': 2.14.4- '@embedpdf/plugin-render': 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0preact: 11.0.0-beta.0react: 19.2.3react-dom: 19.2.3([email protected])svelte: 5.56.3(@typescript-eslint/[email protected])vue: 3.5.38([email protected])- ? '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'+ ? '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))': dependencies:- '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))- '@embedpdf/models': 2.14.4- '@embedpdf/plugin-render': 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))- '@embedpdf/plugin-scroll': 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))- '@embedpdf/plugin-viewport': 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0+ '@embedpdf/plugin-interaction-manager': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-viewport': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))preact: 11.0.0-beta.0react: 19.2.3react-dom: 19.2.3([email protected])svelte: 5.56.3(@typescript-eslint/[email protected])vue: 3.5.38([email protected])- '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':dependencies:- '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))- '@embedpdf/models': 2.14.4+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0preact: 11.0.0-beta.0react: 19.2.3react-dom: 19.2.3([email protected])svelte: 5.56.3(@typescript-eslint/[email protected])vue: 3.5.38([email protected])- ? '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'+ ? '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))': dependencies:- '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))- '@embedpdf/models': 2.14.4- '@embedpdf/plugin-scroll': 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))- '@embedpdf/plugin-viewport': 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0+ '@embedpdf/plugin-annotation': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-history': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-interaction-manager': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-selection': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/utils': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))preact: 11.0.0-beta.0react: 19.2.3react-dom: 19.2.3([email protected])svelte: 5.56.3(@typescript-eslint/[email protected])vue: 3.5.38([email protected])- '@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0+ '@embedpdf/plugin-viewport': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0+ '@embedpdf/plugin-interaction-manager': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/utils': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ ? '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'+ : dependencies:+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0+ '@embedpdf/plugin-annotation': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ ? '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'+ : dependencies:+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0+ '@embedpdf/plugin-annotation': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-i18n': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0+ '@embedpdf/plugin-render': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ ? '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'+ : dependencies:+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0+ '@embedpdf/plugin-render': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-scroll': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-viewport': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ ? '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'+ : dependencies:+ '@embedpdf/core': 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.15.0+ '@embedpdf/plugin-scroll': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-viewport': 2.15.0(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':dependencies:preact: 11.0.0-beta.0react: 19.2.3@@ -9089,6 +9508,8 @@ snapshots:+ [email protected]: {}+