@underverse-ui/underverse 2.0.41 → 2.0.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/components/DropdownMenu.tsx","../src/components/UEditor/url-safety.ts","../src/components/UEditor/async-insertion-position.ts","../src/components/UEditor/image-file-upload.ts","../src/components/UEditor/clipboard-images.ts","../src/components/UEditor/table-width-model.ts","../src/components/UEditor/clipboard-tables.ts","../src/components/UEditor/table-cell-commands.ts","../src/components/UEditor/table-dom-utils.ts","../src/components/UEditor/table-column-resize.ts","../node_modules/prosemirror-model/dist/index.js","../node_modules/prosemirror-transform/dist/index.js","../node_modules/prosemirror-state/dist/index.js","../node_modules/w3c-keyname/index.js","../node_modules/prosemirror-keymap/dist/index.js","../node_modules/prosemirror-tables/src/tablemap.ts","../node_modules/prosemirror-tables/src/schema.ts","../node_modules/prosemirror-tables/src/util.ts","../node_modules/prosemirror-tables/src/cellselection.ts","../node_modules/prosemirror-tables/src/fixtables.ts","../node_modules/prosemirror-tables/src/utils/convert.ts","../node_modules/prosemirror-tables/src/utils/move-row-in-array-of-rows.ts","../node_modules/prosemirror-tables/src/utils/query.ts","../node_modules/prosemirror-tables/src/utils/get-cells.ts","../node_modules/prosemirror-tables/src/utils/selection-range.ts","../node_modules/prosemirror-tables/src/utils/transpose.ts","../node_modules/prosemirror-tables/src/utils/move-column.ts","../node_modules/prosemirror-tables/src/utils/move-row.ts","../node_modules/prosemirror-tables/src/commands.ts","../node_modules/prosemirror-tables/src/copypaste.ts","../node_modules/prosemirror-tables/src/input.ts","../node_modules/prosemirror-tables/src/tableview.ts","../node_modules/prosemirror-tables/src/columnresizing.ts","../node_modules/prosemirror-tables/src/index.ts","../src/components/UEditor/table-layout-model.ts","../src/components/UEditor/table-size-utils.ts","../src/components/UEditor/table-formula.ts","../src/components/UEditor/table-formula-references.ts","../src/components/UEditor/inputs.tsx","../src/components/UEditor/link-commands.ts","../src/components/UEditor/toolbar.tsx","../src/components/UEditor/colors.tsx","../src/components/UEditor/figma-toolbar-icons.tsx","../src/components/UEditor/image-commands.ts","../src/components/UEditor/table-align-utils.ts","../src/components/UEditor/table-vertical-align-icons.tsx","../src/components/UEditor/typography-options.ts","../src/components/UEditor/editor-styles.ts"],"sourcesContent":["\"use client\";\n\nimport { cn } from \"../utils/cn\";\nimport React, { useState } from \"react\";\nimport { setRefValue } from \"../utils/react-compose\";\nimport { Popover } from \"./Popover\";\nimport { ChevronRight } from \"lucide-react\";\nimport { getBorderRadiusClass, type BorderMode } from \"../utils/radius\";\nimport { useUnderverseUIConfig } from \"../contexts/UnderverseConfigContext\";\nimport { formControlFixedClass, formControlOutlineClass, formControlSizeStyles, formControlValueClass, type FormControlSize } from \"../constants/form-control-size\";\n\ntype DropdownMenuContextValue = {\n closeMenu: () => void;\n closeOnSelect: boolean;\n cancelHoverClose: () => void;\n scheduleHoverClose: () => void;\n};\n\nconst DropdownMenuContext = React.createContext<DropdownMenuContextValue | null>(null);\n\nexport function useDropdownMenuClose() {\n return React.useContext(DropdownMenuContext)?.closeMenu ?? (() => {});\n}\n\n/** Public props for the `DropdownMenu` component. */\nexport interface DropdownMenuProps {\n trigger: React.ReactElement;\n children?: React.ReactNode;\n className?: string;\n contentClassName?: string;\n placement?: \"top\" | \"bottom\" | \"left\" | \"right\" | \"top-start\" | \"bottom-start\" | \"top-end\" | \"bottom-end\";\n closeOnSelect?: boolean;\n disabled?: boolean;\n // Alternative API props\n isOpen?: boolean;\n onOpenChange?: (open: boolean) => void;\n openOnHover?: boolean;\n hoverCloseDelay?: number;\n items?: Array<{\n label: string;\n icon?: React.ComponentType<any>;\n onClick: () => void;\n disabled?: boolean;\n destructive?: boolean;\n }>;\n borderMode?: BorderMode;\n /** Resolve the document element that should receive the menu portal. */\n getPortalContainer?: () => HTMLElement | null;\n}\n\nfunction useResettingIndex(resetToken: unknown) {\n const [state, setState] = React.useState<{ resetToken: unknown; index: number }>({ resetToken, index: -1 });\n const activeIndex = Object.is(state.resetToken, resetToken) ? state.index : -1;\n\n const setActiveIndex = React.useCallback((nextIndex: React.SetStateAction<number>) => {\n setState((prev) => {\n const prevIndex = Object.is(prev.resetToken, resetToken) ? prev.index : -1;\n return {\n resetToken,\n index: typeof nextIndex === \"function\" ? (nextIndex as (value: number) => number)(prevIndex) : nextIndex,\n };\n });\n }, [resetToken]);\n\n return [activeIndex, setActiveIndex] as const;\n}\n\nconst DropdownMenu: React.FC<DropdownMenuProps> = ({\n trigger,\n children,\n className,\n contentClassName,\n placement = \"bottom-start\",\n closeOnSelect = true,\n disabled = false,\n isOpen,\n onOpenChange,\n openOnHover = false,\n hoverCloseDelay = 120,\n items,\n borderMode,\n getPortalContainer,\n}) => {\n const [internalOpen, setInternalOpen] = useState(false);\n const open = isOpen !== undefined ? isOpen : internalOpen;\n const setOpen = React.useCallback(\n (nextOpen: boolean) => {\n if (isOpen === undefined) {\n setInternalOpen(nextOpen);\n }\n onOpenChange?.(nextOpen);\n },\n [isOpen, onOpenChange]\n );\n const triggerRef = React.useRef<HTMLElement>(null);\n const menuRef = React.useRef<HTMLDivElement>(null);\n const itemsRef = React.useRef<HTMLButtonElement[]>([]);\n const [activeIndex, setActiveIndex] = useResettingIndex(open);\n const parentMenu = React.useContext(DropdownMenuContext);\n const hoverCloseTimeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const cancelHoverClose = React.useCallback(() => {\n if (hoverCloseTimeoutRef.current === null) return;\n clearTimeout(hoverCloseTimeoutRef.current);\n hoverCloseTimeoutRef.current = null;\n }, []);\n\n const scheduleHoverClose = React.useCallback(() => {\n if (!openOnHover) return;\n cancelHoverClose();\n hoverCloseTimeoutRef.current = setTimeout(() => {\n hoverCloseTimeoutRef.current = null;\n setOpen(false);\n }, hoverCloseDelay);\n }, [cancelHoverClose, hoverCloseDelay, openOnHover, setOpen]);\n\n React.useEffect(() => () => cancelHoverClose(), [cancelHoverClose]);\n\n const closeMenu = React.useCallback(() => {\n cancelHoverClose();\n setOpen(false);\n parentMenu?.closeMenu();\n }, [cancelHoverClose, parentMenu, setOpen]);\n\n const getEnabledMenuItems = React.useCallback(() => {\n const menuEl = menuRef.current;\n if (!menuEl) return [];\n\n return Array.from(menuEl.querySelectorAll<HTMLButtonElement>(\"[data-dropdown-menu-item]\")).filter((el) => !el.disabled);\n }, []);\n\n const focusMenuItem = React.useCallback((index: number) => {\n const enabled = getEnabledMenuItems();\n const item = enabled[index];\n if (!item) return;\n setActiveIndex(index);\n item.focus();\n item.scrollIntoView({ block: \"nearest\" });\n }, [getEnabledMenuItems, setActiveIndex]);\n\n const globalConfig = useUnderverseUIConfig();\n const resolvedBorderMode = borderMode ?? globalConfig.dropdownMenu?.borderMode ?? globalConfig.borderMode;\n\n // Keyboard navigation inside the menu (Arrow keys/Home/End)\n React.useEffect(() => {\n if (!open) return;\n\n const handleKeyNav = (e: KeyboardEvent) => {\n const triggerEl = triggerRef.current;\n const menuEl = menuRef.current;\n const active = menuEl?.ownerDocument.activeElement as Node | null;\n if (!active || !triggerEl || !menuEl) return;\n const isInMenu = menuEl.contains(active);\n const isOnTrigger = triggerEl.contains(active);\n\n const enabled = getEnabledMenuItems();\n if (enabled.length === 0) return;\n const currentIndex = enabled.findIndex((el) => el === active);\n const baseIndex = currentIndex >= 0 ? currentIndex : activeIndex;\n\n if (e.key === \"ArrowDown\") {\n e.preventDefault();\n const next = (baseIndex + 1 + enabled.length) % enabled.length;\n focusMenuItem(next);\n } else if (e.key === \"ArrowUp\") {\n e.preventDefault();\n const prev = (baseIndex - 1 + enabled.length) % enabled.length;\n focusMenuItem(prev);\n } else if (e.key === \"Home\") {\n e.preventDefault();\n focusMenuItem(0);\n } else if (e.key === \"End\") {\n e.preventDefault();\n focusMenuItem(enabled.length - 1);\n } else if (e.key === \"Escape\" && (isInMenu || isOnTrigger)) {\n e.preventDefault();\n closeMenu();\n const focusTarget = triggerEl.matches(\"button,a,input,select,textarea,[tabindex]\")\n ? triggerEl\n : triggerEl.querySelector<HTMLElement>(\"button,a,input,select,textarea,[tabindex]\");\n focusTarget?.focus();\n }\n };\n\n const menuDocument = menuRef.current?.ownerDocument;\n if (!menuDocument) return;\n menuDocument.addEventListener(\"keydown\", handleKeyNav, true);\n return () => {\n menuDocument.removeEventListener(\"keydown\", handleKeyNav, true);\n };\n }, [open, activeIndex, closeMenu, focusMenuItem, getEnabledMenuItems]);\n\n const menuContext = React.useMemo<DropdownMenuContextValue>(\n () => ({\n closeMenu,\n closeOnSelect,\n cancelHoverClose,\n scheduleHoverClose,\n }),\n [cancelHoverClose, closeMenu, closeOnSelect, scheduleHoverClose],\n );\n\n const handleItemClick = (itemOnClick: () => void) => {\n itemOnClick();\n if (closeOnSelect) {\n closeMenu();\n }\n };\n\n const menuBody = (\n <DropdownMenuContext.Provider value={menuContext}>\n <div\n ref={menuRef}\n data-dropdown-menu\n data-state={open ? \"open\" : \"closed\"}\n role=\"menu\"\n className={cn(\"min-w-40\", className)}\n onMouseEnter={openOnHover ? () => {\n cancelHoverClose();\n parentMenu?.cancelHoverClose();\n } : undefined}\n onMouseLeave={openOnHover ? () => {\n scheduleHoverClose();\n parentMenu?.scheduleHoverClose();\n } : undefined}\n >\n {items\n ? items.map((item, index) => {\n const IconComponent = item.icon;\n return (\n <button\n key={index}\n ref={(el) => {\n if (el) itemsRef.current[index] = el;\n }}\n onClick={() => handleItemClick(item.onClick)}\n disabled={item.disabled}\n role=\"menuitem\"\n data-dropdown-menu-item=\"\"\n tabIndex={-1}\n style={{\n animationDelay: open ? `${Math.min(index * 20, 200)}ms` : \"0ms\",\n }}\n className={cn(\n \"dropdown-item flex w-full items-center gap-2 px-2.5 py-1.5 text-sm\",\n resolvedBorderMode ? getBorderRadiusClass(resolvedBorderMode) : \"rounded-lg\",\n \"outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\",\n \"hover:bg-accent hover:text-accent-foreground\",\n \"focus:bg-accent focus:text-accent-foreground\",\n \"disabled:opacity-50 disabled:cursor-not-allowed\",\n item.destructive && \"text-destructive hover:bg-destructive/10 focus:bg-destructive/10\",\n )}\n >\n {IconComponent && <IconComponent aria-hidden=\"true\" className=\"h-4 w-4\" />}\n {item.label}\n </button>\n );\n })\n : children}\n </div>\n </DropdownMenuContext.Provider>\n );\n\n const triggerProps = trigger.props as React.HTMLAttributes<HTMLElement> & { ref?: React.Ref<HTMLElement> };\n const {\n ref: childRef,\n onKeyDown: triggerOnKeyDown,\n onClick: triggerOnClick,\n onMouseEnter: triggerOnMouseEnter,\n onMouseLeave: triggerOnMouseLeave,\n } = triggerProps;\n const setTriggerNode = React.useCallback((node: HTMLElement | null) => {\n setRefValue(childRef, node);\n triggerRef.current = node;\n }, [childRef]);\n const handleTriggerKeyDown = React.useCallback((event: React.KeyboardEvent<HTMLElement>) => {\n const triggerWindow = event.currentTarget.ownerDocument.defaultView;\n const scheduleFrame = (callback: FrameRequestCallback) => {\n if (triggerWindow) triggerWindow.requestAnimationFrame(callback);\n else callback(0);\n };\n if (!disabled) {\n if (!event.altKey && !event.ctrlKey && !event.metaKey && event.key === \"ArrowDown\") {\n event.preventDefault();\n setOpen(true);\n scheduleFrame(() => focusMenuItem(0));\n } else if (!event.altKey && !event.ctrlKey && !event.metaKey && event.key === \"ArrowUp\") {\n event.preventDefault();\n setOpen(true);\n scheduleFrame(() => {\n const enabled = getEnabledMenuItems();\n focusMenuItem(enabled.length - 1);\n });\n } else if (event.key === \"Escape\") {\n event.preventDefault();\n setOpen(false);\n }\n }\n triggerOnKeyDown?.(event);\n }, [disabled, focusMenuItem, getEnabledMenuItems, setOpen, triggerOnKeyDown]);\n const handleTriggerClick = React.useCallback((event: React.MouseEvent<HTMLElement>) => {\n if (openOnHover && !disabled) {\n cancelHoverClose();\n setOpen(true);\n }\n triggerOnClick?.(event);\n }, [cancelHoverClose, disabled, openOnHover, setOpen, triggerOnClick]);\n const handleTriggerMouseEnter = React.useCallback((event: React.MouseEvent<HTMLElement>) => {\n if (openOnHover && !disabled) {\n cancelHoverClose();\n parentMenu?.cancelHoverClose();\n setOpen(true);\n }\n triggerOnMouseEnter?.(event);\n }, [cancelHoverClose, disabled, openOnHover, parentMenu, setOpen, triggerOnMouseEnter]);\n const handleTriggerMouseLeave = React.useCallback((event: React.MouseEvent<HTMLElement>) => {\n scheduleHoverClose();\n triggerOnMouseLeave?.(event);\n }, [scheduleHoverClose, triggerOnMouseLeave]);\n\n // React invokes these ref/event callbacks after render; cloneElement only forwards them to the trigger.\n // eslint-disable-next-line react-hooks/refs\n const enhancedTrigger = React.cloneElement(trigger as React.ReactElement<any>, {\n ...triggerProps,\n ref: setTriggerNode,\n \"aria-haspopup\": \"menu\",\n \"aria-expanded\": open,\n onKeyDown: handleTriggerKeyDown,\n onClick: handleTriggerClick,\n onMouseEnter: handleTriggerMouseEnter,\n onMouseLeave: handleTriggerMouseLeave,\n });\n\n return (\n <Popover\n open={open}\n onOpenChange={setOpen}\n trigger={enhancedTrigger}\n placement={placement}\n disabled={disabled}\n borderMode={resolvedBorderMode}\n getPortalContainer={getPortalContainer}\n contentClassName={cn(\"p-1\", contentClassName)}\n >\n {menuBody}\n </Popover>\n );\n};\n\n/** Public props for the `DropdownMenuItem` component. */\nexport interface DropdownMenuItemProps {\n children?: React.ReactNode;\n label?: string;\n description?: string;\n icon?: React.ComponentType<{ className?: string }>;\n onClick?: () => void;\n disabled?: boolean;\n destructive?: boolean;\n active?: boolean;\n shortcut?: string;\n className?: string;\n closeOnSelect?: boolean;\n borderMode?: BorderMode;\n}\n\nexport const DropdownMenuItem: React.FC<DropdownMenuItemProps> = ({\n children,\n label,\n description,\n icon: Icon,\n onClick,\n disabled,\n destructive,\n active,\n shortcut,\n className,\n closeOnSelect,\n borderMode,\n}) => {\n const menu = React.useContext(DropdownMenuContext);\n const shouldCloseOnSelect = closeOnSelect ?? menu?.closeOnSelect ?? false;\n \n const globalConfig = useUnderverseUIConfig();\n const resolvedBorderMode = borderMode ?? globalConfig.dropdownMenu?.borderMode ?? globalConfig.borderMode;\n\n return (\n <button\n type=\"button\"\n role=\"menuitem\"\n onClick={() => {\n onClick?.();\n if (shouldCloseOnSelect) {\n menu?.closeMenu();\n }\n }}\n disabled={disabled}\n onMouseDown={(e) => e.preventDefault()}\n data-dropdown-menu-item=\"\"\n tabIndex={-1}\n className={cn(\n \"flex w-full items-center gap-2 px-3 py-2 text-sm transition-colors group cursor-pointer\",\n resolvedBorderMode ? getBorderRadiusClass(resolvedBorderMode) : \"rounded-lg\",\n \"hover:bg-accent hover:text-accent-foreground\",\n \"focus:bg-accent focus:text-accent-foreground focus:outline-none\",\n \"disabled:opacity-50 disabled:cursor-not-allowed\",\n destructive && \"text-destructive hover:bg-destructive/10 focus:bg-destructive/10\",\n active && \"bg-primary/10 text-primary\",\n className,\n )}\n >\n {Icon && <Icon aria-hidden=\"true\" className={cn(\"w-4 h-4 shrink-0\", active ? \"text-primary\" : \"opacity-60 group-hover:opacity-100\")} />}\n <div className=\"flex-1 text-left\">\n {label && <div className={cn(\"font-medium\", description && \"leading-tight\")}>{label}</div>}\n {description && <div className=\"text-xs text-muted-foreground\">{description}</div>}\n {children}\n </div>\n {shortcut && <span className=\"ml-2 text-xs text-muted-foreground opacity-60\">{shortcut}</span>}\n {active && (\n <svg aria-hidden=\"true\" className=\"w-4 h-4 text-primary shrink-0\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\">\n <polyline points=\"20 6 9 17 4 12\" />\n </svg>\n )}\n </button>\n );\n};\n\nexport const DropdownMenuSeparator: React.FC<{ className?: string }> = ({ className }) => <div role=\"separator\" className={cn(\"h-px bg-border my-1\", className)} />;\n\nexport const DropdownMenuSub: React.FC<{\n label: string;\n icon?: React.ComponentType<{ className?: string }>;\n disabled?: boolean;\n borderMode?: BorderMode;\n getPortalContainer?: () => HTMLElement | null;\n children: React.ReactNode;\n}> = ({ label, icon: Icon, disabled, borderMode, getPortalContainer, children }) => {\n const globalConfig = useUnderverseUIConfig();\n const resolvedBorderMode = borderMode ?? globalConfig.dropdownMenu?.borderMode ?? globalConfig.borderMode;\n\n return (\n <DropdownMenu\n trigger={\n <button\n type=\"button\"\n role=\"menuitem\"\n data-dropdown-menu-item=\"\"\n tabIndex={-1}\n disabled={disabled}\n onMouseDown={(e) => e.preventDefault()}\n className={cn(\n \"flex w-full items-center gap-2 px-3 py-2 text-sm transition-colors cursor-pointer\",\n resolvedBorderMode ? getBorderRadiusClass(resolvedBorderMode) : \"rounded-lg\",\n \"hover:bg-accent hover:text-accent-foreground\",\n \"focus:bg-accent focus:text-accent-foreground focus:outline-none\",\n \"disabled:opacity-50 disabled:cursor-not-allowed\",\n )}\n >\n {Icon && <Icon aria-hidden=\"true\" className=\"w-4 h-4 shrink-0 opacity-60\" />}\n <span className=\"flex-1 text-left\">{label}</span>\n <ChevronRight aria-hidden=\"true\" className=\"w-3 h-3 opacity-50\" />\n </button>\n }\n placement=\"right\"\n openOnHover\n getPortalContainer={getPortalContainer}\n >\n {children}\n </DropdownMenu>\n );\n};\n\nexport interface SelectDropdownProps {\n options: string[];\n value?: string;\n onChange: (value: string) => void;\n placeholder?: string;\n className?: string;\n borderMode?: BorderMode;\n size?: FormControlSize;\n /** Resolve the document element that should receive the menu portal. */\n getPortalContainer?: () => HTMLElement | null;\n}\n\nexport const SelectDropdown: React.FC<SelectDropdownProps> = ({\n options,\n value,\n onChange,\n placeholder = \"Select...\",\n className,\n borderMode,\n size = \"md\",\n getPortalContainer,\n}) => {\n const globalConfig = useUnderverseUIConfig();\n const resolvedBorderMode = borderMode ?? globalConfig.dropdownMenu?.borderMode ?? globalConfig.borderMode;\n \n return (\n <DropdownMenu\n trigger={\n <button\n className={cn(\n \"inline-flex items-center justify-between gap-2 bg-background\",\n formControlOutlineClass,\n resolvedBorderMode ? getBorderRadiusClass(resolvedBorderMode) : \"rounded-2xl\",\n formControlFixedClass,\n formControlSizeStyles[size].control,\n \"hover:bg-accent/50\",\n className,\n )}\n >\n <span className={cn(formControlValueClass, \"max-w-64 text-foreground/90\")}>{value || placeholder}</span>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 20 20\" fill=\"none\" className=\"shrink-0 opacity-70\">\n <path d=\"M6 8l4 4 4-4\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n </button>\n }\n items={options.map((option) => ({\n label: option,\n onClick: () => onChange(option),\n }))}\n borderMode={resolvedBorderMode}\n getPortalContainer={getPortalContainer}\n />\n );\n};\n\nexport { DropdownMenu };\nexport default DropdownMenu;\n","export type UEditorUrlKind = \"link\" | \"image\" | \"file\";\n\nconst LINK_PROTOCOLS = new Set([\"http:\", \"https:\", \"mailto:\", \"tel:\"]);\nconst IMAGE_PROTOCOLS = new Set([\"http:\", \"https:\"]);\nconst FILE_PROTOCOLS = new Set([\"http:\", \"https:\", \"blob:\"]);\n\nfunction normalizeUrlInput(raw: string) {\n return raw.trim().replace(/[\\u0000-\\u001F\\u007F\\s]+/g, \"\");\n}\n\nfunction isProtocolRelativeUrl(value: string) {\n return value.startsWith(\"//\");\n}\n\nfunction isRelativeUrl(value: string) {\n return value.startsWith(\"/\") || value.startsWith(\"./\") || value.startsWith(\"../\") || value.startsWith(\"#\");\n}\n\nfunction isValidIpv4Hostname(hostname: string) {\n const parts = hostname.split(\".\");\n return parts.length === 4 && parts.every((part) => /^\\d{1,3}$/.test(part) && Number(part) <= 255);\n}\n\nfunction isValidWebHostname(hostname: string) {\n const normalized = hostname.toLowerCase();\n if (normalized === \"localhost\" || isValidIpv4Hostname(normalized)) return true;\n if (normalized.startsWith(\"[\") && normalized.endsWith(\"]\") && normalized.includes(\":\")) return true;\n\n const labels = normalized.split(\".\");\n if (labels.length < 2) return false;\n\n const validLabel = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)$/;\n return labels.every((label) => validLabel.test(label)) && /[a-z]/.test(labels.at(-1) ?? \"\");\n}\n\nfunction isValidLinkUrl(parsed: URL) {\n if (parsed.protocol === \"http:\" || parsed.protocol === \"https:\") {\n return isValidWebHostname(parsed.hostname);\n }\n\n if (parsed.protocol === \"mailto:\") {\n return /^[^@]+@[^@]+\\.[^@]+$/.test(decodeURIComponent(parsed.pathname));\n }\n\n if (parsed.protocol === \"tel:\") {\n const number = decodeURIComponent(parsed.pathname);\n return /^\\+?[\\d().-]+$/.test(number) && (number.match(/\\d/g)?.length ?? 0) >= 3;\n }\n\n return false;\n}\n\nfunction isDataImageUrl(value: string) {\n return /^data:image\\/(?:png|jpe?g|gif|webp|svg\\+xml|bmp|x-icon|avif);base64,/i.test(value);\n}\n\nfunction isDataFileUrl(value: string) {\n return /^data:[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*(?:;[a-z0-9!#$&^_.+-]+=[^;,]*)*;base64,[a-z0-9+/]*={0,2}$/i.test(value);\n}\n\nexport function isSafeUEditorUrl(raw: string, kind: UEditorUrlKind): boolean {\n const value = normalizeUrlInput(raw);\n if (!value) return false;\n // Attribute delimiters must be percent-encoded before a URL reaches the\n // editor. Rejecting them here keeps every HTML serializer as defense in depth.\n if (/[<>'\"`]/.test(value)) return false;\n\n if (kind === \"image\" && isDataImageUrl(value)) return true;\n if (kind === \"file\" && isDataFileUrl(value)) return true;\n if (isProtocolRelativeUrl(value)) return false;\n if (isRelativeUrl(value)) return true;\n\n try {\n const parsed = new URL(value);\n if (kind === \"image\") return IMAGE_PROTOCOLS.has(parsed.protocol);\n if (kind === \"file\") return FILE_PROTOCOLS.has(parsed.protocol);\n return LINK_PROTOCOLS.has(parsed.protocol) && isValidLinkUrl(parsed);\n } catch {\n return false;\n }\n}\n\nexport function sanitizeUEditorUrl(raw: string, kind: UEditorUrlKind): string {\n const value = raw.trim();\n if (!value) return \"\";\n\n if (isSafeUEditorUrl(value, kind)) return normalizeUrlInput(value);\n\n if (kind === \"link\" && !isProtocolRelativeUrl(value) && !/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value)) {\n const withProtocol = `https://${value}`;\n return isSafeUEditorUrl(withProtocol, kind) ? withProtocol : \"\";\n }\n\n return \"\";\n}\n","import type { Editor } from \"@tiptap/core\";\nimport type { Transaction } from \"@tiptap/pm/state\";\n\n/** Keeps an insertion point attached to the same document location while an async task is running. */\nexport function trackEditorInsertionPosition(editor: Editor, initialPosition = editor.state.selection.from) {\n let position = initialPosition;\n const mapPosition = ({ transaction }: { transaction: Transaction }) => {\n position = transaction.mapping.map(position, 1);\n };\n\n editor.on(\"transaction\", mapPosition);\n return {\n get current() {\n return position;\n },\n stop() {\n editor.off(\"transaction\", mapPosition);\n },\n };\n}\n","import { sanitizeUEditorUrl } from \"./url-safety\";\n\nexport type UEditorResolvedImageFile = {\n file: File;\n src: string;\n};\n\nexport type ResolveUEditorImageFilesOptions = {\n maxFileSize: number;\n allowedMimeTypes: string[];\n upload?: (file: File) => Promise<string> | string;\n fallbackToDataUrl: boolean;\n insertMode: \"base64\" | \"upload\";\n onError?: (error: Error, file: File) => void;\n};\n\nexport function fileToDataUrl(file: File): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(String(reader.result ?? \"\"));\n reader.onerror = () => reject(reader.error ?? new Error(\"Failed to read image file.\"));\n reader.readAsDataURL(file);\n });\n}\n\nasync function resolveImageSource(file: File, options: ResolveUEditorImageFilesOptions) {\n if (options.insertMode === \"upload\") {\n if (!options.upload) {\n if (!options.fallbackToDataUrl) {\n throw new Error(\"Image upload handler is not configured.\");\n }\n } else {\n try {\n const uploadedUrl = await options.upload(file);\n const safeUploadedUrl = sanitizeUEditorUrl(uploadedUrl, \"image\");\n if (safeUploadedUrl) return safeUploadedUrl;\n if (!options.fallbackToDataUrl) {\n throw new Error(\"Image upload returned an invalid URL.\");\n }\n } catch (error) {\n if (!options.fallbackToDataUrl) throw error;\n }\n }\n }\n\n const dataUrl = await fileToDataUrl(file);\n const safeDataUrl = sanitizeUEditorUrl(dataUrl, \"image\");\n if (!safeDataUrl) throw new Error(\"Image file could not be converted to a safe data URL.\");\n return safeDataUrl;\n}\n\nexport async function resolveUEditorImageFiles(\n files: File[],\n options: ResolveUEditorImageFilesOptions,\n) {\n let hadError = false;\n const reportError = (error: Error, file: File) => {\n hadError = true;\n options.onError?.(error, file);\n };\n\n const validFiles = files.filter((file) => {\n if (!file.type.startsWith(\"image/\") || (options.allowedMimeTypes.length > 0 && !options.allowedMimeTypes.includes(file.type))) {\n reportError(new Error(`Unsupported image type: ${file.type || \"unknown\"}.`), file);\n return false;\n }\n if (file.size > options.maxFileSize) {\n reportError(new Error(`Image exceeds the ${options.maxFileSize}-byte size limit.`), file);\n return false;\n }\n return true;\n });\n\n const results = await Promise.all(validFiles.map(async (file): Promise<UEditorResolvedImageFile | null> => {\n try {\n return { file, src: await resolveImageSource(file, options) };\n } catch (error) {\n reportError(error instanceof Error ? error : new Error(\"Image upload failed.\"), file);\n return null;\n }\n }));\n\n return {\n images: results.filter((image): image is UEditorResolvedImageFile => image !== null),\n hadError,\n };\n}\n","import { Extension } from \"@tiptap/core\";\nimport { Plugin } from \"@tiptap/pm/state\";\nimport { getClipboardTableContent, getClipboardTsvTableContent, hasClipboardHtmlTable } from \"./clipboard-tables\";\nimport { trackEditorInsertionPosition } from \"./async-insertion-position\";\nimport { resolveUEditorImageFiles } from \"./image-file-upload\";\n\nexport type ClipboardImagesOptions = {\n maxFileSize: number;\n allowedMimeTypes: string[];\n upload?: (file: File) => Promise<string> | string;\n fallbackToDataUrl: boolean;\n insertMode: \"base64\" | \"upload\";\n onError?: (error: Error, file: File) => void;\n};\n\nexport const DEFAULT_UEDITOR_IMAGE_MAX_FILE_SIZE = 10 * 1024 * 1024;\nexport const DEFAULT_UEDITOR_IMAGE_MIME_TYPES = [\"image/png\", \"image/jpeg\", \"image/webp\", \"image/gif\", \"image/svg+xml\"];\n\nfunction getImageFiles(dataTransfer: DataTransfer | null): File[] {\n if (!dataTransfer) return [];\n\n // Some browsers expose the *same* pasted/dropped image both in `items` and `files`.\n // Prefer `items` when available to avoid duplicate inserts.\n const itemFiles: File[] = [];\n const byKey = new Map<string, File>();\n\n for (const item of Array.from(dataTransfer.items ?? [])) {\n if (item.kind !== \"file\") continue;\n if (!item.type.startsWith(\"image/\")) continue;\n const file = item.getAsFile();\n if (!file) continue;\n byKey.set(`${file.name}:${file.size}:${file.lastModified}`, file);\n }\n\n itemFiles.push(...Array.from(byKey.values()));\n if (itemFiles.length > 0) return itemFiles;\n\n for (const file of Array.from(dataTransfer.files ?? [])) {\n if (!file.type.startsWith(\"image/\")) continue;\n byKey.set(`${file.name}:${file.size}:${file.lastModified}`, file);\n }\n\n return Array.from(byKey.values());\n}\n\nexport const ClipboardImages = Extension.create<ClipboardImagesOptions>({\n name: \"clipboardImages\",\n\n addOptions() {\n return {\n maxFileSize: DEFAULT_UEDITOR_IMAGE_MAX_FILE_SIZE,\n allowedMimeTypes: DEFAULT_UEDITOR_IMAGE_MIME_TYPES,\n upload: undefined,\n fallbackToDataUrl: true,\n insertMode: \"base64\",\n onError: undefined,\n };\n },\n\n addProseMirrorPlugins() {\n const editor = this.editor;\n const options = this.options;\n\n const insertFiles = async (files: File[], selectionPos?: number) => {\n const trackedPosition = trackEditorInsertionPosition(editor, selectionPos);\n try {\n const { images } = await resolveUEditorImageFiles(files, {\n maxFileSize: options.maxFileSize,\n allowedMimeTypes: options.allowedMimeTypes,\n upload: options.upload,\n fallbackToDataUrl: options.fallbackToDataUrl,\n insertMode: options.insertMode,\n onError: options.onError,\n });\n if (editor.isDestroyed || images.length === 0) return;\n\n const content = images.map((image) => ({\n type: \"image\",\n attrs: { src: image.src, alt: image.file.name },\n }));\n editor.commands.insertContentAt(trackedPosition.current, content, { updateSelection: false });\n } finally {\n trackedPosition.stop();\n }\n };\n\n return [\n new Plugin({\n props: {\n handlePaste: (_view, event) => {\n if (!event || !event.clipboardData) return false;\n\n const tableContent = getClipboardTableContent(event.clipboardData);\n if (tableContent) {\n event.preventDefault();\n editor.chain().focus().insertContent(tableContent).run();\n return true;\n }\n\n // Let ProseMirror preserve surrounding rich text and multiple tables.\n if (hasClipboardHtmlTable(event.clipboardData)) return false;\n\n const tsvTableContent = getClipboardTsvTableContent(event.clipboardData);\n if (tsvTableContent) {\n event.preventDefault();\n editor.chain().focus().insertContent(tsvTableContent).run();\n return true;\n }\n\n const files = getImageFiles(event.clipboardData);\n if (files.length === 0) return false;\n\n event.preventDefault();\n void insertFiles(files);\n return true;\n },\n handleDrop: (view, event, _slice, moved) => {\n if (moved) return false;\n const DragEventCtor = view.dom.ownerDocument.defaultView?.DragEvent;\n if (!DragEventCtor || !(event instanceof DragEventCtor)) return false;\n const files = getImageFiles(event.dataTransfer);\n if (files.length === 0) return false;\n\n const pos = view.posAtCoords({ left: event.clientX, top: event.clientY })?.pos;\n event.preventDefault();\n void insertFiles(files, pos);\n return true;\n },\n },\n }),\n ];\n },\n});\n","import type { Node as ProseMirrorNode } from \"@tiptap/pm/model\";\n\nexport const TABLE_WIDTH_BASIS_POINTS = 10_000;\nexport const DEFAULT_RESPONSIVE_TABLE_WIDTH_BP = TABLE_WIDTH_BASIS_POINTS;\n// Keep responsive widths bounded so malformed pasted HTML cannot create an\n// effectively infinite layout. 1000% also lines up with the 8192px resize cap\n// for the editor sizes we support in practice.\nexport const MAX_RESPONSIVE_TABLE_WIDTH_BP = 100_000;\n\nexport type UEditorTableWidthMode = \"fixed\" | \"responsive\";\n\nfunction positiveNumber(value: unknown, fallback: number) {\n const number = Number(value);\n return Number.isFinite(number) && number > 0 ? number : fallback;\n}\n\nexport function clampTableBasisPoints(\n value: unknown,\n fallback = TABLE_WIDTH_BASIS_POINTS,\n maximum = TABLE_WIDTH_BASIS_POINTS,\n) {\n const number = Number(value);\n if (!Number.isFinite(number)) return fallback;\n return Math.min(maximum, Math.max(0, Math.round(number)));\n}\n\nexport function clampResponsiveTableWidthBp(\n value: unknown,\n fallback = DEFAULT_RESPONSIVE_TABLE_WIDTH_BP,\n) {\n return Math.max(1, clampTableBasisPoints(value, fallback, MAX_RESPONSIVE_TABLE_WIDTH_BP));\n}\n\nexport function normalizeTableWidthMode(value: unknown): UEditorTableWidthMode {\n return value === \"responsive\" || value === \"full\" ? \"responsive\" : \"fixed\";\n}\n\nexport function parsePercentageToBasisPoints(\n value: string | null | undefined,\n maximum = MAX_RESPONSIVE_TABLE_WIDTH_BP,\n) {\n if (!value) return null;\n const match = value.trim().match(/^(-?\\d+(?:\\.\\d+)?)%$/);\n if (!match) return null;\n const percentage = Number.parseFloat(match[1]);\n if (!Number.isFinite(percentage)) return null;\n return clampTableBasisPoints(percentage * 100, TABLE_WIDTH_BASIS_POINTS, maximum);\n}\n\nexport function formatBasisPointsAsPercentage(value: number) {\n const percentage = clampTableBasisPoints(value, 0, MAX_RESPONSIVE_TABLE_WIDTH_BP) / 100;\n return `${Number.parseFloat(percentage.toFixed(2))}%`;\n}\n\nexport function parseColumnRatios(value: unknown) {\n const parts = Array.isArray(value)\n ? value\n : typeof value === \"string\"\n ? value.split(\",\")\n : [];\n const ratios = parts.map((part) => Number(part));\n return ratios.length > 0 && ratios.every((ratio) => Number.isFinite(ratio) && ratio > 0)\n ? ratios\n : null;\n}\n\nexport function normalizeColumnRatios(values: readonly number[] | null | undefined, columnCount: number) {\n if (columnCount <= 0) return [];\n\n const source = values?.length === columnCount\n ? values.map((value) => positiveNumber(value, 1))\n : Array.from({ length: columnCount }, () => 1);\n const sourceTotal = source.reduce((sum, value) => sum + value, 0);\n const normalized = source.map((value) => Math.max(1, Math.round((value / sourceTotal) * TABLE_WIDTH_BASIS_POINTS)));\n let difference = TABLE_WIDTH_BASIS_POINTS - normalized.reduce((sum, value) => sum + value, 0);\n\n while (difference !== 0) {\n let changed = false;\n for (let index = normalized.length - 1; index >= 0 && difference !== 0; index -= 1) {\n if (difference < 0 && normalized[index] <= 1) continue;\n normalized[index] += difference > 0 ? 1 : -1;\n difference += difference > 0 ? -1 : 1;\n changed = true;\n }\n if (!changed) break;\n }\n\n return normalized;\n}\n\nexport function getLogicalTableColumnCount(table: ProseMirrorNode) {\n const firstRow = table.firstChild;\n if (!firstRow) return 0;\n\n let count = 0;\n firstRow.forEach((cell) => {\n count += Math.max(1, Number(cell.attrs.colspan) || 1);\n });\n return count;\n}\n\nexport function getLegacyTableColumnWeights(table: ProseMirrorNode, fallback = 100) {\n const weights: number[] = [];\n const firstRow = table.firstChild;\n if (!firstRow) return weights;\n\n firstRow.forEach((cell) => {\n const colspan = Math.max(1, Number(cell.attrs.colspan) || 1);\n const colwidth = Array.isArray(cell.attrs.colwidth) ? cell.attrs.colwidth : [];\n for (let index = 0; index < colspan; index += 1) {\n weights.push(positiveNumber(colwidth[index], fallback));\n }\n });\n\n return weights;\n}\n\nexport function getTableColumnRatios(table: ProseMirrorNode) {\n const columnCount = getLogicalTableColumnCount(table);\n const stored = parseColumnRatios(table.attrs.columnRatios);\n return normalizeColumnRatios(\n stored?.length === columnCount ? stored : getLegacyTableColumnWeights(table),\n columnCount,\n );\n}\n\nexport function getResponsiveTableWidthBp(table: ProseMirrorNode) {\n return clampResponsiveTableWidthBp(table.attrs.widthBp);\n}\n\nexport function getResponsiveTableOffsetBp(table: ProseMirrorNode) {\n const width = getResponsiveTableWidthBp(table);\n return resolveResponsiveTableOffsetBp(width, null, table.attrs.offsetBp);\n}\n\nexport function resolveResponsiveTableOffsetBp(\n widthBp: number,\n tableAlign: unknown,\n fallbackOffsetBp: unknown = 0,\n) {\n const availableGap = Math.max(\n 0,\n TABLE_WIDTH_BASIS_POINTS - clampResponsiveTableWidthBp(widthBp),\n );\n if (tableAlign === \"center\") return Math.round(availableGap / 2);\n if (tableAlign === \"right\") return availableGap;\n if (tableAlign === \"left\") return 0;\n return Math.min(availableGap, clampTableBasisPoints(fallbackOffsetBp, 0));\n}\n\nexport function insertResponsiveColumnRatio(ratios: readonly number[], insertIndex: number, sourceIndex: number) {\n if (ratios.length === 0) return [TABLE_WIDTH_BASIS_POINTS];\n const safeSourceIndex = Math.max(0, Math.min(sourceIndex, ratios.length - 1));\n const next = [...ratios];\n const sourceRatio = next[safeSourceIndex];\n next.splice(Math.max(0, Math.min(insertIndex, next.length)), 0, sourceRatio);\n return normalizeColumnRatios(next, next.length);\n}\n\nexport function deleteResponsiveColumnRatio(ratios: readonly number[], deleteIndex: number) {\n if (ratios.length <= 1) return [];\n const next = ratios.filter((_, index) => index !== deleteIndex);\n return normalizeColumnRatios(next, next.length);\n}\n\nexport function moveResponsiveColumnRatio(ratios: readonly number[], from: number, to: number) {\n if (from === to || from < 0 || from >= ratios.length || to < 0 || to >= ratios.length) return [...ratios];\n const next = [...ratios];\n const [moved] = next.splice(from, 1);\n next.splice(to, 0, moved);\n return normalizeColumnRatios(next, next.length);\n}\n\nexport type ResponsiveTableWidthLayout = {\n widthBp: number;\n columnRatios: number[];\n};\n\nexport function insertResponsiveColumnLayout(\n widthBp: number,\n ratios: readonly number[],\n insertIndex: number,\n sourceIndex: number,\n): ResponsiveTableWidthLayout {\n if (ratios.length === 0) {\n return {\n widthBp: clampResponsiveTableWidthBp(widthBp),\n columnRatios: [TABLE_WIDTH_BASIS_POINTS],\n };\n }\n\n const normalized = normalizeColumnRatios(ratios, ratios.length);\n const safeSourceIndex = Math.max(0, Math.min(sourceIndex, normalized.length - 1));\n const sourceRatio = normalized[safeSourceIndex];\n\n return {\n // Growing by the source column's share preserves every existing column's\n // rendered width instead of squeezing the whole table back into 100%.\n widthBp: clampResponsiveTableWidthBp(\n (clampResponsiveTableWidthBp(widthBp) * (TABLE_WIDTH_BASIS_POINTS + sourceRatio))\n / TABLE_WIDTH_BASIS_POINTS,\n ),\n columnRatios: insertResponsiveColumnRatio(normalized, insertIndex, safeSourceIndex),\n };\n}\n\nexport function deleteResponsiveColumnLayout(\n widthBp: number,\n ratios: readonly number[],\n deleteIndex: number,\n): ResponsiveTableWidthLayout {\n const normalized = normalizeColumnRatios(ratios, ratios.length);\n if (normalized.length <= 1 || deleteIndex < 0 || deleteIndex >= normalized.length) {\n return {\n widthBp: clampResponsiveTableWidthBp(widthBp),\n columnRatios: normalized.length <= 1 ? [] : normalized,\n };\n }\n\n const remainingRatio = TABLE_WIDTH_BASIS_POINTS - normalized[deleteIndex];\n const nextWidthBp = clampResponsiveTableWidthBp(\n (clampResponsiveTableWidthBp(widthBp) * remainingRatio) / TABLE_WIDTH_BASIS_POINTS,\n );\n return {\n // Deletion is the inverse operation: remaining columns keep their rendered\n // widths while the table gives the removed column's space back.\n widthBp: Math.abs(nextWidthBp - DEFAULT_RESPONSIVE_TABLE_WIDTH_BP) <= 1\n ? DEFAULT_RESPONSIVE_TABLE_WIDTH_BP\n : nextWidthBp,\n columnRatios: deleteResponsiveColumnRatio(normalized, deleteIndex),\n };\n}\n","import type { JSONContent } from \"@tiptap/core\";\nimport {\n clampResponsiveTableWidthBp,\n DEFAULT_RESPONSIVE_TABLE_WIDTH_BP,\n normalizeColumnRatios,\n parseColumnRatios,\n parsePercentageToBasisPoints,\n resolveResponsiveTableOffsetBp,\n} from \"./table-width-model.ts\";\n\ntype ClipboardDataLike = {\n getData: (type: string) => string;\n};\n\ntype ClipboardStyleDeclarations = Map<string, string>;\ntype ClipboardStyleMap = Map<string, ClipboardStyleDeclarations>;\n\ntype ClipboardTableCellAttrs = {\n backgroundColor?: string;\n borderColor?: string;\n borderStyle?: string;\n borderWidth?: string;\n cellId?: string;\n numberFormat?: string;\n formula?: string;\n computedValue?: string;\n colspan?: number;\n rowspan?: number;\n colwidth?: number[];\n};\n\ntype ClipboardTextSegment = {\n text: string;\n marks?: JSONContent[\"marks\"];\n};\n\ntype ClipboardTableCell = {\n text: string;\n isHeader: boolean;\n attrs?: ClipboardTableCellAttrs;\n segments?: ClipboardTextSegment[];\n textColor?: string;\n};\n\ntype ClipboardTableRow = {\n cells: ClipboardTableCell[];\n attrs?: {\n rowHeight?: number;\n };\n};\n\ntype ClipboardTableLayout = {\n widthBp?: number;\n offsetBp?: number;\n columnRatios?: number[] | null;\n};\n\nconst DEFAULT_HTML_TABLE_CELL_BACKGROUND_COLOR = \"#ffffff\";\nconst DEFAULT_HTML_TABLE_TEXT_COLOR = \"#000000\";\n\nfunction getClipboardData(dataTransfer: ClipboardDataLike, type: string) {\n try {\n return dataTransfer.getData(type) ?? \"\";\n } catch {\n return \"\";\n }\n}\n\nexport function hasClipboardHtmlTable(dataTransfer: ClipboardDataLike) {\n return /<table(?:\\s|>)/i.test(getClipboardData(dataTransfer, \"text/html\"));\n}\n\nfunction extractClipboardHtmlFragment(html: string) {\n const startMarker = \"<!--StartFragment-->\";\n const endMarker = \"<!--EndFragment-->\";\n const start = html.indexOf(startMarker);\n const end = html.indexOf(endMarker);\n\n if (start >= 0 && end > start) {\n return html.slice(start + startMarker.length, end);\n }\n\n return html;\n}\n\nfunction hasMeaningfulContentOutsideTable(container: HTMLElement) {\n const clone = container.cloneNode(true) as HTMLElement;\n clone.querySelectorAll(\"table, style, script, meta, link\").forEach((element) => element.remove());\n\n const remainingText = (clone.textContent ?? \"\")\n .replace(/\\u00a0/g, \" \")\n .replace(/\\u200b/g, \"\")\n .trim();\n if (remainingText) return true;\n\n return !!clone.querySelector(\"img, video, audio, iframe, object, embed, svg, canvas, hr, input, textarea, select, button\");\n}\n\nfunction normalizeClipboardCellText(value: string) {\n return value\n .replace(/\\r\\n/g, \"\\n\")\n .replace(/\\r/g, \"\\n\")\n .replace(/\\u00a0/g, \" \")\n .replace(/[ \\t]+\\n/g, \"\\n\")\n .replace(/\\n[ \\t]+/g, \"\\n\")\n .replace(/\\n+$/g, \"\")\n .replace(/^\\n+/g, \"\")\n .trim();\n}\n\nfunction parseStyleDeclarations(styleText: string | null | undefined): ClipboardStyleDeclarations {\n const declarations: ClipboardStyleDeclarations = new Map();\n if (!styleText) return declarations;\n\n for (const declaration of styleText.split(\";\")) {\n const separatorIndex = declaration.indexOf(\":\");\n if (separatorIndex <= 0) continue;\n\n const property = declaration.slice(0, separatorIndex).trim().toLowerCase();\n const value = cleanStyleValue(declaration.slice(separatorIndex + 1));\n if (!property || !value) continue;\n\n declarations.set(property, value);\n }\n\n return declarations;\n}\n\nfunction mergeStyleDeclarations(...sources: Array<ClipboardStyleDeclarations | null | undefined>) {\n const declarations: ClipboardStyleDeclarations = new Map();\n\n for (const source of sources) {\n if (!source) continue;\n for (const [property, value] of source.entries()) {\n declarations.set(property, value);\n }\n }\n\n return declarations;\n}\n\nfunction extractCssClassNames(selectorText: string) {\n const classNames = new Set<string>();\n const classNamePattern = /\\.([_a-zA-Z-][\\w-]*)/g;\n let match: RegExpExecArray | null;\n\n while ((match = classNamePattern.exec(selectorText)) !== null) {\n classNames.add(match[1]);\n }\n\n return classNames;\n}\n\nfunction parseClipboardCssClassStyles(doc: Document): ClipboardStyleMap {\n const styleMap: ClipboardStyleMap = new Map();\n\n for (const styleElement of Array.from(doc.querySelectorAll(\"style\"))) {\n const cssText = (styleElement.textContent ?? \"\")\n .replace(/<!--|-->/g, \"\")\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\");\n const rulePattern = /([^{}]+)\\{([^{}]*)\\}/g;\n let match: RegExpExecArray | null;\n\n while ((match = rulePattern.exec(cssText)) !== null) {\n const classNames = extractCssClassNames(match[1]);\n if (classNames.size === 0) continue;\n\n const declarations = parseStyleDeclarations(match[2]);\n if (declarations.size === 0) continue;\n\n for (const className of classNames) {\n styleMap.set(className, mergeStyleDeclarations(styleMap.get(className), declarations));\n }\n }\n }\n\n return styleMap;\n}\n\nfunction getElementStyleDeclarations(element: HTMLElement, styleMap: ClipboardStyleMap) {\n const classDeclarations = Array.from(element.classList).map((className) => styleMap.get(className));\n const inlineDeclarations = parseStyleDeclarations(element.getAttribute(\"style\"));\n return mergeStyleDeclarations(...classDeclarations, inlineDeclarations);\n}\n\nfunction cleanStyleValue(value: string | null | undefined) {\n const normalized = value?.trim();\n if (!normalized) return null;\n if (/[\\0<>;{}]/.test(normalized)) return null;\n if (/\\b(?:expression|url|(?:repeating-)?(?:linear|radial|conic)-gradient)\\s*\\(/i.test(normalized)) return null;\n return normalized;\n}\n\nfunction normalizeColorValue(value: string | null | undefined) {\n const normalized = cleanStyleValue(value);\n if (!normalized) return null;\n if (/^(?:auto|inherit|initial|none|transparent|unset)$/i.test(normalized)) return null;\n return normalized;\n}\n\nfunction normalizeTextColorValue(value: string | null | undefined) {\n const normalized = normalizeColorValue(value);\n if (!normalized) return null;\n if (/^(?:automatic|windowtext|black|#000|#000000|rgb\\(\\s*0\\s*,\\s*0\\s*,\\s*0\\s*\\))$/i.test(normalized)) {\n return DEFAULT_HTML_TABLE_TEXT_COLOR;\n }\n return normalized;\n}\n\nfunction isWhiteColor(value: string | null | undefined) {\n if (!value) return false;\n return /^(?:white|#fff|#ffffff|rgb\\(\\s*255\\s*,\\s*255\\s*,\\s*255\\s*\\))$/i.test(value.trim());\n}\n\nfunction parseCssColorRgb(value: string | null | undefined) {\n const normalized = normalizeColorValue(value);\n if (!normalized) return null;\n\n const lowerColor = normalized.toLowerCase();\n if (lowerColor === \"white\") return { r: 255, g: 255, b: 255 };\n if (lowerColor === \"black\") return { r: 0, g: 0, b: 0 };\n\n const hexMatch = lowerColor.match(/^#([\\da-f]{3}|[\\da-f]{6})$/i);\n if (hexMatch) {\n const hex = hexMatch[1];\n const fullHex = hex.length === 3 ? hex.split(\"\").map((part) => part + part).join(\"\") : hex;\n\n return {\n r: Number.parseInt(fullHex.slice(0, 2), 16),\n g: Number.parseInt(fullHex.slice(2, 4), 16),\n b: Number.parseInt(fullHex.slice(4, 6), 16),\n };\n }\n\n const rgbMatch = lowerColor.match(/^rgba?\\(\\s*(\\d+(?:\\.\\d+)?)\\s*,\\s*(\\d+(?:\\.\\d+)?)\\s*,\\s*(\\d+(?:\\.\\d+)?)/);\n if (rgbMatch) {\n return {\n r: Math.max(0, Math.min(255, Number.parseFloat(rgbMatch[1]))),\n g: Math.max(0, Math.min(255, Number.parseFloat(rgbMatch[2]))),\n b: Math.max(0, Math.min(255, Number.parseFloat(rgbMatch[3]))),\n };\n }\n\n return null;\n}\n\nfunction getRelativeLuminance(value: string | null | undefined) {\n const rgb = parseCssColorRgb(value);\n if (!rgb) return null;\n\n const toLinear = (channel: number) => {\n const normalized = channel / 255;\n return normalized <= 0.03928 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;\n };\n\n return 0.2126 * toLinear(rgb.r) + 0.7152 * toLinear(rgb.g) + 0.0722 * toLinear(rgb.b);\n}\n\nfunction isLightTextColor(value: string | null | undefined) {\n const luminance = getRelativeLuminance(value);\n return luminance !== null && luminance >= 0.72;\n}\n\nfunction isDarkReadableBackground(value: string | null | undefined) {\n const luminance = getRelativeLuminance(value);\n return luminance !== null && luminance <= 0.45;\n}\n\nfunction splitCssTokens(value: string) {\n const tokens: string[] = [];\n let current = \"\";\n let depth = 0;\n\n for (const char of value) {\n if (char === \"(\") depth += 1;\n if (char === \")\") depth = Math.max(0, depth - 1);\n\n if (/\\s/.test(char) && depth === 0) {\n if (current) {\n tokens.push(current);\n current = \"\";\n }\n continue;\n }\n\n current += char;\n }\n\n if (current) tokens.push(current);\n return tokens;\n}\n\nfunction extractColorFromShorthand(value: string | null | undefined) {\n const normalized = cleanStyleValue(value);\n if (!normalized) return null;\n\n const explicitColor = normalized.match(/#[\\da-f]{3,8}\\b|rgba?\\([^)]+\\)|hsla?\\([^)]+\\)/i);\n if (explicitColor) return explicitColor[0];\n\n const ignoredKeywords = new Set([\n \"border-box\",\n \"center\",\n \"contain\",\n \"content-box\",\n \"cover\",\n \"fixed\",\n \"inherit\",\n \"initial\",\n \"left\",\n \"local\",\n \"none\",\n \"no-repeat\",\n \"padding-box\",\n \"repeat\",\n \"repeat-x\",\n \"repeat-y\",\n \"right\",\n \"scroll\",\n \"top\",\n \"transparent\",\n \"unset\",\n ]);\n\n return splitCssTokens(normalized).find((token) => !ignoredKeywords.has(token.toLowerCase())) ?? null;\n}\n\nfunction getBackgroundColor(styles: ClipboardStyleDeclarations) {\n return (\n normalizeColorValue(styles.get(\"background-color\"))\n ?? normalizeColorValue(extractColorFromShorthand(styles.get(\"background\")))\n );\n}\n\nconst BORDER_STYLES = new Set([\n \"dashed\",\n \"dotted\",\n \"double\",\n \"groove\",\n \"hidden\",\n \"inset\",\n \"none\",\n \"outset\",\n \"ridge\",\n \"solid\",\n]);\n\nconst BORDER_WIDTH_KEYWORDS = new Set([\"medium\", \"thick\", \"thin\"]);\n\nfunction normalizeBorderStyle(value: string | null | undefined) {\n const normalized = cleanStyleValue(value);\n if (!normalized) return null;\n\n const styles = splitCssTokens(normalized).filter((token) => BORDER_STYLES.has(token.toLowerCase()));\n const usefulStyles = styles.filter((style) => !/^(?:hidden|none)$/i.test(style));\n return usefulStyles.length > 0 ? usefulStyles.join(\" \") : null;\n}\n\nfunction normalizeBorderWidth(value: string | null | undefined) {\n const normalized = cleanStyleValue(value);\n if (!normalized) return null;\n\n const widths = splitCssTokens(normalized).filter((token) => {\n const lowerToken = token.toLowerCase();\n return BORDER_WIDTH_KEYWORDS.has(lowerToken) || /^\\d*\\.?\\d+(?:px|pt|pc|in|cm|mm|em|rem)?$/i.test(token);\n });\n\n return widths.length > 0 ? widths.join(\" \") : null;\n}\n\nfunction parseBorderShorthand(value: string | null | undefined) {\n const normalized = cleanStyleValue(value);\n if (!normalized) return null;\n\n const tokens = splitCssTokens(normalized);\n let borderStyle: string | null = null;\n let borderWidth: string | null = null;\n const colorTokens: string[] = [];\n\n for (const token of tokens) {\n const lowerToken = token.toLowerCase();\n\n if (!borderStyle && BORDER_STYLES.has(lowerToken)) {\n borderStyle = lowerToken;\n continue;\n }\n\n if (\n !borderWidth\n && (BORDER_WIDTH_KEYWORDS.has(lowerToken) || /^\\d*\\.?\\d+(?:px|pt|pc|in|cm|mm|em|rem)?$/i.test(token))\n ) {\n borderWidth = token;\n continue;\n }\n\n colorTokens.push(token);\n }\n\n if (borderStyle && /^(?:hidden|none)$/i.test(borderStyle)) return null;\n\n return {\n borderColor: normalizeColorValue(colorTokens.join(\" \")),\n borderStyle,\n borderWidth,\n };\n}\n\nfunction getFirstParsedBorder(styles: ClipboardStyleDeclarations) {\n for (const property of [\"border\", \"border-top\", \"border-right\", \"border-bottom\", \"border-left\"]) {\n const border = parseBorderShorthand(styles.get(property));\n if (border) return border;\n }\n\n return null;\n}\n\nfunction getBorderAttrs(styles: ClipboardStyleDeclarations) {\n const parsedBorder = getFirstParsedBorder(styles);\n\n return {\n borderColor: normalizeColorValue(styles.get(\"border-color\")) ?? parsedBorder?.borderColor ?? undefined,\n borderStyle: normalizeBorderStyle(styles.get(\"border-style\")) ?? parsedBorder?.borderStyle ?? undefined,\n borderWidth: normalizeBorderWidth(styles.get(\"border-width\")) ?? parsedBorder?.borderWidth ?? undefined,\n };\n}\n\nfunction parsePositiveInteger(value: string | null | undefined, max = 100) {\n if (!value) return null;\n\n const parsed = Number.parseInt(value, 10);\n if (!Number.isFinite(parsed) || parsed < 1) return null;\n\n return Math.min(parsed, max);\n}\n\nfunction parseCssSize(value: string | null | undefined) {\n const normalized = cleanStyleValue(value);\n if (!normalized) return null;\n\n const match = normalized.match(/^(\\d+(?:\\.\\d+)?)(px|pt)?$/i);\n if (!match) return null;\n\n const amount = Number.parseFloat(match[1]);\n if (!Number.isFinite(amount) || amount <= 0) return null;\n\n return Math.round(match[2]?.toLowerCase() === \"pt\" ? amount * (4 / 3) : amount);\n}\n\nfunction getCellWidth(cell: HTMLTableCellElement, styles: ClipboardStyleDeclarations, colspan: number) {\n if (colspan !== 1) return null;\n\n const width = parseCssSize(cell.getAttribute(\"data-colwidth\") ?? cell.getAttribute(\"width\") ?? styles.get(\"width\"));\n return width ? [width] : null;\n}\n\nfunction getTableRowAttrs(row: HTMLTableRowElement, styles: ClipboardStyleDeclarations): ClipboardTableRow[\"attrs\"] {\n const rowHeight = parseCssSize(\n row.getAttribute(\"data-row-height\") ?? row.getAttribute(\"height\") ?? styles.get(\"height\"),\n );\n return rowHeight ? { rowHeight } : undefined;\n}\n\nfunction getTableCellAttrs(\n cell: HTMLTableCellElement,\n styles: ClipboardStyleDeclarations,\n defaultBackgroundColor?: string,\n): ClipboardTableCellAttrs | undefined {\n const colspan = parsePositiveInteger(cell.getAttribute(\"colspan\")) ?? 1;\n const rowspan = parsePositiveInteger(cell.getAttribute(\"rowspan\")) ?? 1;\n const backgroundColor =\n getBackgroundColor(styles)\n ?? normalizeColorValue(cell.getAttribute(\"data-background-color\"))\n ?? normalizeColorValue(cell.getAttribute(\"bgcolor\"))\n ?? defaultBackgroundColor;\n const borderAttrs = getBorderAttrs(styles);\n const colwidth = getCellWidth(cell, styles, colspan);\n\n const attrs: ClipboardTableCellAttrs = {};\n\n if (backgroundColor) attrs.backgroundColor = backgroundColor;\n if (borderAttrs.borderColor) attrs.borderColor = borderAttrs.borderColor;\n if (borderAttrs.borderStyle) attrs.borderStyle = borderAttrs.borderStyle;\n if (borderAttrs.borderWidth) attrs.borderWidth = borderAttrs.borderWidth;\n if (cell.getAttribute(\"data-cell-id\")) attrs.cellId = cell.getAttribute(\"data-cell-id\") ?? undefined;\n if (cell.getAttribute(\"data-number-format\")) attrs.numberFormat = cell.getAttribute(\"data-number-format\") ?? undefined;\n if (cell.getAttribute(\"data-formula\")) attrs.formula = cell.getAttribute(\"data-formula\") ?? undefined;\n if (cell.getAttribute(\"data-computed-value\")) attrs.computedValue = cell.getAttribute(\"data-computed-value\") ?? undefined;\n if (colspan > 1) attrs.colspan = colspan;\n if (rowspan > 1) attrs.rowspan = rowspan;\n if (colwidth) attrs.colwidth = colwidth;\n\n return Object.keys(attrs).length > 0 ? attrs : undefined;\n}\n\nfunction marksEqual(left: JSONContent[\"marks\"], right: JSONContent[\"marks\"]) {\n return JSON.stringify(left ?? []) === JSON.stringify(right ?? []);\n}\n\nfunction mergeMarks(base: JSONContent[\"marks\"] | undefined, additions: JSONContent[\"marks\"] | undefined) {\n const next = [...(base ?? [])];\n\n for (const addition of additions ?? []) {\n const existingIndex = next.findIndex((mark) => mark.type === addition.type);\n if (existingIndex >= 0) {\n const existingMark = next[existingIndex];\n next[existingIndex] = {\n ...existingMark,\n attrs: {\n ...(existingMark.attrs ?? {}),\n ...(addition.attrs ?? {}),\n },\n };\n continue;\n }\n\n next.push(addition);\n }\n\n return next.length > 0 ? next : undefined;\n}\n\nfunction getMarkColor(marks: JSONContent[\"marks\"] | undefined, markType: string) {\n const mark = marks?.find((candidate) => candidate.type === markType);\n const color = mark?.attrs?.color;\n return typeof color === \"string\" ? color : null;\n}\n\nfunction replaceTextStyleColor(marks: JSONContent[\"marks\"] | undefined, color: string) {\n let replaced = false;\n const next = (marks ?? []).map((mark) => {\n if (mark.type !== \"textStyle\") return mark;\n\n replaced = true;\n return {\n ...mark,\n attrs: {\n ...(mark.attrs ?? {}),\n color,\n },\n };\n });\n\n if (!replaced) {\n next.unshift({ type: \"textStyle\", attrs: { color } });\n }\n\n return next;\n}\n\nfunction ensureReadableSpreadsheetSegments(\n segments: ClipboardTextSegment[],\n cellBackgroundColor: string | null | undefined,\n) {\n return segments.map((segment) => {\n const textColor = getMarkColor(segment.marks, \"textStyle\");\n if (!isLightTextColor(textColor)) return segment;\n\n const inlineBackgroundColor = getMarkColor(segment.marks, \"highlight\");\n if (isDarkReadableBackground(inlineBackgroundColor) || isDarkReadableBackground(cellBackgroundColor)) {\n return segment;\n }\n\n return {\n ...segment,\n marks: replaceTextStyleColor(segment.marks, DEFAULT_HTML_TABLE_TEXT_COLOR),\n };\n });\n}\n\nfunction getElementInlineMarks(element: HTMLElement, styles: ClipboardStyleDeclarations): JSONContent[\"marks\"] | undefined {\n const marks: JSONContent[\"marks\"] = [];\n const tagName = element.tagName;\n const color = normalizeTextColorValue(styles.get(\"color\") ?? element.getAttribute(\"color\"));\n const backgroundColor = getBackgroundColor(styles);\n const fontWeight = styles.get(\"font-weight\")?.toLowerCase();\n const fontStyle = styles.get(\"font-style\")?.toLowerCase();\n const textDecoration = styles.get(\"text-decoration\")?.toLowerCase();\n\n if (color) {\n marks.push({ type: \"textStyle\", attrs: { color } });\n }\n\n if (backgroundColor && !isWhiteColor(backgroundColor)) {\n marks.push({ type: \"highlight\", attrs: { color: backgroundColor } });\n }\n\n if (\n tagName === \"B\"\n || tagName === \"STRONG\"\n || fontWeight === \"bold\"\n || (/^\\d+$/.test(fontWeight ?? \"\") && Number(fontWeight) >= 600)\n ) {\n marks.push({ type: \"bold\" });\n }\n\n if (tagName === \"I\" || tagName === \"EM\" || fontStyle === \"italic\") {\n marks.push({ type: \"italic\" });\n }\n\n if (tagName === \"U\" || textDecoration?.includes(\"underline\")) {\n marks.push({ type: \"underline\" });\n }\n\n return marks.length > 0 ? marks : undefined;\n}\n\nfunction appendTextSegment(segments: ClipboardTextSegment[], segment: ClipboardTextSegment) {\n if (!segment.text) return;\n\n const lastSegment = segments[segments.length - 1];\n if (lastSegment && marksEqual(lastSegment.marks, segment.marks)) {\n lastSegment.text += segment.text;\n return;\n }\n\n segments.push(segment);\n}\n\nfunction segmentsEndWithNewline(segments: ClipboardTextSegment[]) {\n return segments.length > 0 && segments[segments.length - 1].text.endsWith(\"\\n\");\n}\n\nfunction normalizeClipboardTextSegments(segments: ClipboardTextSegment[]) {\n const normalizedSegments: ClipboardTextSegment[] = [];\n\n for (const segment of segments) {\n appendTextSegment(normalizedSegments, {\n text: segment.text.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\").replace(/\\u00a0/g, \" \"),\n marks: segment.marks,\n });\n }\n\n while (normalizedSegments.length > 0) {\n const firstSegment = normalizedSegments[0];\n firstSegment.text = firstSegment.text.replace(/^\\s+/, \"\");\n if (firstSegment.text) break;\n normalizedSegments.shift();\n }\n\n while (normalizedSegments.length > 0) {\n const lastSegment = normalizedSegments[normalizedSegments.length - 1];\n lastSegment.text = lastSegment.text.replace(/\\s+$/, \"\");\n if (lastSegment.text) break;\n normalizedSegments.pop();\n }\n\n return normalizedSegments;\n}\n\nfunction getClipboardCellText(node: Node): string {\n if (node.nodeType === Node.TEXT_NODE) {\n return node.textContent ?? \"\";\n }\n\n if (!(node instanceof HTMLElement)) {\n return \"\";\n }\n\n if (node.tagName === \"BR\") {\n return \"\\n\";\n }\n\n const childText = Array.from(node.childNodes).map(getClipboardCellText).join(\"\");\n\n if ((node.tagName === \"P\" || node.tagName === \"DIV\" || node.tagName === \"LI\") && childText && !childText.endsWith(\"\\n\")) {\n return `${childText}\\n`;\n }\n\n return childText;\n}\n\nfunction getClipboardCellSegments(\n node: Node,\n styleMap: ClipboardStyleMap,\n inheritedMarks?: JSONContent[\"marks\"],\n): ClipboardTextSegment[] {\n if (node.nodeType === Node.TEXT_NODE) {\n return [{ text: node.textContent ?? \"\", marks: inheritedMarks }];\n }\n\n if (!(node instanceof HTMLElement)) {\n return [];\n }\n\n if (node.tagName === \"BR\") {\n return [{ text: \"\\n\", marks: inheritedMarks }];\n }\n\n const styles = getElementStyleDeclarations(node, styleMap);\n const marks = mergeMarks(inheritedMarks, getElementInlineMarks(node, styles));\n const segments: ClipboardTextSegment[] = [];\n\n for (const childNode of Array.from(node.childNodes)) {\n for (const segment of getClipboardCellSegments(childNode, styleMap, marks)) {\n appendTextSegment(segments, segment);\n }\n }\n\n if ((node.tagName === \"P\" || node.tagName === \"DIV\" || node.tagName === \"LI\") && segments.length > 0 && !segmentsEndWithNewline(segments)) {\n appendTextSegment(segments, { text: \"\\n\" });\n }\n\n return segments;\n}\n\nfunction getClipboardCellChildSegments(\n cell: HTMLTableCellElement,\n styleMap: ClipboardStyleMap,\n inheritedMarks?: JSONContent[\"marks\"],\n) {\n const segments: ClipboardTextSegment[] = [];\n\n for (const childNode of Array.from(cell.childNodes)) {\n for (const segment of getClipboardCellSegments(childNode, styleMap, inheritedMarks)) {\n appendTextSegment(segments, segment);\n }\n }\n\n return normalizeClipboardTextSegments(segments);\n}\n\nfunction getHtmlTableRows(table: HTMLTableElement, styleMap: ClipboardStyleMap): ClipboardTableRow[] {\n const rows = Array.from(table.querySelectorAll(\"tr\")).map((row) =>\n ({\n attrs: getTableRowAttrs(row, getElementStyleDeclarations(row, styleMap)),\n cells: Array.from(row.children)\n .filter((cell): cell is HTMLTableCellElement => cell instanceof HTMLTableCellElement)\n .map((cell) => {\n const styles = getElementStyleDeclarations(cell, styleMap);\n const textColor = normalizeTextColorValue(styles.get(\"color\")) ?? DEFAULT_HTML_TABLE_TEXT_COLOR;\n const inheritedMarks = [{ type: \"textStyle\", attrs: { color: textColor } }];\n const attrs = getTableCellAttrs(cell, styles, DEFAULT_HTML_TABLE_CELL_BACKGROUND_COLOR);\n const segments = ensureReadableSpreadsheetSegments(\n getClipboardCellChildSegments(cell, styleMap, inheritedMarks),\n attrs?.backgroundColor,\n );\n\n return {\n text: normalizeClipboardCellText(getClipboardCellText(cell)),\n isHeader: cell.tagName === \"TH\",\n attrs,\n segments: segments.length > 0 ? segments : undefined,\n textColor,\n };\n }),\n }),\n );\n\n return rows.filter((row) => row.cells.length > 0);\n}\n\nfunction createTextMarks(cell: ClipboardTableCell) {\n return cell.textColor ? [{ type: \"textStyle\", attrs: { color: cell.textColor } }] : undefined;\n}\n\nfunction createParagraphContent(text: string, marks?: JSONContent[\"marks\"]): JSONContent {\n return text\n ? {\n type: \"paragraph\",\n content: [{ type: \"text\", text, ...(marks ? { marks } : {}) }],\n }\n : { type: \"paragraph\" };\n}\n\nfunction createParagraphContentFromSegments(segments: ClipboardTextSegment[]): JSONContent[] {\n const paragraphs: ClipboardTextSegment[][] = [[]];\n\n for (const segment of segments) {\n const parts = segment.text.split(\"\\n\");\n\n parts.forEach((part, index) => {\n if (part) {\n paragraphs[paragraphs.length - 1].push({ text: part, marks: segment.marks });\n }\n\n if (index < parts.length - 1) {\n paragraphs.push([]);\n }\n });\n }\n\n return paragraphs.map((paragraphSegments) => {\n const content = paragraphSegments.map((segment) => ({\n type: \"text\",\n text: segment.text,\n ...(segment.marks ? { marks: segment.marks } : {}),\n }));\n\n return content.length > 0 ? { type: \"paragraph\", content } : { type: \"paragraph\" };\n });\n}\n\nfunction createTableCellContent(cell: ClipboardTableCell): JSONContent {\n const lines = cell.text.split(\"\\n\");\n const marks = createTextMarks(cell);\n const paragraphs =\n cell.segments && cell.segments.length > 0\n ? createParagraphContentFromSegments(cell.segments)\n : (lines.length > 0 ? lines : [\"\"]).map((line) => createParagraphContent(line, marks));\n\n return {\n type: cell.isHeader ? \"tableHeader\" : \"tableCell\",\n ...(cell.attrs ? { attrs: cell.attrs } : {}),\n content: paragraphs.length > 0 ? paragraphs : [{ type: \"paragraph\" }],\n };\n}\n\ntype PositionedTableCell = {\n startColumn: number;\n colspan: number;\n cell: ClipboardTableCell;\n};\n\ntype PositionedTableRow = {\n cells: PositionedTableCell[];\n coveredColumns: boolean[];\n attrs?: ClipboardTableRow[\"attrs\"];\n};\n\nfunction getRowspanLimitedCell(cell: ClipboardTableCell, remainingRowCount: number): ClipboardTableCell {\n const attrs = cell.attrs;\n if (!attrs?.rowspan || attrs.rowspan <= remainingRowCount) return cell;\n\n if (remainingRowCount <= 1) {\n const { rowspan: _rowspan, ...nextAttrs } = attrs;\n\n return {\n ...cell,\n attrs: Object.keys(nextAttrs).length > 0 ? nextAttrs : undefined,\n };\n }\n\n return {\n ...cell,\n attrs: {\n ...attrs,\n rowspan: remainingRowCount,\n },\n };\n}\n\nfunction normalizeTableRows(rows: ClipboardTableRow[]) {\n const positionedRows: PositionedTableRow[] = [];\n let rowspans: number[] = [];\n let columnCount = 0;\n\n rows.forEach((row, rowIndex) => {\n const coveredColumns = rowspans.map((span) => span > 0);\n const nextRowspans = rowspans.map((span) => Math.max(0, span - 1));\n const positionedCells: PositionedTableCell[] = [];\n let columnIndex = 0;\n\n for (const rawCell of row.cells) {\n while (coveredColumns[columnIndex]) columnIndex += 1;\n\n const remainingRowCount = rows.length - rowIndex;\n const cell = getRowspanLimitedCell(rawCell, remainingRowCount);\n const colspan = Math.max(1, cell.attrs?.colspan ?? 1);\n const rowspan = Math.max(1, cell.attrs?.rowspan ?? 1);\n\n positionedCells.push({ startColumn: columnIndex, colspan, cell });\n\n if (rowspan > 1) {\n for (let offset = 0; offset < colspan; offset += 1) {\n const spannedColumn = columnIndex + offset;\n nextRowspans[spannedColumn] = Math.max(nextRowspans[spannedColumn] ?? 0, rowspan - 1);\n }\n }\n\n columnIndex += colspan;\n }\n\n const lastCoveredColumn = coveredColumns.reduce((lastIndex, covered, index) => (covered ? index : lastIndex), -1);\n const lastFutureRowspanColumn = nextRowspans.reduce((lastIndex, span, index) => (span > 0 ? index : lastIndex), -1);\n columnCount = Math.max(columnCount, columnIndex, lastCoveredColumn + 1, lastFutureRowspanColumn + 1);\n\n positionedRows.push({\n attrs: row.attrs,\n cells: positionedCells,\n coveredColumns,\n });\n rowspans = nextRowspans;\n });\n\n return { positionedRows, columnCount };\n}\n\nfunction createNormalizedRowContent(\n row: PositionedTableRow,\n columnCount: number,\n fillerCellAttrs?: ClipboardTableCellAttrs,\n) {\n const content: JSONContent[] = [];\n const cellByStartColumn = new Map(row.cells.map((cell) => [cell.startColumn, cell]));\n let columnIndex = 0;\n\n while (columnIndex < columnCount) {\n if (row.coveredColumns[columnIndex]) {\n columnIndex += 1;\n continue;\n }\n\n const positionedCell = cellByStartColumn.get(columnIndex);\n if (positionedCell) {\n content.push(createTableCellContent(positionedCell.cell));\n columnIndex += positionedCell.colspan;\n continue;\n }\n\n content.push(createTableCellContent({ text: \"\", isHeader: false, attrs: fillerCellAttrs }));\n columnIndex += 1;\n }\n\n return content;\n}\n\nfunction createTableContent(\n rows: ClipboardTableRow[],\n minColumnCount = 1,\n fillerCellAttrs?: ClipboardTableCellAttrs,\n layout?: ClipboardTableLayout,\n): JSONContent | null {\n const tableRows = rows.filter((row) => row.cells.length > 0);\n if (tableRows.length === 0) return null;\n\n const { positionedRows, columnCount } = normalizeTableRows(tableRows);\n if (columnCount < minColumnCount) return null;\n const inferredColumnWeights = Array.from({ length: columnCount }, () => 100);\n positionedRows.forEach((row) => {\n row.cells.forEach(({ cell, colspan, startColumn }) => {\n const width = colspan === 1 ? cell.attrs?.colwidth?.[0] : null;\n if (typeof width === \"number\" && Number.isFinite(width) && width > 0) {\n inferredColumnWeights[startColumn] = width;\n }\n });\n });\n const columnRatios = normalizeColumnRatios(\n layout?.columnRatios?.length === columnCount ? layout.columnRatios : inferredColumnWeights,\n columnCount,\n );\n const widthBp = clampResponsiveTableWidthBp(layout?.widthBp, DEFAULT_RESPONSIVE_TABLE_WIDTH_BP);\n const offsetBp = resolveResponsiveTableOffsetBp(widthBp, null, layout?.offsetBp);\n\n return {\n type: \"table\",\n attrs: {\n widthMode: \"responsive\",\n widthBp,\n offsetBp,\n columnRatios,\n },\n content: positionedRows.map((row) => ({\n type: \"tableRow\",\n ...(row.attrs ? { attrs: row.attrs } : {}),\n content: createNormalizedRowContent(row, columnCount, fillerCellAttrs),\n })),\n };\n}\n\nexport function getClipboardTableContent(dataTransfer: ClipboardDataLike) {\n const html = getClipboardData(dataTransfer, \"text/html\");\n if (!/<table(?:\\s|>)/i.test(html)) return null;\n if (typeof DOMParser === \"undefined\") return null;\n\n const doc = new DOMParser().parseFromString(html, \"text/html\");\n const fragment = extractClipboardHtmlFragment(html);\n const fragmentDoc = new DOMParser().parseFromString(fragment, \"text/html\");\n const styleMap = parseClipboardCssClassStyles(doc);\n const sourceBody = fragmentDoc.querySelector(\"table\") ? fragmentDoc.body : doc.body;\n const tables = sourceBody.querySelectorAll(\"table\");\n if (tables.length !== 1 || hasMeaningfulContentOutsideTable(sourceBody)) return null;\n\n const table = tables[0];\n if (!(table instanceof HTMLTableElement)) return null;\n const storedWidthValue = table.getAttribute(\"data-table-width-bp\");\n const storedOffsetValue = table.getAttribute(\"data-table-offset-bp\");\n const storedWidthBp = Number(storedWidthValue);\n const storedOffsetBp = Number(storedOffsetValue);\n const widthBp = storedWidthValue !== null && Number.isFinite(storedWidthBp) && storedWidthBp > 0\n ? storedWidthBp\n : parsePercentageToBasisPoints(table.getAttribute(\"data-table-width\") ?? table.style.width)\n ?? DEFAULT_RESPONSIVE_TABLE_WIDTH_BP;\n const offsetBp = storedOffsetValue !== null && Number.isFinite(storedOffsetBp) && storedOffsetBp >= 0\n ? storedOffsetBp\n : parsePercentageToBasisPoints(table.getAttribute(\"data-table-offset\") ?? table.style.marginLeft)\n ?? 0;\n\n return createTableContent(\n getHtmlTableRows(table, styleMap),\n 1,\n { backgroundColor: DEFAULT_HTML_TABLE_CELL_BACKGROUND_COLOR },\n {\n widthBp,\n offsetBp,\n columnRatios: parseColumnRatios(table.getAttribute(\"data-table-column-ratios\")),\n },\n );\n}\n\nfunction parseClipboardTsvRows(text: string) {\n const rows: string[][] = [];\n let row: string[] = [];\n let field = \"\";\n let inQuotes = false;\n\n const pushField = () => {\n row.push(field);\n field = \"\";\n };\n\n const pushRow = () => {\n pushField();\n rows.push(row);\n row = [];\n };\n\n for (let index = 0; index < text.length; index += 1) {\n const char = text[index];\n const nextChar = text[index + 1];\n\n if (inQuotes) {\n if (char === \"\\\"\" && nextChar === \"\\\"\") {\n field += \"\\\"\";\n index += 1;\n continue;\n }\n\n if (char === \"\\\"\") {\n inQuotes = false;\n continue;\n }\n\n field += char;\n continue;\n }\n\n if (char === \"\\\"\" && field.length === 0) {\n inQuotes = true;\n continue;\n }\n\n if (char === \"\\t\") {\n pushField();\n continue;\n }\n\n if (char === \"\\n\") {\n pushRow();\n continue;\n }\n\n field += char;\n }\n\n pushRow();\n\n while (rows.length > 0 && rows[rows.length - 1].every((cell) => cell === \"\")) {\n rows.pop();\n }\n\n return rows;\n}\n\nexport function getClipboardTsvTableContent(dataTransfer: ClipboardDataLike) {\n const text = getClipboardData(dataTransfer, \"text/plain\")\n .replace(/\\r\\n/g, \"\\n\")\n .replace(/\\r/g, \"\\n\");\n\n if (!text.includes(\"\\t\")) return null;\n\n const rows = parseClipboardTsvRows(text);\n return createTableContent(\n rows.map((row) => ({\n cells: row.map((cell) => ({ text: normalizeClipboardCellText(cell), isHeader: false })),\n })),\n 2,\n );\n}\n","import type { ChainedCommands, Editor } from \"@tiptap/core\";\nimport type { Node as ProseMirrorNode } from \"@tiptap/pm/model\";\nimport { TextSelection } from \"@tiptap/pm/state\";\nimport { selectedRect, TableMap } from \"@tiptap/pm/tables\";\nimport { MIN_TABLE_ROW_HEIGHT, UEDITOR_TABLE_LAYOUT_CHANGE_EVENT, isCrossRealmHTMLElement, isCrossRealmTable } from \"./table-dom-utils\";\nimport { MIN_RESIZED_TABLE_COLUMN_WIDTH } from \"./table-column-resize\";\nimport { createTableSizeSnapshot, normalizeWeightsToTotal } from \"./table-size-utils\";\nimport {\n getResponsiveTableWidthBp,\n getTableColumnRatios,\n insertResponsiveColumnLayout,\n normalizeColumnRatios,\n normalizeTableWidthMode,\n resolveResponsiveTableOffsetBp,\n} from \"./table-width-model\";\nimport {\n rewriteTableNodeFormulaReferencesForInsertion,\n shiftCopiedTableNodeFormulaReferences,\n} from \"./table-formula-references\";\n\ntype TableRectInfo = ReturnType<typeof selectedRect>;\n\nfunction getCellSelectionPositions(selection: unknown): { anchor: number; head: number } | null {\n const value = selection as {\n $anchorCell?: { pos?: unknown };\n $headCell?: { pos?: unknown };\n };\n const anchor = value.$anchorCell?.pos;\n const head = value.$headCell?.pos;\n return typeof anchor === \"number\" && typeof head === \"number\" ? { anchor, head } : null;\n}\n\nfunction getSelectedTableAnchorCellPos(editor: Editor): number | null {\n const selection = editor.state.selection;\n const cellSelection = getCellSelectionPositions(selection);\n if (cellSelection) {\n return cellSelection.anchor;\n }\n const { from } = selection;\n const $pos = editor.state.doc.resolve(from);\n for (let depth = $pos.depth; depth > 0; depth -= 1) {\n const node = $pos.node(depth);\n if (node.type.name === \"tableCell\" || node.type.name === \"tableHeader\") {\n return $pos.before(depth);\n }\n }\n return null;\n}\n\nfunction findTableInfoFromCellPos(editor: Editor, cellPos: number) {\n const $pos = editor.state.doc.resolve(cellPos);\n\n for (let depth = $pos.depth; depth > 0; depth -= 1) {\n const node = $pos.node(depth);\n if (node.type.name === \"table\") {\n return {\n table: node,\n tablePos: $pos.before(depth),\n tableStart: $pos.start(depth),\n };\n }\n }\n\n return null;\n}\n\nfunction getFocusableCellPos(editor: Editor, cellPos: number) {\n const cellNode = editor.state.doc.nodeAt(cellPos);\n if (!cellNode) return cellPos + 1;\n\n let offset = cellPos + 1;\n let node = cellNode.firstChild ?? null;\n\n while (node && !node.isTextblock) {\n offset += 1;\n node = node.firstChild ?? null;\n }\n\n return node?.isTextblock ? offset + 1 : cellPos + 1;\n}\n\nfunction focusCell(editor: Editor, cellPos: number) {\n const selection = TextSelection.near(editor.state.doc.resolve(getFocusableCellPos(editor, cellPos)));\n editor.view.dispatch(editor.state.tr.setSelection(selection));\n editor.view.focus();\n}\n\nfunction collectChildren(node: ProseMirrorNode) {\n const children: ProseMirrorNode[] = [];\n node.forEach((child) => children.push(child));\n return children;\n}\n\nfunction createEmptyCellNode(cellNode: ProseMirrorNode) {\n return cellNode.type.createAndFill({\n ...cellNode.attrs,\n formula: null,\n computedValue: null,\n }) ?? cellNode;\n}\n\nfunction createCellCopyForColumnDuplicate(cellNode: ProseMirrorNode) {\n return cellNode.type.create(cellNode.attrs, cellNode.content);\n}\n\nfunction createCellWithDuplicatedLogicalColumn(cellNode: ProseMirrorNode, widthIndex: number) {\n const colspan = Math.max(1, Number(cellNode.attrs.colspan) || 1);\n let nextColwidth: number[] | null = null;\n\n if (Array.isArray(cellNode.attrs.colwidth)) {\n nextColwidth = [...cellNode.attrs.colwidth];\n const duplicateWidth = nextColwidth[widthIndex];\n nextColwidth.splice(widthIndex + 1, 0, typeof duplicateWidth === \"number\" ? duplicateWidth : 0);\n }\n\n return cellNode.type.create({\n ...cellNode.attrs,\n colspan: colspan + 1,\n ...(nextColwidth ? { colwidth: nextColwidth } : null),\n }, cellNode.content);\n}\n\nfunction getTableRows(tableNode: ProseMirrorNode) {\n const rows: Array<{\n node: ProseMirrorNode;\n cells: Array<{ index: number; node: ProseMirrorNode; relativePos: number }>;\n }> = [];\n\n tableNode.forEach((rowNode, rowOffset) => {\n const cells: Array<{ index: number; node: ProseMirrorNode; relativePos: number }> = [];\n\n rowNode.forEach((cellNode, cellOffset, index) => {\n cells.push({\n index,\n node: cellNode,\n relativePos: rowOffset + 1 + cellOffset,\n });\n });\n\n rows.push({\n node: rowNode,\n cells,\n });\n });\n\n return rows;\n}\n\nfunction safeFindCell(map: TableMap, relativePos: number) {\n try {\n return map.findCell(relativePos);\n } catch {\n return null;\n }\n}\n\nfunction getSelectedTableRect(editor: Editor): TableRectInfo {\n const cellSelection = getCellSelectionPositions(editor.state.selection);\n if (cellSelection) {\n const tableInfo = findTableInfoFromCellPos(editor, cellSelection.anchor);\n if (tableInfo) {\n const map = TableMap.get(tableInfo.table);\n const rect = map.rectBetween(\n cellSelection.anchor - tableInfo.tableStart,\n cellSelection.head - tableInfo.tableStart,\n );\n\n return {\n ...rect,\n map,\n table: tableInfo.table,\n tableStart: tableInfo.tableStart,\n };\n }\n }\n\n return selectedRect(editor.state);\n}\n\nfunction parsePixelWidth(value: string | null | undefined) {\n if (!value) return null;\n const parsed = Number.parseFloat(value);\n return Number.isFinite(parsed) && parsed > 0 ? Math.round(parsed) : null;\n}\n\nfunction getDomColumnWidths(editor: Editor, rect: TableRectInfo) {\n const tableDom = editor.view.nodeDOM(rect.tableStart - 1);\n if (!(tableDom instanceof HTMLTableElement)) return null;\n\n const cols = Array.from(tableDom.querySelectorAll<HTMLTableColElement>(\"colgroup > col\"));\n if (cols.length === 0) return null;\n\n const widths: number[] = [];\n for (let col = rect.left; col < rect.right; col += 1) {\n const colElement = cols[col];\n if (!colElement) return null;\n\n const width = parsePixelWidth(colElement.style.width)\n ?? parsePixelWidth(colElement.getAttribute(\"width\"))\n ?? Math.round(colElement.getBoundingClientRect().width);\n\n if (!Number.isFinite(width) || width <= 0) return null;\n widths.push(width);\n }\n\n return widths.length > 0 ? widths : null;\n}\n\nfunction getNodeColumnWidths(rect: TableRectInfo) {\n const widths: number[] = [];\n\n for (let col = rect.left; col < rect.right; col += 1) {\n let width: number | null = null;\n const seen = new Set<number>();\n\n for (let row = 0; row < rect.map.height && width == null; row += 1) {\n const cellPos = rect.map.map[row * rect.map.width + col];\n if (seen.has(cellPos)) continue;\n seen.add(cellPos);\n\n const cell = rect.table.nodeAt(cellPos);\n const colwidth = cell?.attrs.colwidth;\n if (!Array.isArray(colwidth)) continue;\n\n const cellLeft = rect.map.colCount(cellPos);\n const widthIndex = col - cellLeft;\n const candidate = colwidth[widthIndex];\n if (typeof candidate === \"number\" && candidate > 0) {\n width = candidate;\n }\n }\n\n if (width == null) return null;\n widths.push(width);\n }\n\n return widths.length > 0 ? widths : null;\n}\n\nfunction getSelectedColumnWidths(editor: Editor, rect: TableRectInfo) {\n return getDomColumnWidths(editor, rect) ?? getNodeColumnWidths(rect);\n}\n\nexport function dispatchTableLayoutChange(editor: Editor) {\n editor.view.dom.dispatchEvent(new CustomEvent(UEDITOR_TABLE_LAYOUT_CHANGE_EVENT, { bubbles: true }));\n}\n\nexport function mergeTableCellsPreservingColumnWidths(editor: Editor) {\n const rect = getSelectedTableRect(editor);\n const widths = getSelectedColumnWidths(editor, rect);\n const merged = editor.chain().focus().mergeCells().run();\n\n if (!merged) return merged;\n if (!widths) {\n dispatchTableLayoutChange(editor);\n return merged;\n }\n\n const nextRect = getSelectedTableRect(editor);\n const cellPos = nextRect.map.map[nextRect.top * nextRect.map.width + nextRect.left];\n const absolutePos = nextRect.tableStart + cellPos;\n const node = editor.state.doc.nodeAt(absolutePos);\n if (!node) return merged;\n\n editor.view.dispatch(\n editor.state.tr.setNodeMarkup(absolutePos, node.type, {\n ...node.attrs,\n colwidth: widths,\n }),\n );\n dispatchTableLayoutChange(editor);\n\n return true;\n}\n\nexport function runTableCommandAtCellPos(\n editor: Editor,\n cellPos: number | null,\n command: (chain: ChainedCommands) => ChainedCommands,\n) {\n if (cellPos == null) return false;\n focusCell(editor, cellPos);\n return command(editor.chain().focus(null, { scrollIntoView: false })).run();\n}\n\nexport function getTableCornerCellPos(editor: Editor, activePos: number) {\n const tableInfo = findTableInfoFromCellPos(editor, activePos);\n if (!tableInfo) return null;\n\n const map = TableMap.get(tableInfo.table);\n return tableInfo.tableStart + map.positionAt(map.height - 1, map.width - 1, tableInfo.table);\n}\n\nfunction replaceTableAtCellPos(editor: Editor, cellPos: number | null, updateTable: (tableNode: ProseMirrorNode) => ProseMirrorNode | null) {\n if (cellPos == null) return false;\n const tableInfo = findTableInfoFromCellPos(editor, cellPos);\n if (!tableInfo) return false;\n\n const nextTable = updateTable(tableInfo.table);\n if (!nextTable) return false;\n\n editor.view.dispatch(editor.state.tr.replaceWith(tableInfo.tablePos, tableInfo.tablePos + tableInfo.table.nodeSize, nextTable));\n dispatchTableLayoutChange(editor);\n return true;\n}\n\nexport function duplicateTableRowAt(editor: Editor, rowIndex: number, cellPos: number | null) {\n return replaceTableAtCellPos(editor, cellPos, (tableNode) => {\n const tableWithShiftedReferences = rewriteTableNodeFormulaReferencesForInsertion(\n tableNode,\n \"row\",\n rowIndex + 1,\n );\n const rows = collectChildren(tableWithShiftedReferences);\n const rowNode = rows[rowIndex];\n if (!rowNode) return null;\n rows.splice(rowIndex + 1, 0, shiftCopiedTableNodeFormulaReferences(rowNode, \"row\", 1));\n return tableWithShiftedReferences.type.create(tableWithShiftedReferences.attrs, rows);\n });\n}\n\nexport function clearTableRowAt(editor: Editor, rowIndex: number, cellPos: number | null) {\n return replaceTableAtCellPos(editor, cellPos, (tableNode) => {\n const map = TableMap.get(tableNode);\n if (rowIndex < 0 || rowIndex >= map.height) return null;\n\n const rows = getTableRows(tableNode).map((rowInfo) => {\n const cells = collectChildren(rowInfo.node);\n\n for (const entry of rowInfo.cells) {\n const rect = safeFindCell(map, entry.relativePos);\n if (!rect || rect.top > rowIndex || rowIndex >= rect.bottom) continue;\n cells[entry.index] = createEmptyCellNode(entry.node);\n }\n\n return rowInfo.node.type.create(rowInfo.node.attrs, cells);\n });\n\n return tableNode.type.create(tableNode.attrs, rows);\n });\n}\n\nexport function duplicateTableColumnAt(editor: Editor, columnIndex: number, cellPos: number | null) {\n return replaceTableAtCellPos(editor, cellPos, (tableNode) => {\n const tableWithShiftedReferences = rewriteTableNodeFormulaReferencesForInsertion(\n tableNode,\n \"column\",\n columnIndex + 1,\n );\n const map = TableMap.get(tableWithShiftedReferences);\n if (columnIndex < 0 || columnIndex >= map.width) return null;\n\n const rows = getTableRows(tableWithShiftedReferences).map((rowInfo, rowIndex) => {\n const cells = collectChildren(rowInfo.node);\n const sourceCell = rowInfo.cells.find((entry) => {\n const rect = safeFindCell(map, entry.relativePos);\n return rect\n && rect.top === rowIndex\n && rect.left <= columnIndex\n && columnIndex < rect.right;\n });\n\n if (!sourceCell) return rowInfo.node;\n\n const sourceRect = safeFindCell(map, sourceCell.relativePos);\n if (sourceRect && (sourceRect.left < columnIndex || sourceRect.right > columnIndex + 1)) {\n cells[sourceCell.index] = createCellWithDuplicatedLogicalColumn(sourceCell.node, columnIndex - sourceRect.left);\n return rowInfo.node.type.create(rowInfo.node.attrs, cells);\n }\n\n cells.splice(\n sourceCell.index + 1,\n 0,\n shiftCopiedTableNodeFormulaReferences(createCellCopyForColumnDuplicate(sourceCell.node), \"column\", 1),\n );\n return rowInfo.node.type.create(rowInfo.node.attrs, cells);\n });\n\n const responsiveLayout = normalizeTableWidthMode(tableWithShiftedReferences.attrs.widthMode) === \"responsive\"\n ? insertResponsiveColumnLayout(\n getResponsiveTableWidthBp(tableWithShiftedReferences),\n getTableColumnRatios(tableWithShiftedReferences),\n columnIndex + 1,\n columnIndex,\n )\n : null;\n const tableAttrs = responsiveLayout\n ? {\n ...tableWithShiftedReferences.attrs,\n widthMode: \"responsive\",\n widthBp: responsiveLayout.widthBp,\n offsetBp: resolveResponsiveTableOffsetBp(\n responsiveLayout.widthBp,\n tableWithShiftedReferences.attrs.textAlign,\n tableWithShiftedReferences.attrs.offsetBp,\n ),\n columnRatios: responsiveLayout.columnRatios,\n }\n : tableWithShiftedReferences.attrs;\n\n return tableWithShiftedReferences.type.create(tableAttrs, rows);\n });\n}\n\nexport function clearTableColumnAt(editor: Editor, columnIndex: number, cellPos: number | null) {\n return replaceTableAtCellPos(editor, cellPos, (tableNode) => {\n const map = TableMap.get(tableNode);\n if (columnIndex < 0 || columnIndex >= map.width) return null;\n\n const rows = getTableRows(tableNode).map((rowInfo) => {\n const cells = collectChildren(rowInfo.node);\n\n for (const entry of rowInfo.cells) {\n const rect = safeFindCell(map, entry.relativePos);\n if (!rect || rect.left > columnIndex || columnIndex >= rect.right) continue;\n cells[entry.index] = createEmptyCellNode(entry.node);\n }\n\n return rowInfo.node.type.create(rowInfo.node.attrs, cells);\n });\n\n return tableNode.type.create(tableNode.attrs, rows);\n });\n}\n\nexport function expandTableFromCell(editor: Editor, activeCellPos: number, rows: number, columns: number) {\n let cornerCellPos = getTableCornerCellPos(editor, activeCellPos);\n if (cornerCellPos == null) return false;\n\n for (let index = 0; index < rows; index += 1) {\n const ok = runTableCommandAtCellPos(editor, cornerCellPos, (chain) => chain.addRowAfter());\n if (!ok) return false;\n cornerCellPos = getTableCornerCellPos(editor, cornerCellPos);\n if (cornerCellPos == null) return false;\n }\n\n for (let index = 0; index < columns; index += 1) {\n const ok = runTableCommandAtCellPos(editor, cornerCellPos, (chain) => chain.addColumnAfter());\n if (!ok) return false;\n cornerCellPos = getTableCornerCellPos(editor, cornerCellPos);\n if (cornerCellPos == null) return false;\n }\n\n dispatchTableLayoutChange(editor);\n return true;\n}\n\nfunction getExistingTableWidth(tableNode: ProseMirrorNode, tableEl: HTMLElement | null): number {\n const isResponsive = normalizeTableWidthMode(tableNode.attrs.widthMode) === \"responsive\";\n const map = TableMap.get(tableNode);\n\n let colwidthSum = 0;\n let hasColwidths = true;\n const firstRow = tableNode.firstChild;\n if (firstRow) {\n firstRow.forEach((cell) => {\n const colwidth = cell.attrs.colwidth as number[] | null | undefined;\n if (Array.isArray(colwidth) && colwidth.length > 0 && colwidth[0] > 0) {\n colwidthSum += colwidth.reduce((sum, val) => sum + (Number(val) || 0), 0);\n } else {\n hasColwidths = false;\n }\n });\n } else {\n hasColwidths = false;\n }\n\n if (!isResponsive && hasColwidths && colwidthSum > 0) {\n return Math.round(colwidthSum);\n }\n\n const actualTable = tableEl\n ? (isCrossRealmTable(tableEl)\n ? tableEl\n : isCrossRealmHTMLElement(tableEl)\n ? tableEl.querySelector(\"table\") ?? tableEl\n : null)\n : null;\n\n const domWidth = actualTable?.getBoundingClientRect().width ?? 0;\n if (domWidth > 0) return Math.round(domWidth);\n\n if (colwidthSum > 0) return Math.round(colwidthSum);\n return map.width * 100;\n}\n\nfunction getExistingTableHeight(tableNode: ProseMirrorNode, tableEl: HTMLElement | null): number {\n const actualTable = tableEl\n ? (isCrossRealmTable(tableEl)\n ? tableEl\n : isCrossRealmHTMLElement(tableEl)\n ? tableEl.querySelector(\"table\") ?? tableEl\n : null)\n : null;\n\n const domHeight = actualTable?.getBoundingClientRect().height ?? 0;\n if (domHeight > 0) return Math.round(domHeight);\n\n let total = 0;\n tableNode.forEach((row) => {\n total += Number(row.attrs.rowHeight) || 30;\n });\n return total > 0 ? total : tableNode.childCount * 30;\n}\n\nexport function distributeTableColumnsEqually(editor: Editor, cellPos?: number | null): boolean {\n const targetPos = typeof cellPos === \"number\" ? cellPos : getSelectedTableAnchorCellPos(editor);\n if (targetPos == null) return false;\n\n const tableInfo = findTableInfoFromCellPos(editor, targetPos);\n if (!tableInfo) return false;\n\n const tableMap = TableMap.get(tableInfo.table);\n if (tableMap.width <= 1) return false;\n\n const tableEl = editor.view.nodeDOM(tableInfo.tablePos) as HTMLElement | null;\n const currentWidth = getExistingTableWidth(tableInfo.table, tableEl);\n\n const snapshot = createTableSizeSnapshot(editor, targetPos, currentWidth, 200);\n if (!snapshot) return false;\n\n const equalColumnWidths = normalizeWeightsToTotal(\n Array.from({ length: tableMap.width }, () => 1),\n snapshot.startWidth,\n MIN_RESIZED_TABLE_COLUMN_WIDTH,\n );\n\n const tr = editor.state.tr;\n const tableStart = tableInfo.tablePos + 1;\n\n if (snapshot.widthMode === \"responsive\") {\n const equalColumnRatios = normalizeColumnRatios(\n Array.from({ length: tableMap.width }, () => 1),\n tableMap.width,\n );\n tr.setNodeMarkup(tableInfo.tablePos, undefined, {\n ...tableInfo.table.attrs,\n columnRatios: equalColumnRatios,\n });\n }\n\n const seenCellPositions = new Set<number>();\n for (const relativeCellPos of tableMap.map) {\n if (seenCellPositions.has(relativeCellPos)) continue;\n seenCellPositions.add(relativeCellPos);\n\n const cell = tableInfo.table.nodeAt(relativeCellPos);\n if (!cell) continue;\n\n const cellRect = tableMap.findCell(relativeCellPos);\n const colwidth = equalColumnWidths.slice(cellRect.left, cellRect.right);\n\n tr.setNodeMarkup(tableStart + relativeCellPos, undefined, {\n ...cell.attrs,\n colwidth,\n });\n }\n\n if (!tr.docChanged) return false;\n editor.view.dispatch(tr);\n dispatchTableLayoutChange(editor);\n return true;\n}\n\nfunction calculateTargetRowHeights(\n tableNode: ProseMirrorNode,\n tableEl: HTMLElement | null,\n): number[] {\n const rowCount = tableNode.childCount;\n if (rowCount === 0) return [];\n\n const actualTable = tableEl\n ? (isCrossRealmTable(tableEl)\n ? tableEl\n : isCrossRealmHTMLElement(tableEl)\n ? tableEl.querySelector(\"table\") ?? tableEl\n : null)\n : null;\n\n const trElements = actualTable ? Array.from(actualTable.querySelectorAll(\"tr\")) : [];\n const naturalHeights: number[] = [];\n\n tableNode.forEach((row, _offset, index) => {\n const trEl = trElements[index] as HTMLTableRowElement | undefined;\n if (trEl && isCrossRealmHTMLElement(trEl)) {\n const oldHeight = trEl.style.height;\n const oldMinHeight = trEl.style.minHeight;\n trEl.style.height = \"auto\";\n trEl.style.minHeight = \"0px\";\n const naturalHeight = Math.ceil(trEl.getBoundingClientRect().height);\n trEl.style.height = oldHeight;\n trEl.style.minHeight = oldMinHeight;\n naturalHeights.push(Math.max(MIN_TABLE_ROW_HEIGHT, naturalHeight));\n } else {\n naturalHeights.push(Math.max(MIN_TABLE_ROW_HEIGHT, Number(row.attrs.rowHeight) || 30));\n }\n });\n\n const currentTotalHeight = getExistingTableHeight(tableNode, actualTable);\n const averageHeight = Math.round(currentTotalHeight / rowCount);\n const maxNaturalHeight = Math.max(...naturalHeights, MIN_TABLE_ROW_HEIGHT);\n\n const targetHeight = Math.max(averageHeight, maxNaturalHeight);\n return Array.from({ length: rowCount }, () => targetHeight);\n}\n\nexport function distributeTableRowsEqually(editor: Editor, cellPos?: number | null): boolean {\n const targetPos = typeof cellPos === \"number\" ? cellPos : getSelectedTableAnchorCellPos(editor);\n if (targetPos == null) return false;\n\n const tableInfo = findTableInfoFromCellPos(editor, targetPos);\n if (!tableInfo) return false;\n\n const tableMap = TableMap.get(tableInfo.table);\n if (tableMap.height <= 1) return false;\n\n const tableEl = editor.view.nodeDOM(tableInfo.tablePos) as HTMLElement | null;\n const equalRowHeights = calculateTargetRowHeights(tableInfo.table, tableEl);\n if (equalRowHeights.length === 0) return false;\n\n const tr = editor.state.tr;\n const tableStart = tableInfo.tablePos + 1;\n\n tableInfo.table.forEach((row, offset, rowIndex) => {\n const rowHeight = equalRowHeights[rowIndex];\n tr.setNodeMarkup(tableStart + offset, undefined, {\n ...row.attrs,\n rowHeight,\n });\n });\n\n if (!tr.docChanged) return false;\n editor.view.dispatch(tr);\n dispatchTableLayoutChange(editor);\n return true;\n}\n\nexport function distributeTableRowsAndColumnsEqually(editor: Editor, cellPos?: number | null): boolean {\n const targetPos = typeof cellPos === \"number\" ? cellPos : getSelectedTableAnchorCellPos(editor);\n if (targetPos == null) return false;\n\n const tableInfo = findTableInfoFromCellPos(editor, targetPos);\n if (!tableInfo) return false;\n\n const tableMap = TableMap.get(tableInfo.table);\n if (tableMap.width <= 1 && tableMap.height <= 1) return false;\n\n const tableEl = editor.view.nodeDOM(tableInfo.tablePos) as HTMLElement | null;\n const currentWidth = getExistingTableWidth(tableInfo.table, tableEl);\n const currentHeight = getExistingTableHeight(tableInfo.table, tableEl);\n\n const snapshot = createTableSizeSnapshot(editor, targetPos, currentWidth, currentHeight);\n if (!snapshot) return false;\n\n const tr = editor.state.tr;\n const tableStart = tableInfo.tablePos + 1;\n\n if (tableMap.width > 1) {\n const equalColumnWidths = normalizeWeightsToTotal(\n Array.from({ length: tableMap.width }, () => 1),\n snapshot.startWidth,\n MIN_RESIZED_TABLE_COLUMN_WIDTH,\n );\n\n if (snapshot.widthMode === \"responsive\") {\n const equalColumnRatios = normalizeColumnRatios(\n Array.from({ length: tableMap.width }, () => 1),\n tableMap.width,\n );\n tr.setNodeMarkup(tableInfo.tablePos, undefined, {\n ...tableInfo.table.attrs,\n columnRatios: equalColumnRatios,\n });\n }\n\n const seenCellPositions = new Set<number>();\n for (const relativeCellPos of tableMap.map) {\n if (seenCellPositions.has(relativeCellPos)) continue;\n seenCellPositions.add(relativeCellPos);\n\n const cell = tableInfo.table.nodeAt(relativeCellPos);\n if (!cell) continue;\n\n const cellRect = tableMap.findCell(relativeCellPos);\n const colwidth = equalColumnWidths.slice(cellRect.left, cellRect.right);\n\n tr.setNodeMarkup(tableStart + relativeCellPos, undefined, {\n ...cell.attrs,\n colwidth,\n });\n }\n }\n\n if (tableMap.height > 1) {\n const equalRowHeights = calculateTargetRowHeights(tableInfo.table, tableEl);\n\n tableInfo.table.forEach((row, offset, rowIndex) => {\n const rowHeight = equalRowHeights[rowIndex];\n tr.setNodeMarkup(tableStart + offset, undefined, {\n ...row.attrs,\n rowHeight,\n });\n });\n }\n\n if (!tr.docChanged) return false;\n editor.view.dispatch(tr);\n dispatchTableLayoutChange(editor);\n return true;\n}\n","import type { Node as ProseMirrorNode } from \"@tiptap/pm/model\";\nimport type { EditorView } from \"@tiptap/pm/view\";\n\nexport const DEFAULT_TABLE_ROW_HEIGHT = 25;\nexport const MIN_TABLE_ROW_HEIGHT = DEFAULT_TABLE_ROW_HEIGHT;\nexport const COLUMN_RESIZE_LINE_THICKNESS = 2;\nexport const ROW_RESIZE_LINE_THICKNESS = 2;\nexport const UEDITOR_TABLE_LAYOUT_CHANGE_EVENT = \"ueditor:table-layout-change\";\n\nexport const isRowResizingGlobal = { active: false };\n\n/** DOM guards intentionally use node shape/tag names so adopted nodes remain valid across realms. */\nexport function isCrossRealmNode(value: unknown): value is Node {\n return Boolean(value && typeof value === \"object\" && (value as Node).nodeType != null);\n}\n\nexport function isCrossRealmElement(value: unknown): value is Element {\n return isCrossRealmNode(value) && (value as Node).nodeType === 1 && typeof (value as Element).closest === \"function\";\n}\n\nexport function isCrossRealmHTMLElement(value: unknown): value is HTMLElement {\n return isCrossRealmElement(value) && typeof (value as HTMLElement).style === \"object\";\n}\n\nexport function isCrossRealmTable(value: unknown): value is HTMLTableElement {\n return isCrossRealmElement(value) && String((value as Element).tagName).toUpperCase() === \"TABLE\" && \"rows\" in value;\n}\n\nexport function isCrossRealmTableRow(value: unknown): value is HTMLTableRowElement {\n return isCrossRealmElement(value) && String((value as Element).tagName).toUpperCase() === \"TR\" && \"cells\" in value;\n}\n\nexport function isCrossRealmTableCell(value: unknown): value is HTMLTableCellElement {\n return isCrossRealmElement(value) && [\"TD\", \"TH\"].includes(String((value as Element).tagName).toUpperCase()) && \"cellIndex\" in value;\n}\n\nexport function isValidProseMirrorPosition(doc: ProseMirrorNode, pos: unknown): pos is number {\n return Number.isInteger(pos) && (pos as number) >= 0 && (pos as number) <= doc.content.size;\n}\n\nconst TABLE_RESIZE_HIT_ZONE = 5;\n\nexport function findTableRowNodeInfo(view: EditorView, rowElement: HTMLTableRowElement): { pos: number; node: ProseMirrorNode } | null {\n if (!view.dom.contains(rowElement)) return null;\n\n const firstCell = rowElement.querySelector(\"th,td\");\n if (!isCrossRealmTableCell(firstCell) || !view.dom.contains(firstCell)) return null;\n\n const cellPos = view.posAtDOM(firstCell, 0);\n if (!isValidProseMirrorPosition(view.state.doc, cellPos)) return null;\n const $pos = view.state.doc.resolve(cellPos);\n\n for (let depth = $pos.depth; depth > 0; depth -= 1) {\n const node = $pos.node(depth);\n if (node.type.name === \"tableRow\") {\n return {\n pos: $pos.before(depth),\n node,\n };\n }\n }\n\n return null;\n}\n\nexport function resolveEventElement(target: EventTarget | null) {\n if (isCrossRealmElement(target)) return target;\n if (isCrossRealmNode(target)) return target.parentElement;\n return null;\n}\n\n/**\n * Returns true only when the pointer is over a rendered text run. Checking the\n * event target is not sufficient because block elements usually fill the\n * complete table cell, including its empty padding.\n */\nexport function isPointOverRenderedText(root: HTMLElement, clientX: number, clientY: number) {\n const view = root.ownerDocument.defaultView;\n if (!view) return false;\n\n const walker = root.ownerDocument.createTreeWalker(root, view.NodeFilter.SHOW_TEXT);\n let textNode = walker.nextNode();\n\n while (textNode) {\n if (textNode.textContent?.length) {\n const range = root.ownerDocument.createRange();\n range.selectNodeContents(textNode);\n const textRects = Array.from(range.getClientRects());\n range.detach?.();\n\n if (textRects.some((rect) => (\n clientX >= rect.left\n && clientX <= rect.right\n && clientY >= rect.top\n && clientY <= rect.bottom\n ))) {\n return true;\n }\n }\n\n textNode = walker.nextNode();\n }\n\n return false;\n}\n\nexport function getSelectionTableCell(view: EditorView) {\n const realm = view.dom.ownerDocument.defaultView;\n const browserSelection = realm?.getSelection();\n const anchorElement = resolveEventElement(browserSelection?.anchorNode ?? null);\n const anchorCell = anchorElement?.closest?.(\"th,td\");\n if (isCrossRealmTableCell(anchorCell) && view.dom.contains(anchorCell)) {\n return anchorCell;\n }\n\n const { from } = view.state.selection;\n const domAtPos = view.domAtPos(from);\n const element = resolveEventElement(domAtPos.node);\n const cell = element?.closest?.(\"th,td\");\n return isCrossRealmTableCell(cell) && view.dom.contains(cell) ? cell : null;\n}\n\nexport function resolveRowResizeTarget(\n cell: HTMLElement,\n clientX: number,\n clientY: number,\n): { row: HTMLTableRowElement; cell: HTMLTableCellElement } | null {\n const rect = cell.getBoundingClientRect();\n const row = cell.closest(\"tr\");\n if (!isCrossRealmTableRow(row) || !isCrossRealmTableCell(cell)) {\n return null;\n }\n\n const distToBottom = Math.abs(clientY - rect.bottom);\n const distToTop = Math.abs(clientY - rect.top);\n const distToRight = Math.abs(clientX - rect.right);\n const distToLeft = Math.abs(clientX - rect.left);\n\n if (distToRight <= 3 || distToLeft <= 3) {\n return null;\n }\n\n if (distToBottom <= TABLE_RESIZE_HIT_ZONE) {\n return { row, cell };\n }\n\n if (distToTop <= TABLE_RESIZE_HIT_ZONE) {\n const prevRow = row.previousElementSibling;\n if (isCrossRealmTableRow(prevRow)) {\n const cellIndex = cell.cellIndex;\n const prevCell = (prevRow.children[cellIndex] ?? prevRow.firstElementChild) as HTMLTableCellElement | null;\n if (isCrossRealmTableCell(prevCell)) {\n return { row: prevRow, cell: prevCell };\n }\n }\n }\n\n return null;\n}\n\nexport function resolveColumnResizeTarget(\n cell: HTMLElement,\n clientX: number,\n clientY: number,\n): { row: HTMLTableRowElement; cell: HTMLTableCellElement } | null {\n const rect = cell.getBoundingClientRect();\n const row = cell.closest(\"tr\");\n if (!isCrossRealmTableRow(row) || !isCrossRealmTableCell(cell)) {\n return null;\n }\n\n const distToRight = Math.abs(clientX - rect.right);\n const distToLeft = Math.abs(clientX - rect.left);\n const distToBottom = Math.abs(clientY - rect.bottom);\n const distToTop = Math.abs(clientY - rect.top);\n\n if (distToBottom <= 3 || distToTop <= 3) {\n return null;\n }\n\n if (distToRight <= TABLE_RESIZE_HIT_ZONE) {\n return { row, cell };\n }\n\n if (distToLeft <= TABLE_RESIZE_HIT_ZONE) {\n const prevCell = cell.previousElementSibling;\n if (isCrossRealmTableCell(prevCell)) {\n return { row, cell: prevCell };\n }\n }\n\n return null;\n}\n\nexport function isRowResizeHotspot(cell: HTMLElement, clientX: number, clientY: number) {\n return resolveRowResizeTarget(cell, clientX, clientY) !== null;\n}\n\nexport function isColumnResizeHotspot(cell: HTMLElement, clientX: number, clientY: number) {\n return resolveColumnResizeTarget(cell, clientX, clientY) !== null;\n}\n\nexport function getRelativeBoundaryMetrics(surface: HTMLElement, table: HTMLTableElement, row: HTMLTableRowElement, cell: HTMLTableCellElement) {\n const surfaceRect = surface.getBoundingClientRect();\n const originLeft = surfaceRect.left + surface.clientLeft;\n const originTop = surfaceRect.top + surface.clientTop;\n const tableRect = table.getBoundingClientRect();\n const rowRect = row.getBoundingClientRect();\n const cellRect = cell.getBoundingClientRect();\n\n return {\n left: tableRect.left - originLeft + surface.scrollLeft,\n top: tableRect.top - originTop + surface.scrollTop,\n width: tableRect.width,\n height: tableRect.height,\n rowBottom: rowRect.bottom - originTop + surface.scrollTop,\n columnRight: cellRect.right - originLeft + surface.scrollLeft,\n };\n}\n\nexport function getRelativeCellMetrics(surface: HTMLElement, cell: HTMLElement) {\n const surfaceRect = surface.getBoundingClientRect();\n const originLeft = surfaceRect.left + surface.clientLeft;\n const originTop = surfaceRect.top + surface.clientTop;\n const cellRect = cell.getBoundingClientRect();\n\n return {\n left: cellRect.left - originLeft + surface.scrollLeft,\n top: cellRect.top - originTop + surface.scrollTop,\n width: cellRect.width,\n height: cellRect.height,\n };\n}\n\nexport function getRelativeSelectedCellsMetrics(surface: HTMLElement) {\n const selectedCells = Array.from(\n surface.querySelectorAll<HTMLElement>(\"td.selectedCell, th.selectedCell\"),\n );\n\n if (selectedCells.length === 0) {\n return null;\n }\n\n const surfaceRect = surface.getBoundingClientRect();\n const originLeft = surfaceRect.left + surface.clientLeft;\n const originTop = surfaceRect.top + surface.clientTop;\n let left = Number.POSITIVE_INFINITY;\n let top = Number.POSITIVE_INFINITY;\n let right = Number.NEGATIVE_INFINITY;\n let bottom = Number.NEGATIVE_INFINITY;\n\n selectedCells.forEach((cell) => {\n const rect = cell.getBoundingClientRect();\n left = Math.min(left, rect.left);\n top = Math.min(top, rect.top);\n right = Math.max(right, rect.right);\n bottom = Math.max(bottom, rect.bottom);\n });\n\n return {\n left: left - originLeft + surface.scrollLeft,\n top: top - originTop + surface.scrollTop,\n width: right - left,\n height: bottom - top,\n };\n}\n","import type { Node as ProseMirrorNode } from \"@tiptap/pm/model\";\nimport { Plugin, type EditorState } from \"@tiptap/pm/state\";\nimport {\n Decoration,\n DecorationSet,\n type EditorView,\n type NodeView,\n type ViewMutationRecord,\n} from \"@tiptap/pm/view\";\nimport {\n ResizeState,\n TableMap,\n cellAround,\n columnResizingPluginKey,\n pointsAtCell,\n tableNodeTypes,\n type ColumnResizingOptions,\n} from \"@tiptap/pm/tables\";\nimport { isCrossRealmElement, isCrossRealmHTMLElement, isCrossRealmNode, isCrossRealmTable } from \"./table-dom-utils\";\nimport {\n formatBasisPointsAsPercentage,\n getLegacyTableColumnWeights,\n getResponsiveTableOffsetBp,\n getResponsiveTableWidthBp,\n getTableColumnRatios,\n normalizeColumnRatios,\n normalizeTableWidthMode,\n} from \"./table-width-model\";\n\nexport const DEFAULT_TABLE_COLUMN_WIDTH = 100;\nexport const MIN_RESIZED_TABLE_COLUMN_WIDTH = 25;\n\ntype DynamicColumnDragging = {\n startX: number;\n startWidth: number;\n minWidth: number;\n columnIndex?: number;\n responsiveColumnWidths?: number[];\n neighborStartWidth?: number;\n};\n\nexport function getColumnResizeMinWidth(configuredMinWidth: number) {\n const normalizedMinWidth = Number.isFinite(configuredMinWidth) && configuredMinWidth > 0\n ? Math.round(configuredMinWidth)\n : MIN_RESIZED_TABLE_COLUMN_WIDTH;\n\n return Math.max(MIN_RESIZED_TABLE_COLUMN_WIDTH, normalizedMinWidth);\n}\n\nfunction setColumnStyle(\n column: HTMLTableColElement,\n width: number,\n ratio: number,\n explicit: boolean,\n responsive: boolean,\n) {\n column.style.width = responsive ? formatBasisPointsAsPercentage(ratio) : `${width}px`;\n column.style.minWidth = responsive || explicit ? \"\" : `${width}px`;\n column.setAttribute(\"width\", String(width));\n}\n\nfunction isTableColumnElement(node: ChildNode | null): node is HTMLTableColElement {\n return isCrossRealmElement(node) && String(node.tagName).toUpperCase() === \"COL\";\n}\n\nfunction updateDynamicColumns(\n node: ProseMirrorNode,\n colgroup: HTMLTableColElement,\n table: HTMLTableElement,\n ownerDocument: Document,\n overrideCol?: number,\n overrideValue?: number,\n) {\n let totalWidth = 0;\n let nextDOM = colgroup.firstChild;\n const row = node.firstChild;\n const columns: Array<{ element: HTMLTableColElement; explicit: boolean; width: number }> = [];\n\n if (row) {\n for (let rowCellIndex = 0, col = 0; rowCellIndex < row.childCount; rowCellIndex += 1) {\n const { colspan, colwidth } = row.child(rowCellIndex).attrs as { colspan: number; colwidth?: number[] | null };\n\n for (let spanIndex = 0; spanIndex < colspan; spanIndex += 1, col += 1) {\n const rawWidth = overrideCol === col ? overrideValue : colwidth?.[spanIndex];\n const width = rawWidth ? Math.max(rawWidth, MIN_RESIZED_TABLE_COLUMN_WIDTH) : null;\n totalWidth += width ?? DEFAULT_TABLE_COLUMN_WIDTH;\n\n const colElement = isTableColumnElement(nextDOM)\n ? nextDOM\n : colgroup.appendChild(ownerDocument.createElement(\"col\"));\n columns.push({\n element: colElement,\n explicit: width !== null,\n width: width ?? DEFAULT_TABLE_COLUMN_WIDTH,\n });\n nextDOM = colElement.nextSibling;\n }\n }\n }\n\n while (nextDOM) {\n const after = nextDOM.nextSibling;\n nextDOM.parentNode?.removeChild(nextDOM);\n nextDOM = after;\n }\n\n const responsive = normalizeTableWidthMode(node.attrs.widthMode) === \"responsive\";\n const columnRatios = getTableColumnRatios(node);\n columns.forEach(({ element, explicit, width }, index) => {\n setColumnStyle(element, width, columnRatios[index] ?? 1, explicit, responsive);\n });\n\n if (responsive) {\n const widthBp = getResponsiveTableWidthBp(node);\n const offsetBp = getResponsiveTableOffsetBp(node);\n table.setAttribute(\"data-table-width-mode\", \"responsive\");\n table.setAttribute(\"data-table-width\", formatBasisPointsAsPercentage(widthBp));\n table.setAttribute(\"data-table-width-bp\", String(widthBp));\n table.setAttribute(\"data-table-offset\", formatBasisPointsAsPercentage(offsetBp));\n table.setAttribute(\"data-table-offset-bp\", String(offsetBp));\n table.setAttribute(\"data-table-column-ratios\", columnRatios.join(\",\"));\n table.style.width = formatBasisPointsAsPercentage(widthBp);\n table.style.marginLeft = formatBasisPointsAsPercentage(offsetBp);\n table.style.marginRight = \"auto\";\n table.style.minWidth = `${Math.max(1, colgroup.childElementCount) * MIN_RESIZED_TABLE_COLUMN_WIDTH}px`;\n } else {\n table.removeAttribute(\"data-table-width-mode\");\n table.removeAttribute(\"data-table-width\");\n table.removeAttribute(\"data-table-width-bp\");\n table.removeAttribute(\"data-table-offset\");\n table.removeAttribute(\"data-table-offset-bp\");\n table.removeAttribute(\"data-table-column-ratios\");\n table.style.width = `${totalWidth}px`;\n table.style.minWidth = \"\";\n const tableAlign = node.attrs.textAlign;\n table.style.marginLeft = tableAlign === \"center\" || tableAlign === \"right\" ? \"auto\" : \"0px\";\n table.style.marginRight = tableAlign === \"center\" ? \"auto\" : tableAlign === \"right\" ? \"0px\" : \"auto\";\n }\n\n if (node.attrs.textAlign) table.setAttribute(\"data-table-align\", String(node.attrs.textAlign));\n else table.removeAttribute(\"data-table-align\");\n}\n\nclass UEditorTableView implements NodeView {\n node: ProseMirrorNode;\n\n dom: HTMLDivElement;\n\n table: HTMLTableElement;\n\n colgroup: HTMLTableColElement;\n\n contentDOM: HTMLTableSectionElement;\n\n constructor(node: ProseMirrorNode, _defaultColumnWidth: number | EditorView, maybeView?: EditorView) {\n this.node = node;\n const view = maybeView ?? _defaultColumnWidth as EditorView;\n const ownerDocument = view.dom.ownerDocument;\n this.dom = ownerDocument.createElement(\"div\");\n this.dom.className = \"tableWrapper\";\n this.table = this.dom.appendChild(ownerDocument.createElement(\"table\"));\n\n if (node.attrs.style) {\n this.table.style.cssText = node.attrs.style;\n }\n this.table.style.tableLayout = \"fixed\";\n\n this.colgroup = this.table.appendChild(ownerDocument.createElement(\"colgroup\"));\n updateDynamicColumns(node, this.colgroup, this.table, ownerDocument);\n this.contentDOM = this.table.appendChild(ownerDocument.createElement(\"tbody\"));\n }\n\n update(node: ProseMirrorNode) {\n if (node.type !== this.node.type) return false;\n\n this.node = node;\n updateDynamicColumns(node, this.colgroup, this.table, this.dom.ownerDocument);\n return true;\n }\n\n ignoreMutation(mutation: ViewMutationRecord) {\n const target = mutation.target;\n const isInsideWrapper = this.dom.contains(target);\n const isInsideContent = this.contentDOM.contains(target);\n\n if (isInsideWrapper && !isInsideContent) {\n return mutation.type === \"attributes\" || mutation.type === \"childList\" || mutation.type === \"characterData\";\n }\n\n return false;\n }\n}\n\nfunction getDraggedWidth(dragging: DynamicColumnDragging, event: MouseEvent) {\n const offset = event.clientX - dragging.startX;\n const maximum = dragging.neighborStartWidth === undefined\n ? Number.POSITIVE_INFINITY\n : dragging.startWidth + dragging.neighborStartWidth - dragging.minWidth;\n return Math.min(maximum, Math.max(dragging.minWidth, Math.round(dragging.startWidth + offset)));\n}\n\nfunction normalizeColumnWidthsToTotal(values: number[], total: number, minimum: number) {\n const safeTotal = Math.max(values.length * minimum, Math.round(total));\n const weights = values.map((value) => Number.isFinite(value) && value > 0 ? value : DEFAULT_TABLE_COLUMN_WIDTH);\n const weightSum = weights.reduce((sum, value) => sum + value, 0);\n const widths = weights.map((value) => Math.max(minimum, Math.round((value / weightSum) * safeTotal)));\n let difference = safeTotal - widths.reduce((sum, value) => sum + value, 0);\n\n while (difference !== 0) {\n let changed = false;\n for (let index = widths.length - 1; index >= 0 && difference !== 0; index -= 1) {\n if (difference < 0 && widths[index] <= minimum) continue;\n widths[index] += difference > 0 ? 1 : -1;\n difference += difference > 0 ? -1 : 1;\n changed = true;\n }\n if (!changed) break;\n }\n\n return widths;\n}\n\nfunction getResizeColumnInfo(state: EditorState, cell: number) {\n const $cell = state.doc.resolve(cell);\n const table = $cell.node(-1);\n const map = TableMap.get(table);\n const start = $cell.start(-1);\n const nodeAfter = $cell.nodeAfter;\n if (!nodeAfter) return null;\n\n return {\n col: map.colCount($cell.pos - start) + nodeAfter.attrs.colspan - 1,\n map,\n start,\n table,\n };\n}\n\nfunction getCurrentColWidth(\n view: EditorView,\n cellPos: number,\n { colspan, colwidth }: { colspan: number; colwidth?: number[] | null },\n) {\n const width = colwidth?.[colwidth.length - 1];\n if (width) return width;\n\n const dom = view.domAtPos(cellPos);\n const cellElement = dom.node.childNodes[dom.offset];\n let domWidth = isCrossRealmHTMLElement(cellElement) ? cellElement.offsetWidth : 0;\n let parts = Math.max(1, colspan);\n\n if (colwidth) {\n for (let index = 0; index < colspan; index += 1) {\n const partWidth = colwidth[index];\n if (partWidth) {\n domWidth -= partWidth;\n parts -= 1;\n }\n }\n }\n\n return domWidth / Math.max(1, parts);\n}\n\nfunction domCellAround(view: EditorView, target: EventTarget | null) {\n let node = isCrossRealmNode(target) ? target : null;\n\n while (node && node.nodeName !== \"TD\" && node.nodeName !== \"TH\") {\n const element = isCrossRealmElement(node) ? node : null;\n if (element?.classList.contains(\"ProseMirror\")) return null;\n node = node.parentNode;\n }\n\n return isCrossRealmHTMLElement(node) ? node : null;\n}\n\nfunction edgeCell(view: EditorView, event: MouseEvent, side: \"left\" | \"right\", handleWidth: number) {\n const offset = side === \"right\" ? -handleWidth : handleWidth;\n const found = view.posAtCoords({\n left: event.clientX + offset,\n top: event.clientY,\n });\n if (!found) return -1;\n\n const $cell = cellAround(view.state.doc.resolve(found.pos));\n if (!$cell) return -1;\n if (side === \"right\") return $cell.pos;\n\n const map = TableMap.get($cell.node(-1));\n const start = $cell.start(-1);\n const index = map.map.indexOf($cell.pos - start);\n return index % map.width === 0 ? -1 : start + map.map[index - 1];\n}\n\nlet handleHoverTimer: number | null = null;\nlet handleHoverWindow: Window | null = null;\nlet pendingHandleCell = -1;\n\nfunction clearHandleHoverTimer() {\n if (handleHoverTimer !== null) {\n handleHoverWindow?.clearTimeout(handleHoverTimer);\n handleHoverTimer = null;\n }\n handleHoverWindow = null;\n pendingHandleCell = -1;\n}\n\nfunction updateHandle(view: EditorView, value: number) {\n view.dispatch(view.state.tr.setMeta(columnResizingPluginKey, { setHandle: value }));\n}\n\nfunction handleMouseMove(view: EditorView, event: MouseEvent, handleWidth: number, lastColumnResizable: boolean) {\n if (!view.editable) return;\n\n const pluginState = columnResizingPluginKey.getState(view.state);\n if (!pluginState || pluginState.dragging) return;\n\n const target = domCellAround(view, event.target);\n let cell = -1;\n\n if (target) {\n const { left, right } = target.getBoundingClientRect();\n if (event.clientX - left <= handleWidth) cell = edgeCell(view, event, \"left\", handleWidth);\n else if (right - event.clientX <= handleWidth) cell = edgeCell(view, event, \"right\", handleWidth);\n }\n\n if (cell !== -1) {\n const info = getResizeColumnInfo(view.state, cell);\n if (info && normalizeTableWidthMode(info.table.attrs.widthMode) === \"responsive\" && info.col === info.map.width - 1) {\n cell = -1;\n }\n }\n\n if (cell === pluginState.activeHandle) {\n clearHandleHoverTimer();\n return;\n }\n\n if (cell === -1) {\n clearHandleHoverTimer();\n if (pluginState.activeHandle !== -1) {\n updateHandle(view, -1);\n }\n return;\n }\n\n if (!lastColumnResizable) {\n const $cell = view.state.doc.resolve(cell);\n const table = $cell.node(-1);\n const map = TableMap.get(table);\n const tableStart = $cell.start(-1);\n const nodeAfter = $cell.nodeAfter;\n if (!nodeAfter) return;\n\n if (map.colCount($cell.pos - tableStart) + nodeAfter.attrs.colspan - 1 === map.width - 1) {\n clearHandleHoverTimer();\n if (pluginState.activeHandle !== -1) {\n updateHandle(view, -1);\n }\n return;\n }\n }\n\n if (pendingHandleCell === cell) return;\n\n clearHandleHoverTimer();\n pendingHandleCell = cell;\n const ownerWindow = view.dom.ownerDocument.defaultView;\n if (!ownerWindow) return;\n handleHoverWindow = ownerWindow;\n handleHoverTimer = ownerWindow.setTimeout(() => {\n handleHoverTimer = null;\n pendingHandleCell = -1;\n updateHandle(view, cell);\n }, 100);\n}\n\nfunction handleMouseLeave(view: EditorView) {\n clearHandleHoverTimer();\n if (!view.editable) return;\n\n const pluginState = columnResizingPluginKey.getState(view.state);\n if (pluginState && pluginState.activeHandle > -1 && !pluginState.dragging) {\n updateHandle(view, -1);\n }\n}\n\nfunction updateColumnWidths(\n view: EditorView,\n cell: number,\n widthsByColumn: ReadonlyMap<number, number>,\n columnRatios?: number[],\n) {\n const info = getResizeColumnInfo(view.state, cell);\n if (!info) return;\n const { map, start, table } = info;\n const tr = view.state.tr;\n const seenCellPositions = new Set<number>();\n\n for (const pos of map.map) {\n if (seenCellPositions.has(pos)) continue;\n seenCellPositions.add(pos);\n const cellNode = table.nodeAt(pos);\n if (!cellNode) continue;\n\n const attrs = cellNode.attrs;\n const colwidth = attrs.colwidth ? attrs.colwidth.slice() : Array.from({ length: attrs.colspan }, () => 0);\n const cellStartColumn = map.colCount(pos);\n let changed = false;\n for (let index = 0; index < attrs.colspan; index += 1) {\n const width = widthsByColumn.get(cellStartColumn + index);\n if (width === undefined || colwidth[index] === width) continue;\n colwidth[index] = width;\n changed = true;\n }\n if (!changed) continue;\n\n tr.setNodeMarkup(start + pos, null, {\n ...attrs,\n colwidth,\n });\n }\n\n if (columnRatios) {\n tr.setNodeMarkup(start - 1, undefined, {\n ...table.attrs,\n widthMode: \"responsive\",\n columnRatios: normalizeColumnRatios(columnRatios, map.width),\n });\n }\n\n if (tr.docChanged) view.dispatch(tr);\n}\n\nfunction updateColumnWidth(view: EditorView, cell: number, width: number) {\n const info = getResizeColumnInfo(view.state, cell);\n if (!info) return;\n updateColumnWidths(view, cell, new Map([[info.col, width]]));\n}\n\nfunction getActiveDragging(state: EditorState): DynamicColumnDragging | null {\n const dragging = columnResizingPluginKey.getState(state)?.dragging;\n return dragging ? (dragging as DynamicColumnDragging) : null;\n}\n\nfunction getColumnResizeGhost(view: EditorView) {\n const doc = view.dom.ownerDocument;\n let ghost = doc.querySelector<HTMLDivElement>(\"[data-ueditor-column-resize-ghost]\");\n if (!ghost) {\n ghost = doc.createElement(\"div\");\n ghost.setAttribute(\"data-ueditor-column-resize-ghost\", \"\");\n ghost.style.position = \"fixed\";\n ghost.style.zIndex = \"99999\";\n ghost.style.pointerEvents = \"none\";\n ghost.style.width = \"2px\";\n ghost.style.backgroundColor = \"var(--primary, #2563eb)\";\n ghost.style.opacity = \"0.5\";\n ghost.style.borderRadius = \"9999px\";\n ghost.style.boxShadow = \"0 0 0 1px color-mix(in oklch, var(--background, #fff) 80%, transparent)\";\n ghost.style.transform = \"translateX(-1px)\";\n ghost.style.willChange = \"left\";\n doc.body.appendChild(ghost);\n }\n\n return ghost;\n}\n\nfunction hideColumnResizeGhost(view: EditorView) {\n view.dom.ownerDocument.querySelector(\"[data-ueditor-column-resize-ghost]\")?.remove();\n}\n\nfunction getTableElementAtCell(view: EditorView, cell: number) {\n const $cell = view.state.doc.resolve(cell);\n let dom: Node | null = view.domAtPos($cell.start(-1)).node;\n while (dom && dom.nodeName !== \"TABLE\") dom = dom.parentNode;\n return isCrossRealmTable(dom) ? dom : null;\n}\n\nfunction showColumnResizeGhost(view: EditorView, cell: number, dragging: DynamicColumnDragging, width: number) {\n const table = getTableElementAtCell(view, cell);\n if (!table) return;\n\n const rect = table.getBoundingClientRect();\n const left = dragging.startX + width - dragging.startWidth;\n const ghost = getColumnResizeGhost(view);\n ghost.style.left = `${left}px`;\n ghost.style.top = `${rect.top}px`;\n ghost.style.height = `${rect.height}px`;\n}\n\nfunction handleMouseDown(\n view: EditorView,\n event: MouseEvent,\n cellMinWidth: number,\n) {\n clearHandleHoverTimer();\n if (!view.editable) return false;\n\n const win = view.dom.ownerDocument.defaultView ?? window;\n const pluginState = columnResizingPluginKey.getState(view.state);\n if (!pluginState || pluginState.activeHandle === -1 || pluginState.dragging) return false;\n\n const cell = view.state.doc.nodeAt(pluginState.activeHandle);\n if (!cell) return false;\n\n const resizeInfo = getResizeColumnInfo(view.state, pluginState.activeHandle);\n if (!resizeInfo) return false;\n\n const attrs = cell.attrs as { colspan?: number; colwidth?: number[] | null };\n let width = getCurrentColWidth(view, pluginState.activeHandle, {\n colspan: attrs.colspan ?? 1,\n colwidth: attrs.colwidth,\n });\n const minWidth = getColumnResizeMinWidth(cellMinWidth);\n let responsiveColumnWidths: number[] | undefined;\n let neighborStartWidth: number | undefined;\n\n if (normalizeTableWidthMode(resizeInfo.table.attrs.widthMode) === \"responsive\") {\n if (resizeInfo.col >= resizeInfo.map.width - 1) return false;\n\n const storedRatios = getTableColumnRatios(resizeInfo.table);\n const legacyWidths = getLegacyTableColumnWeights(resizeInfo.table, DEFAULT_TABLE_COLUMN_WIDTH);\n const storedTotal = legacyWidths.reduce((sum, value) => sum + value, 0);\n const tableElement = getTableElementAtCell(view, pluginState.activeHandle);\n const renderedWidth = tableElement?.getBoundingClientRect().width || storedTotal;\n responsiveColumnWidths = normalizeColumnWidthsToTotal(storedRatios, renderedWidth, minWidth);\n width = responsiveColumnWidths[resizeInfo.col];\n neighborStartWidth = responsiveColumnWidths[resizeInfo.col + 1];\n }\n\n const dragging: DynamicColumnDragging = {\n startX: event.clientX,\n startWidth: width,\n minWidth,\n ...(responsiveColumnWidths\n ? {\n columnIndex: resizeInfo.col,\n responsiveColumnWidths,\n neighborStartWidth,\n }\n : null),\n };\n\n view.dispatch(view.state.tr.setMeta(columnResizingPluginKey, { setDragging: dragging }));\n\n function finish(nextEvent: MouseEvent) {\n win.removeEventListener(\"mouseup\", finish);\n win.removeEventListener(\"mousemove\", move);\n\n const activeDragging = getActiveDragging(view.state);\n const activeHandle = columnResizingPluginKey.getState(view.state)?.activeHandle ?? -1;\n if (activeDragging && activeHandle > -1) {\n const nextWidth = getDraggedWidth(activeDragging, nextEvent);\n if (\n activeDragging.responsiveColumnWidths\n && activeDragging.columnIndex !== undefined\n && activeDragging.neighborStartWidth !== undefined\n ) {\n const nextColumnWidths = activeDragging.responsiveColumnWidths.slice();\n nextColumnWidths[activeDragging.columnIndex] = nextWidth;\n nextColumnWidths[activeDragging.columnIndex + 1] = (\n activeDragging.startWidth + activeDragging.neighborStartWidth - nextWidth\n );\n updateColumnWidths(\n view,\n activeHandle,\n new Map(nextColumnWidths.map((columnWidth, index) => [index, columnWidth])),\n normalizeColumnRatios(nextColumnWidths, nextColumnWidths.length),\n );\n } else {\n updateColumnWidth(view, activeHandle, nextWidth);\n }\n view.dispatch(view.state.tr.setMeta(columnResizingPluginKey, { setDragging: null }));\n }\n hideColumnResizeGhost(view);\n }\n\n function move(nextEvent: MouseEvent) {\n if (!nextEvent.buttons) return finish(nextEvent);\n\n const activeDragging = getActiveDragging(view.state);\n const activeHandle = columnResizingPluginKey.getState(view.state)?.activeHandle ?? -1;\n if (activeDragging && activeHandle > -1) {\n showColumnResizeGhost(view, activeHandle, activeDragging, getDraggedWidth(activeDragging, nextEvent));\n }\n }\n\n showColumnResizeGhost(view, pluginState.activeHandle, dragging, width);\n win.addEventListener(\"mouseup\", finish);\n win.addEventListener(\"mousemove\", move);\n event.preventDefault();\n return true;\n}\n\nfunction handleDecorations(state: EditorState, cell: number, ownerDocument: Document | null) {\n if (!ownerDocument) return DecorationSet.empty;\n const decorations = [];\n const $cell = state.doc.resolve(cell);\n const table = $cell.node(-1);\n if (!table) return DecorationSet.empty;\n\n const map = TableMap.get(table);\n const start = $cell.start(-1);\n const nodeAfter = $cell.nodeAfter;\n if (!nodeAfter) return DecorationSet.empty;\n\n const col = map.colCount($cell.pos - start) + nodeAfter.attrs.colspan - 1;\n // A responsive table has no resizable outer-right column edge. Rendering the\n // regular handle there would extend 5px beyond the table and make the\n // overflow-auto wrapper show a horizontal scrollbar.\n if (normalizeTableWidthMode(table.attrs.widthMode) === \"responsive\" && col === map.width - 1) {\n return DecorationSet.empty;\n }\n\n for (let row = 0; row < map.height; row += 1) {\n const index = col + row * map.width;\n if (\n (col === map.width - 1 || map.map[index] !== map.map[index + 1])\n && (row === 0 || map.map[index] !== map.map[index - map.width])\n ) {\n const cellPos = map.map[index];\n const cellNode = table.nodeAt(cellPos);\n if (!cellNode) continue;\n\n const pos = start + cellPos + cellNode.nodeSize - 1;\n const dom = ownerDocument.createElement(\"div\");\n dom.className = \"column-resize-handle\";\n\n if (columnResizingPluginKey.getState(state)?.dragging) {\n decorations.push(Decoration.node(start + cellPos, start + cellPos + cellNode.nodeSize, { class: \"column-resize-dragging\" }));\n }\n\n decorations.push(Decoration.widget(pos, dom));\n }\n }\n\n return DecorationSet.create(state.doc, decorations);\n}\n\nexport function dynamicColumnResizing({\n handleWidth = 5,\n cellMinWidth = MIN_RESIZED_TABLE_COLUMN_WIDTH,\n defaultCellMinWidth = DEFAULT_TABLE_COLUMN_WIDTH,\n View = UEditorTableView,\n lastColumnResizable = true,\n}: ColumnResizingOptions = {}) {\n let ownerDocument: Document | null = null;\n const plugin = new Plugin({\n key: columnResizingPluginKey,\n state: {\n init(_, state) {\n const nodeViews = plugin.spec.props?.nodeViews as Record<string, (node: ProseMirrorNode, view: EditorView) => NodeView> | undefined;\n const tableName = tableNodeTypes(state.schema).table.name;\n if (View && nodeViews) {\n nodeViews[tableName] = (node, view) => {\n ownerDocument = view.dom.ownerDocument;\n return new View(node, defaultCellMinWidth, view);\n };\n }\n return new ResizeState(-1, false);\n },\n apply(tr, prev: ResizeState) {\n return prev.apply(tr);\n },\n },\n props: {\n attributes: (state): Record<string, string> => {\n const pluginState = columnResizingPluginKey.getState(state);\n return pluginState && pluginState.activeHandle > -1 ? { class: \"resize-cursor\" } : {};\n },\n handleDOMEvents: {\n mousemove: (view, event) => {\n handleMouseMove(view, event as MouseEvent, handleWidth, lastColumnResizable);\n },\n mouseleave: (view) => {\n handleMouseLeave(view);\n },\n mousedown: (view, event) => handleMouseDown(view, event as MouseEvent, cellMinWidth),\n },\n decorations: (state) => {\n const pluginState = columnResizingPluginKey.getState(state);\n if (pluginState && pluginState.activeHandle > -1) {\n return handleDecorations(state, pluginState.activeHandle, ownerDocument);\n }\n return undefined;\n },\n nodeViews: {},\n },\n });\n\n return plugin;\n}\n","import OrderedMap from 'orderedmap';\n\nfunction findDiffStart(a, b, pos) {\n for (let i = 0;; i++) {\n if (i == a.childCount || i == b.childCount)\n return a.childCount == b.childCount ? null : pos;\n let childA = a.child(i), childB = b.child(i);\n if (childA == childB) {\n pos += childA.nodeSize;\n continue;\n }\n if (!childA.sameMarkup(childB))\n return pos;\n if (childA.isText && childA.text != childB.text) {\n let tA = childA.text, tB = childB.text, j = 0;\n for (; tA[j] == tB[j]; j++)\n pos++;\n if (j && j < tA.length && j < tB.length && surrogateHigh(tA.charCodeAt(j - 1)) && surrogateLow(tA.charCodeAt(j)))\n pos--;\n return pos;\n }\n if (childA.content.size || childB.content.size) {\n let inner = findDiffStart(childA.content, childB.content, pos + 1);\n if (inner != null)\n return inner;\n }\n pos += childA.nodeSize;\n }\n}\nfunction findDiffEnd(a, b, posA, posB) {\n for (let iA = a.childCount, iB = b.childCount;;) {\n if (iA == 0 || iB == 0)\n return iA == iB ? null : { a: posA, b: posB };\n let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize;\n if (childA == childB) {\n posA -= size;\n posB -= size;\n continue;\n }\n if (!childA.sameMarkup(childB))\n return { a: posA, b: posB };\n if (childA.isText && childA.text != childB.text) {\n let tA = childA.text, tB = childB.text, iA = tA.length, iB = tB.length;\n while (iA > 0 && iB > 0 && tA[iA - 1] == tB[iB - 1]) {\n iA--;\n iB--;\n posA--;\n posB--;\n }\n if (iA && iB && iA < tA.length && surrogateHigh(tA.charCodeAt(iA - 1)) && surrogateLow(tA.charCodeAt(iA))) {\n posA++;\n posB++;\n }\n return { a: posA, b: posB };\n }\n if (childA.content.size || childB.content.size) {\n let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);\n if (inner)\n return inner;\n }\n posA -= size;\n posB -= size;\n }\n}\nfunction surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; }\nfunction surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; }\n\n/**\nA fragment represents a node's collection of child nodes.\n\nLike nodes, fragments are persistent data structures, and you\nshould not mutate them or their content. Rather, you create new\ninstances whenever needed. The API tries to make this easy.\n*/\nclass Fragment {\n /**\n @internal\n */\n constructor(\n /**\n The child nodes in this fragment.\n */\n content, size) {\n this.content = content;\n this.size = size || 0;\n if (size == null)\n for (let i = 0; i < content.length; i++)\n this.size += content[i].nodeSize;\n }\n /**\n Invoke a callback for all descendant nodes between the given two\n positions (relative to start of this fragment). Doesn't descend\n into a node when the callback returns `false`.\n */\n nodesBetween(from, to, f, nodeStart = 0, parent) {\n for (let i = 0, pos = 0; pos < to; i++) {\n let child = this.content[i], end = pos + child.nodeSize;\n if (end > from && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) {\n let start = pos + 1;\n child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start);\n }\n pos = end;\n }\n }\n /**\n Call the given callback for every descendant node. `pos` will be\n relative to the start of the fragment. The callback may return\n `false` to prevent traversal of a given node's children.\n */\n descendants(f) {\n this.nodesBetween(0, this.size, f);\n }\n /**\n Extract the text between `from` and `to`. See the same method on\n [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).\n */\n textBetween(from, to, blockSeparator, leafText) {\n let text = \"\", first = true;\n this.nodesBetween(from, to, (node, pos) => {\n let nodeText = node.isText ? node.text.slice(Math.max(from, pos) - pos, to - pos)\n : !node.isLeaf ? \"\"\n : leafText ? (typeof leafText === \"function\" ? leafText(node) : leafText)\n : node.type.spec.leafText ? node.type.spec.leafText(node)\n : \"\";\n if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) {\n if (first)\n first = false;\n else\n text += blockSeparator;\n }\n text += nodeText;\n }, 0);\n return text;\n }\n /**\n Create a new fragment containing the combined content of this\n fragment and the other.\n */\n append(other) {\n if (!other.size)\n return this;\n if (!this.size)\n return other;\n let last = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0;\n if (last.isText && last.sameMarkup(first)) {\n content[content.length - 1] = last.withText(last.text + first.text);\n i = 1;\n }\n for (; i < other.content.length; i++)\n content.push(other.content[i]);\n return new Fragment(content, this.size + other.size);\n }\n /**\n Cut out the sub-fragment between the two given positions.\n */\n cut(from, to = this.size) {\n if (from == 0 && to == this.size)\n return this;\n let result = [], size = 0;\n if (to > from)\n for (let i = 0, pos = 0; pos < to; i++) {\n let child = this.content[i], end = pos + child.nodeSize;\n if (end > from) {\n if (pos < from || end > to) {\n if (child.isText)\n child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos));\n else\n child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1));\n }\n result.push(child);\n size += child.nodeSize;\n }\n pos = end;\n }\n return new Fragment(result, size);\n }\n /**\n @internal\n */\n cutByIndex(from, to) {\n if (from == to)\n return Fragment.empty;\n if (from == 0 && to == this.content.length)\n return this;\n return new Fragment(this.content.slice(from, to));\n }\n /**\n Create a new fragment in which the node at the given index is\n replaced by the given node.\n */\n replaceChild(index, node) {\n let current = this.content[index];\n if (current == node)\n return this;\n let copy = this.content.slice();\n let size = this.size + node.nodeSize - current.nodeSize;\n copy[index] = node;\n return new Fragment(copy, size);\n }\n /**\n Create a new fragment by prepending the given node to this\n fragment.\n */\n addToStart(node) {\n return new Fragment([node].concat(this.content), this.size + node.nodeSize);\n }\n /**\n Create a new fragment by appending the given node to this\n fragment.\n */\n addToEnd(node) {\n return new Fragment(this.content.concat(node), this.size + node.nodeSize);\n }\n /**\n Compare this fragment to another one.\n */\n eq(other) {\n if (this.content.length != other.content.length)\n return false;\n for (let i = 0; i < this.content.length; i++)\n if (!this.content[i].eq(other.content[i]))\n return false;\n return true;\n }\n /**\n The first child of the fragment, or `null` if it is empty.\n */\n get firstChild() { return this.content.length ? this.content[0] : null; }\n /**\n The last child of the fragment, or `null` if it is empty.\n */\n get lastChild() { return this.content.length ? this.content[this.content.length - 1] : null; }\n /**\n The number of child nodes in this fragment.\n */\n get childCount() { return this.content.length; }\n /**\n Get the child node at the given index. Raise an error when the\n index is out of range.\n */\n child(index) {\n let found = this.content[index];\n if (!found)\n throw new RangeError(\"Index \" + index + \" out of range for \" + this);\n return found;\n }\n /**\n Get the child node at the given index, if it exists.\n */\n maybeChild(index) {\n return this.content[index] || null;\n }\n /**\n Call `f` for every child node, passing the node, its offset\n into this parent node, and its index.\n */\n forEach(f) {\n for (let i = 0, p = 0; i < this.content.length; i++) {\n let child = this.content[i];\n f(child, p, i);\n p += child.nodeSize;\n }\n }\n /**\n Find the first position at which this fragment and another\n fragment differ, or `null` if they are the same.\n */\n findDiffStart(other, pos = 0) {\n return findDiffStart(this, other, pos);\n }\n /**\n Find the first position, searching from the end, at which this\n fragment and the given fragment differ, or `null` if they are\n the same. Since this position will not be the same in both\n nodes, an object with two separate positions is returned.\n */\n findDiffEnd(other, pos = this.size, otherPos = other.size) {\n return findDiffEnd(this, other, pos, otherPos);\n }\n /**\n Find the index and inner offset corresponding to a given relative\n position in this fragment. The result object will be reused\n (overwritten) the next time the function is called. @internal\n */\n findIndex(pos) {\n if (pos == 0)\n return retIndex(0, pos);\n if (pos == this.size)\n return retIndex(this.content.length, pos);\n if (pos > this.size || pos < 0)\n throw new RangeError(`Position ${pos} outside of fragment (${this})`);\n for (let i = 0, curPos = 0;; i++) {\n let cur = this.child(i), end = curPos + cur.nodeSize;\n if (end >= pos) {\n if (end == pos)\n return retIndex(i + 1, end);\n return retIndex(i, curPos);\n }\n curPos = end;\n }\n }\n /**\n Return a debugging string that describes this fragment.\n */\n toString() { return \"<\" + this.toStringInner() + \">\"; }\n /**\n @internal\n */\n toStringInner() { return this.content.join(\", \"); }\n /**\n Create a JSON-serializeable representation of this fragment.\n */\n toJSON() {\n return this.content.length ? this.content.map(n => n.toJSON()) : null;\n }\n /**\n Deserialize a fragment from its JSON representation.\n */\n static fromJSON(schema, value) {\n if (!value)\n return Fragment.empty;\n if (!Array.isArray(value))\n throw new RangeError(\"Invalid input for Fragment.fromJSON\");\n return Fragment.fromArray(value.map(schema.nodeFromJSON));\n }\n /**\n Build a fragment from an array of nodes. Ensures that adjacent\n text nodes with the same marks are joined together.\n */\n static fromArray(array) {\n if (!array.length)\n return Fragment.empty;\n let joined, size = 0;\n for (let i = 0; i < array.length; i++) {\n let node = array[i];\n size += node.nodeSize;\n if (i && node.isText && array[i - 1].sameMarkup(node)) {\n if (!joined)\n joined = array.slice(0, i);\n joined[joined.length - 1] = node\n .withText(joined[joined.length - 1].text + node.text);\n }\n else if (joined) {\n joined.push(node);\n }\n }\n return new Fragment(joined || array, size);\n }\n /**\n Create a fragment from something that can be interpreted as a\n set of nodes. For `null`, it returns the empty fragment. For a\n fragment, the fragment itself. For a node or array of nodes, a\n fragment containing those nodes.\n */\n static from(nodes) {\n if (!nodes)\n return Fragment.empty;\n if (nodes instanceof Fragment)\n return nodes;\n if (Array.isArray(nodes))\n return this.fromArray(nodes);\n if (nodes.attrs)\n return new Fragment([nodes], nodes.nodeSize);\n throw new RangeError(\"Can not convert \" + nodes + \" to a Fragment\" +\n (nodes.nodesBetween ? \" (looks like multiple versions of prosemirror-model were loaded)\" : \"\"));\n }\n}\n/**\nAn empty fragment. Intended to be reused whenever a node doesn't\ncontain anything (rather than allocating a new empty fragment for\neach leaf node).\n*/\nFragment.empty = new Fragment([], 0);\nconst found = { index: 0, offset: 0 };\nfunction retIndex(index, offset) {\n found.index = index;\n found.offset = offset;\n return found;\n}\n\nfunction compareDeep(a, b) {\n if (a === b)\n return true;\n if (!(a && typeof a == \"object\") ||\n !(b && typeof b == \"object\"))\n return false;\n let array = Array.isArray(a);\n if (Array.isArray(b) != array)\n return false;\n if (array) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!compareDeep(a[i], b[i]))\n return false;\n }\n else {\n for (let p in a)\n if (!(p in b) || !compareDeep(a[p], b[p]))\n return false;\n for (let p in b)\n if (!(p in a))\n return false;\n }\n return true;\n}\n\n/**\nA mark is a piece of information that can be attached to a node,\nsuch as it being emphasized, in code font, or a link. It has a\ntype and optionally a set of attributes that provide further\ninformation (such as the target of the link). Marks are created\nthrough a `Schema`, which controls which types exist and which\nattributes they have.\n*/\nclass Mark {\n /**\n @internal\n */\n constructor(\n /**\n The type of this mark.\n */\n type, \n /**\n The attributes associated with this mark.\n */\n attrs) {\n this.type = type;\n this.attrs = attrs;\n }\n /**\n Given a set of marks, create a new set which contains this one as\n well, in the right position. If this mark is already in the set,\n the set itself is returned. If any marks that are set to be\n [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,\n those are replaced by this one.\n */\n addToSet(set) {\n let copy, placed = false;\n for (let i = 0; i < set.length; i++) {\n let other = set[i];\n if (this.eq(other))\n return set;\n if (this.type.excludes(other.type)) {\n if (!copy)\n copy = set.slice(0, i);\n }\n else if (other.type.excludes(this.type)) {\n return set;\n }\n else {\n if (!placed && other.type.rank > this.type.rank) {\n if (!copy)\n copy = set.slice(0, i);\n copy.push(this);\n placed = true;\n }\n if (copy)\n copy.push(other);\n }\n }\n if (!copy)\n copy = set.slice();\n if (!placed)\n copy.push(this);\n return copy;\n }\n /**\n Remove this mark from the given set, returning a new set. If this\n mark is not in the set, the set itself is returned.\n */\n removeFromSet(set) {\n for (let i = 0; i < set.length; i++)\n if (this.eq(set[i]))\n return set.slice(0, i).concat(set.slice(i + 1));\n return set;\n }\n /**\n Test whether this mark is in the given set of marks.\n */\n isInSet(set) {\n for (let i = 0; i < set.length; i++)\n if (this.eq(set[i]))\n return true;\n return false;\n }\n /**\n Test whether this mark has the same type and attributes as\n another mark.\n */\n eq(other) {\n return this == other ||\n (this.type == other.type && compareDeep(this.attrs, other.attrs));\n }\n /**\n Convert this mark to a JSON-serializeable representation.\n */\n toJSON() {\n let obj = { type: this.type.name };\n for (let _ in this.attrs) {\n obj.attrs = this.attrs;\n break;\n }\n return obj;\n }\n /**\n Deserialize a mark from JSON.\n */\n static fromJSON(schema, json) {\n if (!json)\n throw new RangeError(\"Invalid input for Mark.fromJSON\");\n let type = schema.marks[json.type];\n if (!type)\n throw new RangeError(`There is no mark type ${json.type} in this schema`);\n let mark = type.create(json.attrs);\n type.checkAttrs(mark.attrs);\n return mark;\n }\n /**\n Test whether two sets of marks are identical.\n */\n static sameSet(a, b) {\n if (a == b)\n return true;\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!a[i].eq(b[i]))\n return false;\n return true;\n }\n /**\n Create a properly sorted mark set from null, a single mark, or an\n unsorted array of marks.\n */\n static setFrom(marks) {\n if (!marks || Array.isArray(marks) && marks.length == 0)\n return Mark.none;\n if (marks instanceof Mark)\n return [marks];\n let copy = marks.slice();\n copy.sort((a, b) => a.type.rank - b.type.rank);\n return copy;\n }\n}\n/**\nThe empty set of marks.\n*/\nMark.none = [];\n\n/**\nError type raised by [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) when\ngiven an invalid replacement.\n*/\nclass ReplaceError extends Error {\n}\n/**\nA slice represents a piece cut out of a larger document. It\nstores not only a fragment, but also the depth up to which nodes on\nboth side are ‘open’ (cut through).\n*/\nclass Slice {\n /**\n Create a slice. When specifying a non-zero open depth, you must\n make sure that there are nodes of at least that depth at the\n appropriate side of the fragment—i.e. if the fragment is an\n empty paragraph node, `openStart` and `openEnd` can't be greater\n than 1.\n \n It is not necessary for the content of open nodes to conform to\n the schema's content constraints, though it should be a valid\n start/end/middle for such a node, depending on which sides are\n open.\n */\n constructor(\n /**\n The slice's content.\n */\n content, \n /**\n The open depth at the start of the fragment.\n */\n openStart, \n /**\n The open depth at the end.\n */\n openEnd) {\n this.content = content;\n this.openStart = openStart;\n this.openEnd = openEnd;\n }\n /**\n The size this slice would add when inserted into a document.\n */\n get size() {\n return this.content.size - this.openStart - this.openEnd;\n }\n /**\n @internal\n */\n insertAt(pos, fragment) {\n let content = insertInto(this.content, pos + this.openStart, fragment, this.openStart + 1, this.openEnd + 1);\n return content && new Slice(content, this.openStart, this.openEnd);\n }\n /**\n @internal\n */\n removeBetween(from, to) {\n return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd);\n }\n /**\n Tests whether this slice is equal to another slice.\n */\n eq(other) {\n return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;\n }\n /**\n @internal\n */\n toString() {\n return this.content + \"(\" + this.openStart + \",\" + this.openEnd + \")\";\n }\n /**\n Convert a slice to a JSON-serializable representation.\n */\n toJSON() {\n if (!this.content.size)\n return null;\n let json = { content: this.content.toJSON() };\n if (this.openStart > 0)\n json.openStart = this.openStart;\n if (this.openEnd > 0)\n json.openEnd = this.openEnd;\n return json;\n }\n /**\n Deserialize a slice from its JSON representation.\n */\n static fromJSON(schema, json) {\n if (!json)\n return Slice.empty;\n let openStart = json.openStart || 0, openEnd = json.openEnd || 0;\n if (typeof openStart != \"number\" || typeof openEnd != \"number\")\n throw new RangeError(\"Invalid input for Slice.fromJSON\");\n return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd);\n }\n /**\n Create a slice from a fragment by taking the maximum possible\n open value on both side of the fragment.\n */\n static maxOpen(fragment, openIsolating = true) {\n let openStart = 0, openEnd = 0;\n for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild)\n openStart++;\n for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild)\n openEnd++;\n return new Slice(fragment, openStart, openEnd);\n }\n}\n/**\nThe empty slice.\n*/\nSlice.empty = new Slice(Fragment.empty, 0, 0);\nfunction removeRange(content, from, to) {\n let { index, offset } = content.findIndex(from), child = content.maybeChild(index);\n let { index: indexTo, offset: offsetTo } = content.findIndex(to);\n if (offset == from || child.isText) {\n if (offsetTo != to && !content.child(indexTo).isText)\n throw new RangeError(\"Removing non-flat range\");\n return content.cut(0, from).append(content.cut(to));\n }\n if (index != indexTo)\n throw new RangeError(\"Removing non-flat range\");\n return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)));\n}\nfunction insertInto(content, dist, insert, openStart, openEnd, parent) {\n let { index, offset } = content.findIndex(dist), child = content.maybeChild(index);\n if (offset == dist || child.isText) {\n if (parent && openStart <= 0 && openEnd <= 0 && !parent.canReplace(index, index, insert))\n return null;\n return content.cut(0, dist).append(insert).append(content.cut(dist));\n }\n let inner = insertInto(child.content, dist - offset - 1, insert, index == 0 ? openStart - 1 : 0, index == content.childCount - 1 ? openEnd - 1 : 0, child);\n return inner && content.replaceChild(index, child.copy(inner));\n}\nfunction replace($from, $to, slice) {\n if (slice.openStart > $from.depth)\n throw new ReplaceError(\"Inserted content deeper than insertion position\");\n if ($from.depth - slice.openStart != $to.depth - slice.openEnd)\n throw new ReplaceError(\"Inconsistent open depths\");\n return replaceOuter($from, $to, slice, 0);\n}\nfunction replaceOuter($from, $to, slice, depth) {\n let index = $from.index(depth), node = $from.node(depth);\n if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {\n let inner = replaceOuter($from, $to, slice, depth + 1);\n return node.copy(node.content.replaceChild(index, inner));\n }\n else if (!slice.content.size) {\n return close(node, replaceTwoWay($from, $to, depth));\n }\n else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { // Simple, flat case\n let parent = $from.parent, content = parent.content;\n return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)));\n }\n else {\n let { start, end } = prepareSliceForReplace(slice, $from);\n return close(node, replaceThreeWay($from, start, end, $to, depth));\n }\n}\nfunction checkJoin(main, sub) {\n if (!sub.type.compatibleContent(main.type))\n throw new ReplaceError(\"Cannot join \" + sub.type.name + \" onto \" + main.type.name);\n}\nfunction joinable($before, $after, depth) {\n let node = $before.node(depth);\n checkJoin(node, $after.node(depth));\n return node;\n}\nfunction addNode(child, target) {\n let last = target.length - 1;\n if (last >= 0 && child.isText && child.sameMarkup(target[last]))\n target[last] = child.withText(target[last].text + child.text);\n else\n target.push(child);\n}\nfunction addRange($start, $end, depth, target) {\n let node = ($end || $start).node(depth);\n let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount;\n if ($start) {\n startIndex = $start.index(depth);\n if ($start.depth > depth) {\n startIndex++;\n }\n else if ($start.textOffset) {\n addNode($start.nodeAfter, target);\n startIndex++;\n }\n }\n for (let i = startIndex; i < endIndex; i++)\n addNode(node.child(i), target);\n if ($end && $end.depth == depth && $end.textOffset)\n addNode($end.nodeBefore, target);\n}\nfunction close(node, content) {\n if (!node.type.validContent(content))\n throw new ReplaceError(\"Invalid content for node \" + node.type.name);\n return node.copy(content);\n}\nfunction replaceThreeWay($from, $start, $end, $to, depth) {\n let openStart = $from.depth > depth && joinable($from, $start, depth + 1);\n let openEnd = $to.depth > depth && joinable($end, $to, depth + 1);\n let content = [];\n addRange(null, $from, depth, content);\n if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {\n checkJoin(openStart, openEnd);\n addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);\n }\n else {\n if (openStart)\n addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);\n addRange($start, $end, depth, content);\n if (openEnd)\n addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);\n }\n addRange($to, null, depth, content);\n return new Fragment(content);\n}\nfunction replaceTwoWay($from, $to, depth) {\n let content = [];\n addRange(null, $from, depth, content);\n if ($from.depth > depth) {\n let type = joinable($from, $to, depth + 1);\n addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);\n }\n addRange($to, null, depth, content);\n return new Fragment(content);\n}\nfunction prepareSliceForReplace(slice, $along) {\n let extra = $along.depth - slice.openStart, parent = $along.node(extra);\n let node = parent.copy(slice.content);\n for (let i = extra - 1; i >= 0; i--)\n node = $along.node(i).copy(Fragment.from(node));\n return { start: node.resolveNoCache(slice.openStart + extra),\n end: node.resolveNoCache(node.content.size - slice.openEnd - extra) };\n}\n\n/**\nYou can [_resolve_](https://prosemirror.net/docs/ref/#model.Node.resolve) a position to get more\ninformation about it. Objects of this class represent such a\nresolved position, providing various pieces of context\ninformation, and some helper methods.\n\nThroughout this interface, methods that take an optional `depth`\nparameter will interpret undefined as `this.depth` and negative\nnumbers as `this.depth + value`.\n*/\nclass ResolvedPos {\n /**\n @internal\n */\n constructor(\n /**\n The position that was resolved.\n */\n pos, \n /**\n @internal\n */\n path, \n /**\n The offset this position has into its parent node.\n */\n parentOffset) {\n this.pos = pos;\n this.path = path;\n this.parentOffset = parentOffset;\n this.depth = path.length / 3 - 1;\n }\n /**\n @internal\n */\n resolveDepth(val) {\n if (val == null)\n return this.depth;\n if (val < 0)\n return this.depth + val;\n return val;\n }\n /**\n The parent node that the position points into. Note that even if\n a position points into a text node, that node is not considered\n the parent—text nodes are ‘flat’ in this model, and have no content.\n */\n get parent() { return this.node(this.depth); }\n /**\n The root node in which the position was resolved.\n */\n get doc() { return this.node(0); }\n /**\n The ancestor node at the given level. `p.node(p.depth)` is the\n same as `p.parent`.\n */\n node(depth) { return this.path[this.resolveDepth(depth) * 3]; }\n /**\n The index into the ancestor at the given level. If this points\n at the 3rd node in the 2nd paragraph on the top level, for\n example, `p.index(0)` is 1 and `p.index(1)` is 2.\n */\n index(depth) { return this.path[this.resolveDepth(depth) * 3 + 1]; }\n /**\n The index pointing after this position into the ancestor at the\n given level.\n */\n indexAfter(depth) {\n depth = this.resolveDepth(depth);\n return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);\n }\n /**\n The (absolute) position at the start of the node at the given\n level.\n */\n start(depth) {\n depth = this.resolveDepth(depth);\n return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n }\n /**\n The (absolute) position at the end of the node at the given\n level.\n */\n end(depth) {\n depth = this.resolveDepth(depth);\n return this.start(depth) + this.node(depth).content.size;\n }\n /**\n The (absolute) position directly before the wrapping node at the\n given level, or, when `depth` is `this.depth + 1`, the original\n position.\n */\n before(depth) {\n depth = this.resolveDepth(depth);\n if (!depth)\n throw new RangeError(\"There is no position before the top-level node\");\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];\n }\n /**\n The (absolute) position directly after the wrapping node at the\n given level, or the original position when `depth` is `this.depth + 1`.\n */\n after(depth) {\n depth = this.resolveDepth(depth);\n if (!depth)\n throw new RangeError(\"There is no position after the top-level node\");\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;\n }\n /**\n When this position points into a text node, this returns the\n distance between the position and the start of the text node.\n Will be zero for positions that point between nodes.\n */\n get textOffset() { return this.pos - this.path[this.path.length - 1]; }\n /**\n Get the node directly after the position, if any. If the position\n points into a text node, only the part of that node after the\n position is returned.\n */\n get nodeAfter() {\n let parent = this.parent, index = this.index(this.depth);\n if (index == parent.childCount)\n return null;\n let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index);\n return dOff ? parent.child(index).cut(dOff) : child;\n }\n /**\n Get the node directly before the position, if any. If the\n position points into a text node, only the part of that node\n before the position is returned.\n */\n get nodeBefore() {\n let index = this.index(this.depth);\n let dOff = this.pos - this.path[this.path.length - 1];\n if (dOff)\n return this.parent.child(index).cut(0, dOff);\n return index == 0 ? null : this.parent.child(index - 1);\n }\n /**\n Get the position at the given index in the parent node at the\n given depth (which defaults to `this.depth`).\n */\n posAtIndex(index, depth) {\n depth = this.resolveDepth(depth);\n let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n for (let i = 0; i < index; i++)\n pos += node.child(i).nodeSize;\n return pos;\n }\n /**\n Get the marks at this position, factoring in the surrounding\n marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the\n position is at the start of a non-empty node, the marks of the\n node after it (if any) are returned.\n */\n marks() {\n let parent = this.parent, index = this.index();\n // In an empty parent, return the empty array\n if (parent.content.size == 0)\n return Mark.none;\n // When inside a text node, just return the text node's marks\n if (this.textOffset)\n return parent.child(index).marks;\n let main = parent.maybeChild(index - 1), other = parent.maybeChild(index);\n // If the `after` flag is true of there is no node before, make\n // the node after this position the main reference.\n if (!main) {\n let tmp = main;\n main = other;\n other = tmp;\n }\n // Use all marks in the main node, except those that have\n // `inclusive` set to false and are not present in the other node.\n let marks = main.marks;\n for (var i = 0; i < marks.length; i++)\n if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks)))\n marks = marks[i--].removeFromSet(marks);\n return marks;\n }\n /**\n Get the marks after the current position, if any, except those\n that are non-inclusive and not present at position `$end`. This\n is mostly useful for getting the set of marks to preserve after a\n deletion. Will return `null` if this position is at the end of\n its parent node or its parent node isn't a textblock (in which\n case no marks should be preserved).\n */\n marksAcross($end) {\n let after = this.parent.maybeChild(this.index());\n if (!after || !after.isInline)\n return null;\n let marks = after.marks, next = $end.parent.maybeChild($end.index());\n for (var i = 0; i < marks.length; i++)\n if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks)))\n marks = marks[i--].removeFromSet(marks);\n return marks;\n }\n /**\n The depth up to which this position and the given (non-resolved)\n position share the same parent nodes.\n */\n sharedDepth(pos) {\n for (let depth = this.depth; depth > 0; depth--)\n if (this.start(depth) <= pos && this.end(depth) >= pos)\n return depth;\n return 0;\n }\n /**\n Returns a range based on the place where this position and the\n given position diverge around block content. If both point into\n the same textblock, for example, a range around that textblock\n will be returned. If they point into different blocks, the range\n around those blocks in their shared ancestor is returned. You can\n pass in an optional predicate that will be called with a parent\n node to see if a range into that parent is acceptable.\n */\n blockRange(other = this, pred) {\n if (other.pos < this.pos)\n return other.blockRange(this);\n for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--)\n if (other.pos <= this.end(d) && (!pred || pred(this.node(d))))\n return new NodeRange(this, other, d);\n return null;\n }\n /**\n Query whether the given position shares the same parent node.\n */\n sameParent(other) {\n return this.pos - this.parentOffset == other.pos - other.parentOffset;\n }\n /**\n Return the greater of this and the given position.\n */\n max(other) {\n return other.pos > this.pos ? other : this;\n }\n /**\n Return the smaller of this and the given position.\n */\n min(other) {\n return other.pos < this.pos ? other : this;\n }\n /**\n @internal\n */\n toString() {\n let str = \"\";\n for (let i = 1; i <= this.depth; i++)\n str += (str ? \"/\" : \"\") + this.node(i).type.name + \"_\" + this.index(i - 1);\n return str + \":\" + this.parentOffset;\n }\n /**\n @internal\n */\n static resolve(doc, pos) {\n if (!(pos >= 0 && pos <= doc.content.size))\n throw new RangeError(\"Position \" + pos + \" out of range\");\n let path = [];\n let start = 0, parentOffset = pos;\n for (let node = doc;;) {\n let { index, offset } = node.content.findIndex(parentOffset);\n let rem = parentOffset - offset;\n path.push(node, index, start + offset);\n if (!rem)\n break;\n node = node.child(index);\n if (node.isText)\n break;\n parentOffset = rem - 1;\n start += offset + 1;\n }\n return new ResolvedPos(pos, path, parentOffset);\n }\n /**\n @internal\n */\n static resolveCached(doc, pos) {\n let cache = resolveCache.get(doc);\n if (cache) {\n for (let i = 0; i < cache.elts.length; i++) {\n let elt = cache.elts[i];\n if (elt.pos == pos)\n return elt;\n }\n }\n else {\n resolveCache.set(doc, cache = new ResolveCache);\n }\n let result = cache.elts[cache.i] = ResolvedPos.resolve(doc, pos);\n cache.i = (cache.i + 1) % resolveCacheSize;\n return result;\n }\n}\nclass ResolveCache {\n constructor() {\n this.elts = [];\n this.i = 0;\n }\n}\nconst resolveCacheSize = 12, resolveCache = new WeakMap();\n/**\nRepresents a flat range of content, i.e. one that starts and\nends in the same node.\n*/\nclass NodeRange {\n /**\n Construct a node range. `$from` and `$to` should point into the\n same node until at least the given `depth`, since a node range\n denotes an adjacent set of nodes in a single parent node.\n */\n constructor(\n /**\n A resolved position along the start of the content. May have a\n `depth` greater than this object's `depth` property, since\n these are the positions that were used to compute the range,\n not re-resolved positions directly at its boundaries.\n */\n $from, \n /**\n A position along the end of the content. See\n caveat for [`$from`](https://prosemirror.net/docs/ref/#model.NodeRange.$from).\n */\n $to, \n /**\n The depth of the node that this range points into.\n */\n depth) {\n this.$from = $from;\n this.$to = $to;\n this.depth = depth;\n }\n /**\n The position at the start of the range.\n */\n get start() { return this.$from.before(this.depth + 1); }\n /**\n The position at the end of the range.\n */\n get end() { return this.$to.after(this.depth + 1); }\n /**\n The parent node that the range points into.\n */\n get parent() { return this.$from.node(this.depth); }\n /**\n The start index of the range in the parent node.\n */\n get startIndex() { return this.$from.index(this.depth); }\n /**\n The end index of the range in the parent node.\n */\n get endIndex() { return this.$to.indexAfter(this.depth); }\n}\n\nconst emptyAttrs = Object.create(null);\n/**\nThis class represents a node in the tree that makes up a\nProseMirror document. So a document is an instance of `Node`, with\nchildren that are also instances of `Node`.\n\nNodes are persistent data structures. Instead of changing them, you\ncreate new ones with the content you want. Old ones keep pointing\nat the old document shape. This is made cheaper by sharing\nstructure between the old and new data as much as possible, which a\ntree shape like this (without back pointers) makes easy.\n\n**Do not** directly mutate the properties of a `Node` object. See\n[the guide](https://prosemirror.net/docs/guide/#doc) for more information.\n*/\nclass Node {\n /**\n @internal\n */\n constructor(\n /**\n The type of node that this is.\n */\n type, \n /**\n An object mapping attribute names to values. The kind of\n attributes allowed and required are\n [determined](https://prosemirror.net/docs/ref/#model.NodeSpec.attrs) by the node type.\n */\n attrs, \n // A fragment holding the node's children.\n content, \n /**\n The marks (things like whether it is emphasized or part of a\n link) applied to this node.\n */\n marks = Mark.none) {\n this.type = type;\n this.attrs = attrs;\n this.marks = marks;\n this.content = content || Fragment.empty;\n }\n /**\n The array of this node's child nodes.\n */\n get children() { return this.content.content; }\n /**\n The size of this node, as defined by the integer-based [indexing\n scheme](https://prosemirror.net/docs/guide/#doc.indexing). For text nodes, this is the\n amount of characters. For other leaf nodes, it is one. For\n non-leaf nodes, it is the size of the content plus two (the\n start and end token).\n */\n get nodeSize() { return this.isLeaf ? 1 : 2 + this.content.size; }\n /**\n The number of children that the node has.\n */\n get childCount() { return this.content.childCount; }\n /**\n Get the child node at the given index. Raises an error when the\n index is out of range.\n */\n child(index) { return this.content.child(index); }\n /**\n Get the child node at the given index, if it exists.\n */\n maybeChild(index) { return this.content.maybeChild(index); }\n /**\n Call `f` for every child node, passing the node, its offset\n into this parent node, and its index.\n */\n forEach(f) { this.content.forEach(f); }\n /**\n Invoke a callback for all descendant nodes recursively overlapping\n the given two positions that are relative to start of this\n node's content. This includes all ancestors of the nodes\n containing the two positions. The callback is invoked with the\n node, its position relative to the original node (method receiver),\n its parent node, and its child index. When the callback returns\n false for a given node, that node's children will not be\n recursed over. The last parameter can be used to specify a\n starting position to count from.\n */\n nodesBetween(from, to, f, startPos = 0) {\n this.content.nodesBetween(from, to, f, startPos, this);\n }\n /**\n Call the given callback for every descendant node. Doesn't\n descend into a node when the callback returns `false`.\n */\n descendants(f) {\n this.nodesBetween(0, this.content.size, f);\n }\n /**\n Concatenates all the text nodes found in this fragment and its\n children.\n */\n get textContent() {\n return (this.isLeaf && this.type.spec.leafText)\n ? this.type.spec.leafText(this)\n : this.textBetween(0, this.content.size, \"\");\n }\n /**\n Get all text between positions `from` and `to`. When\n `blockSeparator` is given, it will be inserted to separate text\n from different block nodes. If `leafText` is given, it'll be\n inserted for every non-text leaf node encountered, otherwise\n [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec.leafText) will be used.\n */\n textBetween(from, to, blockSeparator, leafText) {\n return this.content.textBetween(from, to, blockSeparator, leafText);\n }\n /**\n Returns this node's first child, or `null` if there are no\n children.\n */\n get firstChild() { return this.content.firstChild; }\n /**\n Returns this node's last child, or `null` if there are no\n children.\n */\n get lastChild() { return this.content.lastChild; }\n /**\n Test whether two nodes represent the same piece of document.\n */\n eq(other) {\n return this == other || (this.sameMarkup(other) && this.content.eq(other.content));\n }\n /**\n Compare the markup (type, attributes, and marks) of this node to\n those of another. Returns `true` if both have the same markup.\n */\n sameMarkup(other) {\n return this.hasMarkup(other.type, other.attrs, other.marks);\n }\n /**\n Check whether this node's markup correspond to the given type,\n attributes, and marks.\n */\n hasMarkup(type, attrs, marks) {\n return this.type == type &&\n compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) &&\n Mark.sameSet(this.marks, marks || Mark.none);\n }\n /**\n Create a new node with the same markup as this node, containing\n the given content (or empty, if no content is given).\n */\n copy(content = null) {\n if (content == this.content)\n return this;\n return new Node(this.type, this.attrs, content, this.marks);\n }\n /**\n Create a copy of this node, with the given set of marks instead\n of the node's own marks.\n */\n mark(marks) {\n return marks == this.marks ? this : new Node(this.type, this.attrs, this.content, marks);\n }\n /**\n Create a copy of this node with only the content between the\n given positions. If `to` is not given, it defaults to the end of\n the node.\n */\n cut(from, to = this.content.size) {\n if (from == 0 && to == this.content.size)\n return this;\n return this.copy(this.content.cut(from, to));\n }\n /**\n Cut out the part of the document between the given positions, and\n return it as a `Slice` object.\n */\n slice(from, to = this.content.size, includeParents = false) {\n if (from == to)\n return Slice.empty;\n let $from = this.resolve(from), $to = this.resolve(to);\n let depth = includeParents ? 0 : $from.sharedDepth(to);\n let start = $from.start(depth), node = $from.node(depth);\n let content = node.content.cut($from.pos - start, $to.pos - start);\n return new Slice(content, $from.depth - depth, $to.depth - depth);\n }\n /**\n Replace the part of the document between the given positions with\n the given slice. The slice must 'fit', meaning its open sides\n must be able to connect to the surrounding content, and its\n content nodes must be valid children for the node they are placed\n into. If any of this is violated, an error of type\n [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.\n */\n replace(from, to, slice) {\n return replace(this.resolve(from), this.resolve(to), slice);\n }\n /**\n Find the node directly after the given position.\n */\n nodeAt(pos) {\n for (let node = this;;) {\n let { index, offset } = node.content.findIndex(pos);\n node = node.maybeChild(index);\n if (!node)\n return null;\n if (offset == pos || node.isText)\n return node;\n pos -= offset + 1;\n }\n }\n /**\n Find the (direct) child node after the given offset, if any,\n and return it along with its index and offset relative to this\n node.\n */\n childAfter(pos) {\n let { index, offset } = this.content.findIndex(pos);\n return { node: this.content.maybeChild(index), index, offset };\n }\n /**\n Find the (direct) child node before the given offset, if any,\n and return it along with its index and offset relative to this\n node.\n */\n childBefore(pos) {\n if (pos == 0)\n return { node: null, index: 0, offset: 0 };\n let { index, offset } = this.content.findIndex(pos);\n if (offset < pos)\n return { node: this.content.child(index), index, offset };\n let node = this.content.child(index - 1);\n return { node, index: index - 1, offset: offset - node.nodeSize };\n }\n /**\n Resolve the given position in the document, returning an\n [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.\n */\n resolve(pos) { return ResolvedPos.resolveCached(this, pos); }\n /**\n @internal\n */\n resolveNoCache(pos) { return ResolvedPos.resolve(this, pos); }\n /**\n Test whether a given mark or mark type occurs in this document\n between the two given positions.\n */\n rangeHasMark(from, to, type) {\n let found = false;\n if (to > from)\n this.nodesBetween(from, to, node => {\n if (type.isInSet(node.marks))\n found = true;\n return !found;\n });\n return found;\n }\n /**\n True when this is a block (non-inline node)\n */\n get isBlock() { return this.type.isBlock; }\n /**\n True when this is a textblock node, a block node with inline\n content.\n */\n get isTextblock() { return this.type.isTextblock; }\n /**\n True when this node allows inline content.\n */\n get inlineContent() { return this.type.inlineContent; }\n /**\n True when this is an inline node (a text node or a node that can\n appear among text).\n */\n get isInline() { return this.type.isInline; }\n /**\n True when this is a text node.\n */\n get isText() { return this.type.isText; }\n /**\n True when this is a leaf node.\n */\n get isLeaf() { return this.type.isLeaf; }\n /**\n True when this is an atom, i.e. when it does not have directly\n editable content. This is usually the same as `isLeaf`, but can\n be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)\n on a node's spec (typically used when the node is displayed as\n an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).\n */\n get isAtom() { return this.type.isAtom; }\n /**\n Return a string representation of this node for debugging\n purposes.\n */\n toString() {\n if (this.type.spec.toDebugString)\n return this.type.spec.toDebugString(this);\n let name = this.type.name;\n if (this.content.size)\n name += \"(\" + this.content.toStringInner() + \")\";\n return wrapMarks(this.marks, name);\n }\n /**\n Get the content match in this node at the given index.\n */\n contentMatchAt(index) {\n let match = this.type.contentMatch.matchFragment(this.content, 0, index);\n if (!match)\n throw new Error(\"Called contentMatchAt on a node with invalid content\");\n return match;\n }\n /**\n Test whether replacing the range between `from` and `to` (by\n child index) with the given replacement fragment (which defaults\n to the empty fragment) would leave the node's content valid. You\n can optionally pass `start` and `end` indices into the\n replacement fragment.\n */\n canReplace(from, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) {\n let one = this.contentMatchAt(from).matchFragment(replacement, start, end);\n let two = one && one.matchFragment(this.content, to);\n if (!two || !two.validEnd)\n return false;\n for (let i = start; i < end; i++)\n if (!this.type.allowsMarks(replacement.child(i).marks))\n return false;\n return true;\n }\n /**\n Test whether replacing the range `from` to `to` (by index) with\n a node of the given type would leave the node's content valid.\n */\n canReplaceWith(from, to, type, marks) {\n if (marks && !this.type.allowsMarks(marks))\n return false;\n let start = this.contentMatchAt(from).matchType(type);\n let end = start && start.matchFragment(this.content, to);\n return end ? end.validEnd : false;\n }\n /**\n Test whether the given node's content could be appended to this\n node. If that node is empty, this will only return true if there\n is at least one node type that can appear in both nodes (to avoid\n merging completely incompatible nodes).\n */\n canAppend(other) {\n if (other.content.size)\n return this.canReplace(this.childCount, this.childCount, other.content);\n else\n return this.type.compatibleContent(other.type);\n }\n /**\n Check whether this node and its descendants conform to the\n schema, and raise an exception when they do not.\n */\n check() {\n this.type.checkContent(this.content);\n this.type.checkAttrs(this.attrs);\n let copy = Mark.none;\n for (let i = 0; i < this.marks.length; i++) {\n let mark = this.marks[i];\n mark.type.checkAttrs(mark.attrs);\n copy = mark.addToSet(copy);\n }\n if (!Mark.sameSet(copy, this.marks))\n throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(m => m.type.name)}`);\n this.content.forEach(node => node.check());\n }\n /**\n Return a JSON-serializeable representation of this node.\n */\n toJSON() {\n let obj = { type: this.type.name };\n for (let _ in this.attrs) {\n obj.attrs = this.attrs;\n break;\n }\n if (this.content.size)\n obj.content = this.content.toJSON();\n if (this.marks.length)\n obj.marks = this.marks.map(n => n.toJSON());\n return obj;\n }\n /**\n Deserialize a node from its JSON representation.\n */\n static fromJSON(schema, json) {\n if (!json)\n throw new RangeError(\"Invalid input for Node.fromJSON\");\n let marks = undefined;\n if (json.marks) {\n if (!Array.isArray(json.marks))\n throw new RangeError(\"Invalid mark data for Node.fromJSON\");\n marks = json.marks.map(schema.markFromJSON);\n }\n if (json.type == \"text\") {\n if (typeof json.text != \"string\")\n throw new RangeError(\"Invalid text node in JSON\");\n return schema.text(json.text, marks);\n }\n let content = Fragment.fromJSON(schema, json.content);\n let node = schema.nodeType(json.type).create(json.attrs, content, marks);\n node.type.checkAttrs(node.attrs);\n return node;\n }\n}\nNode.prototype.text = undefined;\nclass TextNode extends Node {\n /**\n @internal\n */\n constructor(type, attrs, content, marks) {\n super(type, attrs, null, marks);\n if (!content)\n throw new RangeError(\"Empty text nodes are not allowed\");\n this.text = content;\n }\n toString() {\n if (this.type.spec.toDebugString)\n return this.type.spec.toDebugString(this);\n return wrapMarks(this.marks, JSON.stringify(this.text));\n }\n get textContent() { return this.text; }\n textBetween(from, to) { return this.text.slice(from, to); }\n get nodeSize() { return this.text.length; }\n mark(marks) {\n return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks);\n }\n withText(text) {\n if (text == this.text)\n return this;\n return new TextNode(this.type, this.attrs, text, this.marks);\n }\n cut(from = 0, to = this.text.length) {\n if (from == 0 && to == this.text.length)\n return this;\n return this.withText(this.text.slice(from, to));\n }\n eq(other) {\n return this.sameMarkup(other) && this.text == other.text;\n }\n toJSON() {\n let base = super.toJSON();\n base.text = this.text;\n return base;\n }\n}\nfunction wrapMarks(marks, str) {\n for (let i = marks.length - 1; i >= 0; i--)\n str = marks[i].type.name + \"(\" + str + \")\";\n return str;\n}\n\n/**\nInstances of this class represent a match state of a node type's\n[content expression](https://prosemirror.net/docs/ref/#model.NodeSpec.content), and can be used to\nfind out whether further content matches here, and whether a given\nposition is a valid end of the node.\n*/\nclass ContentMatch {\n /**\n @internal\n */\n constructor(\n /**\n True when this match state represents a valid end of the node.\n */\n validEnd) {\n this.validEnd = validEnd;\n /**\n @internal\n */\n this.next = [];\n /**\n @internal\n */\n this.wrapCache = [];\n }\n /**\n @internal\n */\n static parse(string, nodeTypes) {\n let stream = new TokenStream(string, nodeTypes);\n if (stream.next == null)\n return ContentMatch.empty;\n let expr = parseExpr(stream);\n if (stream.next)\n stream.err(\"Unexpected trailing text\");\n let match = dfa(nfa(expr));\n checkForDeadEnds(match, stream);\n return match;\n }\n /**\n Match a node type, returning a match after that node if\n successful.\n */\n matchType(type) {\n for (let i = 0; i < this.next.length; i++)\n if (this.next[i].type == type)\n return this.next[i].next;\n return null;\n }\n /**\n Try to match a fragment. Returns the resulting match when\n successful.\n */\n matchFragment(frag, start = 0, end = frag.childCount) {\n let cur = this;\n for (let i = start; cur && i < end; i++)\n cur = cur.matchType(frag.child(i).type);\n return cur;\n }\n /**\n @internal\n */\n get inlineContent() {\n return this.next.length != 0 && this.next[0].type.isInline;\n }\n /**\n Get the first matching node type at this match position that can\n be generated.\n */\n get defaultType() {\n for (let i = 0; i < this.next.length; i++) {\n let { type } = this.next[i];\n if (!(type.isText || type.hasRequiredAttrs()))\n return type;\n }\n return null;\n }\n /**\n @internal\n */\n compatible(other) {\n for (let i = 0; i < this.next.length; i++)\n for (let j = 0; j < other.next.length; j++)\n if (this.next[i].type == other.next[j].type)\n return true;\n return false;\n }\n /**\n Try to match the given fragment, and if that fails, see if it can\n be made to match by inserting nodes in front of it. When\n successful, return a fragment of inserted nodes (which may be\n empty if nothing had to be inserted). When `toEnd` is true, only\n return a fragment if the resulting match goes to the end of the\n content expression.\n */\n fillBefore(after, toEnd = false, startIndex = 0) {\n let seen = [this];\n function search(match, types) {\n let finished = match.matchFragment(after, startIndex);\n if (finished && (!toEnd || finished.validEnd))\n return Fragment.from(types.map(tp => tp.createAndFill()));\n for (let i = 0; i < match.next.length; i++) {\n let { type, next } = match.next[i];\n if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {\n seen.push(next);\n let found = search(next, types.concat(type));\n if (found)\n return found;\n }\n }\n return null;\n }\n return search(this, []);\n }\n /**\n Find a set of wrapping node types that would allow a node of the\n given type to appear at this position. The result may be empty\n (when it fits directly) and will be null when no such wrapping\n exists.\n */\n findWrapping(target) {\n for (let i = 0; i < this.wrapCache.length; i += 2)\n if (this.wrapCache[i] == target)\n return this.wrapCache[i + 1];\n let computed = this.computeWrapping(target);\n this.wrapCache.push(target, computed);\n return computed;\n }\n /**\n @internal\n */\n computeWrapping(target) {\n let seen = Object.create(null), active = [{ match: this, type: null, via: null }];\n while (active.length) {\n let current = active.shift(), match = current.match;\n if (match.matchType(target)) {\n let result = [];\n for (let obj = current; obj.type; obj = obj.via)\n result.push(obj.type);\n return result.reverse();\n }\n for (let i = 0; i < match.next.length; i++) {\n let { type, next } = match.next[i];\n if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) {\n active.push({ match: type.contentMatch, type, via: current });\n seen[type.name] = true;\n }\n }\n }\n return null;\n }\n /**\n The number of outgoing edges this node has in the finite\n automaton that describes the content expression.\n */\n get edgeCount() {\n return this.next.length;\n }\n /**\n Get the _n_​th outgoing edge from this node in the finite\n automaton that describes the content expression.\n */\n edge(n) {\n if (n >= this.next.length)\n throw new RangeError(`There's no ${n}th edge in this content match`);\n return this.next[n];\n }\n /**\n @internal\n */\n toString() {\n let seen = [];\n function scan(m) {\n seen.push(m);\n for (let i = 0; i < m.next.length; i++)\n if (seen.indexOf(m.next[i].next) == -1)\n scan(m.next[i].next);\n }\n scan(this);\n return seen.map((m, i) => {\n let out = i + (m.validEnd ? \"*\" : \" \") + \" \";\n for (let i = 0; i < m.next.length; i++)\n out += (i ? \", \" : \"\") + m.next[i].type.name + \"->\" + seen.indexOf(m.next[i].next);\n return out;\n }).join(\"\\n\");\n }\n}\n/**\n@internal\n*/\nContentMatch.empty = new ContentMatch(true);\nclass TokenStream {\n constructor(string, nodeTypes) {\n this.string = string;\n this.nodeTypes = nodeTypes;\n this.inline = null;\n this.pos = 0;\n this.tokens = string.split(/\\s*(?=\\b|\\W|$)/);\n if (this.tokens[this.tokens.length - 1] == \"\")\n this.tokens.pop();\n if (this.tokens[0] == \"\")\n this.tokens.shift();\n }\n get next() { return this.tokens[this.pos]; }\n eat(tok) { return this.next == tok && (this.pos++ || true); }\n err(str) { throw new SyntaxError(str + \" (in content expression '\" + this.string + \"')\"); }\n}\nfunction parseExpr(stream) {\n let exprs = [];\n do {\n exprs.push(parseExprSeq(stream));\n } while (stream.eat(\"|\"));\n return exprs.length == 1 ? exprs[0] : { type: \"choice\", exprs };\n}\nfunction parseExprSeq(stream) {\n let exprs = [];\n do {\n exprs.push(parseExprSubscript(stream));\n } while (stream.next && stream.next != \")\" && stream.next != \"|\");\n return exprs.length == 1 ? exprs[0] : { type: \"seq\", exprs };\n}\nfunction parseExprSubscript(stream) {\n let expr = parseExprAtom(stream);\n for (;;) {\n if (stream.eat(\"+\"))\n expr = { type: \"plus\", expr };\n else if (stream.eat(\"*\"))\n expr = { type: \"star\", expr };\n else if (stream.eat(\"?\"))\n expr = { type: \"opt\", expr };\n else if (stream.eat(\"{\"))\n expr = parseExprRange(stream, expr);\n else\n break;\n }\n return expr;\n}\nfunction parseNum(stream) {\n if (/\\D/.test(stream.next))\n stream.err(\"Expected number, got '\" + stream.next + \"'\");\n let result = Number(stream.next);\n stream.pos++;\n return result;\n}\nfunction parseExprRange(stream, expr) {\n let min = parseNum(stream), max = min;\n if (stream.eat(\",\")) {\n if (stream.next != \"}\")\n max = parseNum(stream);\n else\n max = -1;\n }\n if (!stream.eat(\"}\"))\n stream.err(\"Unclosed braced range\");\n return { type: \"range\", min, max, expr };\n}\nfunction resolveName(stream, name) {\n let types = stream.nodeTypes, type = types[name];\n if (type)\n return [type];\n let result = [];\n for (let typeName in types) {\n let type = types[typeName];\n if (type.isInGroup(name))\n result.push(type);\n }\n if (result.length == 0)\n stream.err(\"No node type or group '\" + name + \"' found\");\n return result;\n}\nfunction parseExprAtom(stream) {\n if (stream.eat(\"(\")) {\n let expr = parseExpr(stream);\n if (!stream.eat(\")\"))\n stream.err(\"Missing closing paren\");\n return expr;\n }\n else if (!/\\W/.test(stream.next)) {\n let exprs = resolveName(stream, stream.next).map(type => {\n if (stream.inline == null)\n stream.inline = type.isInline;\n else if (stream.inline != type.isInline)\n stream.err(\"Mixing inline and block content\");\n return { type: \"name\", value: type };\n });\n stream.pos++;\n return exprs.length == 1 ? exprs[0] : { type: \"choice\", exprs };\n }\n else {\n stream.err(\"Unexpected token '\" + stream.next + \"'\");\n }\n}\n// Construct an NFA from an expression as returned by the parser. The\n// NFA is represented as an array of states, which are themselves\n// arrays of edges, which are `{term, to}` objects. The first state is\n// the entry state and the last node is the success state.\n//\n// Note that unlike typical NFAs, the edge ordering in this one is\n// significant, in that it is used to contruct filler content when\n// necessary.\nfunction nfa(expr) {\n let nfa = [[]];\n connect(compile(expr, 0), node());\n return nfa;\n function node() { return nfa.push([]) - 1; }\n function edge(from, to, term) {\n let edge = { term, to };\n nfa[from].push(edge);\n return edge;\n }\n function connect(edges, to) {\n edges.forEach(edge => edge.to = to);\n }\n function compile(expr, from) {\n if (expr.type == \"choice\") {\n return expr.exprs.reduce((out, expr) => out.concat(compile(expr, from)), []);\n }\n else if (expr.type == \"seq\") {\n for (let i = 0;; i++) {\n let next = compile(expr.exprs[i], from);\n if (i == expr.exprs.length - 1)\n return next;\n connect(next, from = node());\n }\n }\n else if (expr.type == \"star\") {\n let loop = node();\n edge(from, loop);\n connect(compile(expr.expr, loop), loop);\n return [edge(loop)];\n }\n else if (expr.type == \"plus\") {\n let loop = node();\n connect(compile(expr.expr, from), loop);\n connect(compile(expr.expr, loop), loop);\n return [edge(loop)];\n }\n else if (expr.type == \"opt\") {\n return [edge(from)].concat(compile(expr.expr, from));\n }\n else if (expr.type == \"range\") {\n let cur = from;\n for (let i = 0; i < expr.min; i++) {\n let next = node();\n connect(compile(expr.expr, cur), next);\n cur = next;\n }\n if (expr.max == -1) {\n connect(compile(expr.expr, cur), cur);\n }\n else {\n for (let i = expr.min; i < expr.max; i++) {\n let next = node();\n edge(cur, next);\n connect(compile(expr.expr, cur), next);\n cur = next;\n }\n }\n return [edge(cur)];\n }\n else if (expr.type == \"name\") {\n return [edge(from, undefined, expr.value)];\n }\n else {\n throw new Error(\"Unknown expr type\");\n }\n }\n}\nfunction cmp(a, b) { return b - a; }\n// Get the set of nodes reachable by null edges from `node`. Omit\n// nodes with only a single null-out-edge, since they may lead to\n// needless duplicated nodes.\nfunction nullFrom(nfa, node) {\n let result = [];\n scan(node);\n return result.sort(cmp);\n function scan(node) {\n let edges = nfa[node];\n if (edges.length == 1 && !edges[0].term)\n return scan(edges[0].to);\n result.push(node);\n for (let i = 0; i < edges.length; i++) {\n let { term, to } = edges[i];\n if (!term && result.indexOf(to) == -1)\n scan(to);\n }\n }\n}\n// Compiles an NFA as produced by `nfa` into a DFA, modeled as a set\n// of state objects (`ContentMatch` instances) with transitions\n// between them.\nfunction dfa(nfa) {\n let labeled = Object.create(null);\n return explore(nullFrom(nfa, 0));\n function explore(states) {\n let out = [];\n states.forEach(node => {\n nfa[node].forEach(({ term, to }) => {\n if (!term)\n return;\n let set;\n for (let i = 0; i < out.length; i++)\n if (out[i][0] == term)\n set = out[i][1];\n nullFrom(nfa, to).forEach(node => {\n if (!set)\n out.push([term, set = []]);\n if (set.indexOf(node) == -1)\n set.push(node);\n });\n });\n });\n let state = labeled[states.join(\",\")] = new ContentMatch(states.indexOf(nfa.length - 1) > -1);\n for (let i = 0; i < out.length; i++) {\n let states = out[i][1].sort(cmp);\n state.next.push({ type: out[i][0], next: labeled[states.join(\",\")] || explore(states) });\n }\n return state;\n }\n}\nfunction checkForDeadEnds(match, stream) {\n for (let i = 0, work = [match]; i < work.length; i++) {\n let state = work[i], dead = !state.validEnd, nodes = [];\n for (let j = 0; j < state.next.length; j++) {\n let { type, next } = state.next[j];\n nodes.push(type.name);\n if (dead && !(type.isText || type.hasRequiredAttrs()))\n dead = false;\n if (work.indexOf(next) == -1)\n work.push(next);\n }\n if (dead)\n stream.err(\"Only non-generatable nodes (\" + nodes.join(\", \") + \") in a required position (see https://prosemirror.net/docs/guide/#generatable)\");\n }\n}\n\n// For node types where all attrs have a default value (or which don't\n// have any attributes), build up a single reusable default attribute\n// object, and use it for all nodes that don't specify specific\n// attributes.\nfunction defaultAttrs(attrs) {\n let defaults = Object.create(null);\n for (let attrName in attrs) {\n let attr = attrs[attrName];\n if (!attr.hasDefault)\n return null;\n defaults[attrName] = attr.default;\n }\n return defaults;\n}\nfunction computeAttrs(attrs, value) {\n let built = Object.create(null);\n for (let name in attrs) {\n let given = value && value[name];\n if (given === undefined) {\n let attr = attrs[name];\n if (attr.hasDefault)\n given = attr.default;\n else\n throw new RangeError(\"No value supplied for attribute \" + name);\n }\n built[name] = given;\n }\n return built;\n}\nfunction checkAttrs(attrs, values, type, name) {\n for (let attr in values)\n if (!(attr in attrs))\n throw new RangeError(`Unsupported attribute ${attr} for ${type} of type ${name}`);\n for (let attr in attrs) {\n if (attrs[attr].validate)\n attrs[attr].validate(values[attr]);\n }\n}\nfunction initAttrs(typeName, attrs) {\n let result = Object.create(null);\n if (attrs)\n for (let name in attrs)\n result[name] = new Attribute(typeName, name, attrs[name]);\n return result;\n}\n/**\nNode types are objects allocated once per `Schema` and used to\n[tag](https://prosemirror.net/docs/ref/#model.Node.type) `Node` instances. They contain information\nabout the node type, such as its name and what kind of node it\nrepresents.\n*/\nclass NodeType {\n /**\n @internal\n */\n constructor(\n /**\n The name the node type has in this schema.\n */\n name, \n /**\n A link back to the `Schema` the node type belongs to.\n */\n schema, \n /**\n The spec that this type is based on\n */\n spec) {\n this.name = name;\n this.schema = schema;\n this.spec = spec;\n /**\n The set of marks allowed in this node. `null` means all marks\n are allowed.\n */\n this.markSet = null;\n this.groups = spec.group ? spec.group.split(\" \") : [];\n this.attrs = initAttrs(name, spec.attrs);\n this.defaultAttrs = defaultAttrs(this.attrs);\n this.contentMatch = null;\n this.inlineContent = null;\n this.isBlock = !(spec.inline || name == \"text\");\n this.isText = name == \"text\";\n }\n /**\n True if this is an inline type.\n */\n get isInline() { return !this.isBlock; }\n /**\n True if this is a textblock type, a block that contains inline\n content.\n */\n get isTextblock() { return this.isBlock && this.inlineContent; }\n /**\n True for node types that allow no content.\n */\n get isLeaf() { return this.contentMatch == ContentMatch.empty; }\n /**\n True when this node is an atom, i.e. when it does not have\n directly editable content.\n */\n get isAtom() { return this.isLeaf || !!this.spec.atom; }\n /**\n Return true when this node type is part of the given\n [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group).\n */\n isInGroup(group) {\n return this.groups.indexOf(group) > -1;\n }\n /**\n The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.\n */\n get whitespace() {\n return this.spec.whitespace || (this.spec.code ? \"pre\" : \"normal\");\n }\n /**\n Tells you whether this node type has any required attributes.\n */\n hasRequiredAttrs() {\n for (let n in this.attrs)\n if (this.attrs[n].isRequired)\n return true;\n return false;\n }\n /**\n Indicates whether this node allows some of the same content as\n the given node type.\n */\n compatibleContent(other) {\n return this == other || this.contentMatch.compatible(other.contentMatch);\n }\n /**\n @internal\n */\n computeAttrs(attrs) {\n if (!attrs && this.defaultAttrs)\n return this.defaultAttrs;\n else\n return computeAttrs(this.attrs, attrs);\n }\n /**\n Create a `Node` of this type. The given attributes are\n checked and defaulted (you can pass `null` to use the type's\n defaults entirely, if no required attributes exist). `content`\n may be a `Fragment`, a node, an array of nodes, or\n `null`. Similarly `marks` may be `null` to default to the empty\n set of marks.\n */\n create(attrs = null, content, marks) {\n if (this.isText)\n throw new Error(\"NodeType.create can't construct text nodes\");\n return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks));\n }\n /**\n Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content\n against the node type's content restrictions, and throw an error\n if it doesn't match.\n */\n createChecked(attrs = null, content, marks) {\n content = Fragment.from(content);\n this.checkContent(content);\n return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks));\n }\n /**\n Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is\n necessary to add nodes to the start or end of the given fragment\n to make it fit the node. If no fitting wrapping can be found,\n return null. Note that, due to the fact that required nodes can\n always be created, this will always succeed if you pass null or\n `Fragment.empty` as content.\n */\n createAndFill(attrs = null, content, marks) {\n attrs = this.computeAttrs(attrs);\n content = Fragment.from(content);\n if (content.size) {\n let before = this.contentMatch.fillBefore(content);\n if (!before)\n return null;\n content = before.append(content);\n }\n let matched = this.contentMatch.matchFragment(content);\n let after = matched && matched.fillBefore(Fragment.empty, true);\n if (!after)\n return null;\n return new Node(this, attrs, content.append(after), Mark.setFrom(marks));\n }\n /**\n Returns true if the given fragment is valid content for this node\n type.\n */\n validContent(content) {\n let result = this.contentMatch.matchFragment(content);\n if (!result || !result.validEnd)\n return false;\n for (let i = 0; i < content.childCount; i++)\n if (!this.allowsMarks(content.child(i).marks))\n return false;\n return true;\n }\n /**\n Throws a RangeError if the given fragment is not valid content for this\n node type.\n @internal\n */\n checkContent(content) {\n if (!this.validContent(content))\n throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);\n }\n /**\n @internal\n */\n checkAttrs(attrs) {\n checkAttrs(this.attrs, attrs, \"node\", this.name);\n }\n /**\n Check whether the given mark type is allowed in this node.\n */\n allowsMarkType(markType) {\n return this.markSet == null || this.markSet.indexOf(markType) > -1;\n }\n /**\n Test whether the given set of marks are allowed in this node.\n */\n allowsMarks(marks) {\n if (this.markSet == null)\n return true;\n for (let i = 0; i < marks.length; i++)\n if (!this.allowsMarkType(marks[i].type))\n return false;\n return true;\n }\n /**\n Removes the marks that are not allowed in this node from the given set.\n */\n allowedMarks(marks) {\n if (this.markSet == null)\n return marks;\n let copy;\n for (let i = 0; i < marks.length; i++) {\n if (!this.allowsMarkType(marks[i].type)) {\n if (!copy)\n copy = marks.slice(0, i);\n }\n else if (copy) {\n copy.push(marks[i]);\n }\n }\n return !copy ? marks : copy.length ? copy : Mark.none;\n }\n /**\n @internal\n */\n static compile(nodes, schema) {\n let result = Object.create(null);\n nodes.forEach((name, spec) => result[name] = new NodeType(name, schema, spec));\n let topType = schema.spec.topNode || \"doc\";\n if (!result[topType])\n throw new RangeError(\"Schema is missing its top node type ('\" + topType + \"')\");\n if (!result.text)\n throw new RangeError(\"Every schema needs a 'text' type\");\n for (let _ in result.text.attrs)\n throw new RangeError(\"The text node type should not have attributes\");\n return result;\n }\n}\nfunction validateType(typeName, attrName, type) {\n let types = type.split(\"|\");\n return (value) => {\n let name = value === null ? \"null\" : typeof value;\n if (types.indexOf(name) < 0)\n throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`);\n };\n}\n// Attribute descriptors\nclass Attribute {\n constructor(typeName, attrName, options) {\n this.hasDefault = Object.prototype.hasOwnProperty.call(options, \"default\");\n this.default = options.default;\n this.validate = typeof options.validate == \"string\" ? validateType(typeName, attrName, options.validate) : options.validate;\n }\n get isRequired() {\n return !this.hasDefault;\n }\n}\n// Marks\n/**\nLike nodes, marks (which are associated with nodes to signify\nthings like emphasis or being part of a link) are\n[tagged](https://prosemirror.net/docs/ref/#model.Mark.type) with type objects, which are\ninstantiated once per `Schema`.\n*/\nclass MarkType {\n /**\n @internal\n */\n constructor(\n /**\n The name of the mark type.\n */\n name, \n /**\n @internal\n */\n rank, \n /**\n The schema that this mark type instance is part of.\n */\n schema, \n /**\n The spec on which the type is based.\n */\n spec) {\n this.name = name;\n this.rank = rank;\n this.schema = schema;\n this.spec = spec;\n this.attrs = initAttrs(name, spec.attrs);\n this.excluded = null;\n let defaults = defaultAttrs(this.attrs);\n this.instance = defaults ? new Mark(this, defaults) : null;\n }\n /**\n Create a mark of this type. `attrs` may be `null` or an object\n containing only some of the mark's attributes. The others, if\n they have defaults, will be added.\n */\n create(attrs = null) {\n if (!attrs && this.instance)\n return this.instance;\n return new Mark(this, computeAttrs(this.attrs, attrs));\n }\n /**\n @internal\n */\n static compile(marks, schema) {\n let result = Object.create(null), rank = 0;\n marks.forEach((name, spec) => result[name] = new MarkType(name, rank++, schema, spec));\n return result;\n }\n /**\n When there is a mark of this type in the given set, a new set\n without it is returned. Otherwise, the input set is returned.\n */\n removeFromSet(set) {\n for (var i = 0; i < set.length; i++)\n if (set[i].type == this) {\n set = set.slice(0, i).concat(set.slice(i + 1));\n i--;\n }\n return set;\n }\n /**\n Tests whether there is a mark of this type in the given set.\n */\n isInSet(set) {\n for (let i = 0; i < set.length; i++)\n if (set[i].type == this)\n return set[i];\n }\n /**\n @internal\n */\n checkAttrs(attrs) {\n checkAttrs(this.attrs, attrs, \"mark\", this.name);\n }\n /**\n Queries whether a given mark type is\n [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.\n */\n excludes(other) {\n return this.excluded.indexOf(other) > -1;\n }\n}\n/**\nA document schema. Holds [node](https://prosemirror.net/docs/ref/#model.NodeType) and [mark\ntype](https://prosemirror.net/docs/ref/#model.MarkType) objects for the nodes and marks that may\noccur in conforming documents, and provides functionality for\ncreating and deserializing such documents.\n\nWhen given, the type parameters provide the names of the nodes and\nmarks in this schema.\n*/\nclass Schema {\n /**\n Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).\n */\n constructor(spec) {\n /**\n The [linebreak\n replacement](https://prosemirror.net/docs/ref/#model.NodeSpec.linebreakReplacement) node defined\n in this schema, if any.\n */\n this.linebreakReplacement = null;\n /**\n An object for storing whatever values modules may want to\n compute and cache per schema. (If you want to store something\n in it, try to use property names unlikely to clash.)\n */\n this.cached = Object.create(null);\n let instanceSpec = this.spec = {};\n for (let prop in spec)\n instanceSpec[prop] = spec[prop];\n instanceSpec.nodes = OrderedMap.from(spec.nodes),\n instanceSpec.marks = OrderedMap.from(spec.marks || {}),\n this.nodes = NodeType.compile(this.spec.nodes, this);\n this.marks = MarkType.compile(this.spec.marks, this);\n let contentExprCache = Object.create(null);\n for (let prop in this.nodes) {\n if (prop in this.marks)\n throw new RangeError(prop + \" can not be both a node and a mark\");\n let type = this.nodes[prop], contentExpr = type.spec.content || \"\", markExpr = type.spec.marks;\n type.contentMatch = contentExprCache[contentExpr] ||\n (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));\n type.inlineContent = type.contentMatch.inlineContent;\n if (type.spec.linebreakReplacement) {\n if (this.linebreakReplacement)\n throw new RangeError(\"Multiple linebreak nodes defined\");\n if (!type.isInline || !type.isLeaf)\n throw new RangeError(\"Linebreak replacement nodes must be inline leaf nodes\");\n this.linebreakReplacement = type;\n }\n type.markSet = markExpr == \"_\" ? null :\n markExpr ? gatherMarks(this, markExpr.split(\" \")) :\n markExpr == \"\" || !type.inlineContent ? [] : null;\n }\n for (let prop in this.marks) {\n let type = this.marks[prop], excl = type.spec.excludes;\n type.excluded = excl == null ? [type] : excl == \"\" ? [] : gatherMarks(this, excl.split(\" \"));\n }\n this.nodeFromJSON = json => Node.fromJSON(this, json);\n this.markFromJSON = json => Mark.fromJSON(this, json);\n this.topNodeType = this.nodes[this.spec.topNode || \"doc\"];\n this.cached.wrappings = Object.create(null);\n }\n /**\n Create a node in this schema. The `type` may be a string or a\n `NodeType` instance. Attributes will be extended with defaults,\n `content` may be a `Fragment`, `null`, a `Node`, or an array of\n nodes.\n */\n node(type, attrs = null, content, marks) {\n if (typeof type == \"string\")\n type = this.nodeType(type);\n else if (!(type instanceof NodeType))\n throw new RangeError(\"Invalid node type: \" + type);\n else if (type.schema != this)\n throw new RangeError(\"Node type from different schema used (\" + type.name + \")\");\n return type.createChecked(attrs, content, marks);\n }\n /**\n Create a text node in the schema. Empty text nodes are not\n allowed.\n */\n text(text, marks) {\n let type = this.nodes.text;\n return new TextNode(type, type.defaultAttrs, text, Mark.setFrom(marks));\n }\n /**\n Create a mark with the given type and attributes.\n */\n mark(type, attrs) {\n if (typeof type == \"string\")\n type = this.marks[type];\n return type.create(attrs);\n }\n /**\n @internal\n */\n nodeType(name) {\n let found = this.nodes[name];\n if (!found)\n throw new RangeError(\"Unknown node type: \" + name);\n return found;\n }\n}\nfunction gatherMarks(schema, marks) {\n let found = [];\n for (let i = 0; i < marks.length; i++) {\n let name = marks[i], mark = schema.marks[name], ok = mark;\n if (mark) {\n found.push(mark);\n }\n else {\n for (let prop in schema.marks) {\n let mark = schema.marks[prop];\n if (name == \"_\" || (mark.spec.group && mark.spec.group.split(\" \").indexOf(name) > -1))\n found.push(ok = mark);\n }\n }\n if (!ok)\n throw new SyntaxError(\"Unknown mark type: '\" + marks[i] + \"'\");\n }\n return found;\n}\n\nfunction isTagRule(rule) { return rule.tag != null; }\nfunction isStyleRule(rule) { return rule.style != null; }\n/**\nA DOM parser represents a strategy for parsing DOM content into a\nProseMirror document conforming to a given schema. Its behavior is\ndefined by an array of [rules](https://prosemirror.net/docs/ref/#model.ParseRule).\n*/\nclass DOMParser {\n /**\n Create a parser that targets the given schema, using the given\n parsing rules.\n */\n constructor(\n /**\n The schema into which the parser parses.\n */\n schema, \n /**\n The set of [parse rules](https://prosemirror.net/docs/ref/#model.ParseRule) that the parser\n uses, in order of precedence.\n */\n rules) {\n this.schema = schema;\n this.rules = rules;\n /**\n @internal\n */\n this.tags = [];\n /**\n @internal\n */\n this.styles = [];\n let matchedStyles = this.matchedStyles = [];\n rules.forEach(rule => {\n if (isTagRule(rule)) {\n this.tags.push(rule);\n }\n else if (isStyleRule(rule)) {\n let prop = /[^=]*/.exec(rule.style)[0];\n if (matchedStyles.indexOf(prop) < 0)\n matchedStyles.push(prop);\n this.styles.push(rule);\n }\n });\n // Only normalize list elements when lists in the schema can't directly contain themselves\n this.normalizeLists = !this.tags.some(r => {\n if (!/^(ul|ol)\\b/.test(r.tag) || !r.node)\n return false;\n let node = schema.nodes[r.node];\n return node.contentMatch.matchType(node);\n });\n }\n /**\n Parse a document from the content of a DOM node.\n */\n parse(dom, options = {}) {\n let context = new ParseContext(this, options, false);\n context.addAll(dom, Mark.none, options.from, options.to);\n return context.finish();\n }\n /**\n Parses the content of the given DOM node, like\n [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of\n options. But unlike that method, which produces a whole node,\n this one returns a slice that is open at the sides, meaning that\n the schema constraints aren't applied to the start of nodes to\n the left of the input and the end of nodes at the end.\n */\n parseSlice(dom, options = {}) {\n let context = new ParseContext(this, options, true);\n context.addAll(dom, Mark.none, options.from, options.to);\n return Slice.maxOpen(context.finish());\n }\n /**\n @internal\n */\n matchTag(dom, context, after) {\n for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) {\n let rule = this.tags[i];\n if (matches(dom, rule.tag) &&\n (rule.namespace === undefined || dom.namespaceURI == rule.namespace) &&\n (!rule.context || context.matchesContext(rule.context))) {\n if (rule.getAttrs) {\n let result = rule.getAttrs(dom);\n if (result === false)\n continue;\n rule.attrs = result || undefined;\n }\n return rule;\n }\n }\n }\n /**\n @internal\n */\n matchStyle(prop, value, context, after) {\n for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) {\n let rule = this.styles[i], style = rule.style;\n if (style.indexOf(prop) != 0 ||\n rule.context && !context.matchesContext(rule.context) ||\n // Test that the style string either precisely matches the prop,\n // or has an '=' sign after the prop, followed by the given\n // value.\n style.length > prop.length &&\n (style.charCodeAt(prop.length) != 61 || style.slice(prop.length + 1) != value))\n continue;\n if (rule.getAttrs) {\n let result = rule.getAttrs(value);\n if (result === false)\n continue;\n rule.attrs = result || undefined;\n }\n return rule;\n }\n }\n /**\n @internal\n */\n static schemaRules(schema) {\n let result = [];\n function insert(rule) {\n let priority = rule.priority == null ? 50 : rule.priority, i = 0;\n for (; i < result.length; i++) {\n let next = result[i], nextPriority = next.priority == null ? 50 : next.priority;\n if (nextPriority < priority)\n break;\n }\n result.splice(i, 0, rule);\n }\n for (let name in schema.marks) {\n let rules = schema.marks[name].spec.parseDOM;\n if (rules)\n rules.forEach(rule => {\n insert(rule = copy(rule));\n if (!(rule.mark || rule.ignore || rule.clearMark))\n rule.mark = name;\n });\n }\n for (let name in schema.nodes) {\n let rules = schema.nodes[name].spec.parseDOM;\n if (rules)\n rules.forEach(rule => {\n insert(rule = copy(rule));\n if (!(rule.node || rule.ignore || rule.mark))\n rule.node = name;\n });\n }\n return result;\n }\n /**\n Construct a DOM parser using the parsing rules listed in a\n schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by\n [priority](https://prosemirror.net/docs/ref/#model.GenericParseRule.priority).\n */\n static fromSchema(schema) {\n return schema.cached.domParser ||\n (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema)));\n }\n}\nconst blockTags = {\n address: true, article: true, aside: true, blockquote: true, body: true, canvas: true,\n dd: true, div: true, dl: true, fieldset: true, figcaption: true, figure: true,\n footer: true, form: true, h1: true, h2: true, h3: true, h4: true, h5: true,\n h6: true, header: true, hgroup: true, hr: true, li: true, noscript: true, ol: true,\n output: true, p: true, pre: true, section: true, table: true, tfoot: true, ul: true\n};\nconst ignoreTags = {\n head: true, noscript: true, object: true, script: true, style: true, title: true\n};\nconst listTags = { ol: true, ul: true };\n// Using a bitfield for node context options\nconst OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4;\nfunction wsOptionsFor(type, preserveWhitespace, base) {\n if (preserveWhitespace != null)\n return (preserveWhitespace ? OPT_PRESERVE_WS : 0) |\n (preserveWhitespace === \"full\" ? OPT_PRESERVE_WS_FULL : 0);\n return type && type.whitespace == \"pre\" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base & ~OPT_OPEN_LEFT;\n}\nclass NodeContext {\n constructor(type, attrs, marks, solid, match, options) {\n this.type = type;\n this.attrs = attrs;\n this.marks = marks;\n this.solid = solid;\n this.options = options;\n this.content = [];\n // Marks applied to the node's children\n this.activeMarks = Mark.none;\n this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch);\n }\n findWrapping(node) {\n if (!this.match) {\n if (!this.type)\n return [];\n let fill = this.type.contentMatch.fillBefore(Fragment.from(node));\n if (fill) {\n this.match = this.type.contentMatch.matchFragment(fill);\n }\n else {\n let start = this.type.contentMatch, wrap;\n if (wrap = start.findWrapping(node.type)) {\n this.match = start;\n return wrap;\n }\n else {\n return null;\n }\n }\n }\n return this.match.findWrapping(node.type);\n }\n finish(openEnd) {\n if (!(this.options & OPT_PRESERVE_WS)) { // Strip trailing whitespace\n let last = this.content[this.content.length - 1], m;\n if (last && last.isText && (m = /[ \\t\\r\\n\\u000c]+$/.exec(last.text))) {\n let text = last;\n if (last.text.length == m[0].length)\n this.content.pop();\n else\n this.content[this.content.length - 1] = text.withText(text.text.slice(0, text.text.length - m[0].length));\n }\n }\n let content = Fragment.from(this.content);\n if (!openEnd && this.match)\n content = content.append(this.match.fillBefore(Fragment.empty, true));\n return this.type ? this.type.create(this.attrs, content, this.marks) : content;\n }\n inlineContext(node) {\n if (this.type)\n return this.type.inlineContent;\n if (this.content.length)\n return this.content[0].isInline;\n return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase());\n }\n}\nclass ParseContext {\n constructor(\n // The parser we are using.\n parser, \n // The options passed to this parse.\n options, isOpen) {\n this.parser = parser;\n this.options = options;\n this.isOpen = isOpen;\n this.open = 0;\n this.localPreserveWS = false;\n let topNode = options.topNode, topContext;\n let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0);\n if (topNode)\n topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, true, options.topMatch || topNode.type.contentMatch, topOptions);\n else if (isOpen)\n topContext = new NodeContext(null, null, Mark.none, true, null, topOptions);\n else\n topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, true, null, topOptions);\n this.nodes = [topContext];\n this.find = options.findPositions;\n this.needsBlock = false;\n }\n get top() {\n return this.nodes[this.open];\n }\n // Add a DOM node to the content. Text is inserted as text node,\n // otherwise, the node is passed to `addElement` or, if it has a\n // `style` attribute, `addElementWithStyles`.\n addDOM(dom, marks) {\n if (dom.nodeType == 3)\n this.addTextNode(dom, marks);\n else if (dom.nodeType == 1)\n this.addElement(dom, marks);\n }\n addTextNode(dom, marks) {\n let value = dom.nodeValue;\n let top = this.top, preserveWS = (top.options & OPT_PRESERVE_WS_FULL) ? \"full\"\n : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0;\n let { schema } = this.parser;\n if (preserveWS === \"full\" ||\n top.inlineContext(dom) ||\n /[^ \\t\\r\\n\\u000c]/.test(value)) {\n if (!preserveWS) {\n value = value.replace(/[ \\t\\r\\n\\u000c]+/g, \" \");\n // If this starts with whitespace, and there is no node before it, or\n // a hard break, or a text node that ends with whitespace, strip the\n // leading space.\n if (/^[ \\t\\r\\n\\u000c]/.test(value) && this.open == this.nodes.length - 1) {\n let nodeBefore = top.content[top.content.length - 1];\n let domNodeBefore = dom.previousSibling;\n if (!nodeBefore ||\n (domNodeBefore && domNodeBefore.nodeName == 'BR') ||\n (nodeBefore.isText && /[ \\t\\r\\n\\u000c]$/.test(nodeBefore.text)))\n value = value.slice(1);\n }\n }\n else if (preserveWS === \"full\") {\n value = value.replace(/\\r\\n?/g, \"\\n\");\n }\n else if (schema.linebreakReplacement && /[\\r\\n]/.test(value) && this.top.findWrapping(schema.linebreakReplacement.create())) {\n let lines = value.split(/\\r?\\n|\\r/);\n for (let i = 0; i < lines.length; i++) {\n if (i)\n this.insertNode(schema.linebreakReplacement.create(), marks, true);\n if (lines[i])\n this.insertNode(schema.text(lines[i]), marks, !/\\S/.test(lines[i]));\n }\n value = \"\";\n }\n else {\n value = value.replace(/\\r?\\n|\\r/g, \" \");\n }\n if (value)\n this.insertNode(schema.text(value), marks, !/\\S/.test(value));\n this.findInText(dom);\n }\n else {\n this.findInside(dom);\n }\n }\n // Try to find a handler for the given tag and use that to parse. If\n // none is found, the element's content nodes are added directly.\n addElement(dom, marks, matchAfter) {\n let outerWS = this.localPreserveWS, top = this.top;\n if (dom.tagName == \"PRE\" || /pre/.test(dom.style && dom.style.whiteSpace))\n this.localPreserveWS = true;\n let name = dom.nodeName.toLowerCase(), ruleID;\n if (listTags.hasOwnProperty(name) && this.parser.normalizeLists)\n normalizeList(dom);\n let rule = (this.options.ruleFromNode && this.options.ruleFromNode(dom)) ||\n (ruleID = this.parser.matchTag(dom, this, matchAfter));\n out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {\n this.findInside(dom);\n this.ignoreFallback(dom, marks);\n }\n else if (!rule || rule.skip || rule.closeParent) {\n if (rule && rule.closeParent)\n this.open = Math.max(0, this.open - 1);\n else if (rule && rule.skip.nodeType)\n dom = rule.skip;\n let sync, oldNeedsBlock = this.needsBlock;\n if (blockTags.hasOwnProperty(name)) {\n if (top.content.length && top.content[0].isInline && this.open) {\n this.open--;\n top = this.top;\n }\n sync = true;\n if (!top.type)\n this.needsBlock = true;\n }\n else if (!dom.firstChild) {\n this.leafFallback(dom, marks);\n break out;\n }\n let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks);\n if (innerMarks)\n this.addAll(dom, innerMarks);\n if (sync)\n this.sync(top);\n this.needsBlock = oldNeedsBlock;\n }\n else {\n let innerMarks = this.readStyles(dom, marks);\n if (innerMarks)\n this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : undefined);\n }\n this.localPreserveWS = outerWS;\n }\n // Called for leaf DOM nodes that would otherwise be ignored\n leafFallback(dom, marks) {\n if (dom.nodeName == \"BR\" && this.top.type && this.top.type.inlineContent)\n this.addTextNode(dom.ownerDocument.createTextNode(\"\\n\"), marks);\n }\n // Called for ignored nodes\n ignoreFallback(dom, marks) {\n // Ignored BR nodes should at least create an inline context\n if (dom.nodeName == \"BR\" && (!this.top.type || !this.top.type.inlineContent))\n this.findPlace(this.parser.schema.text(\"-\"), marks, true);\n }\n // Run any style parser associated with the node's styles. Either\n // return an updated array of marks, or null to indicate some of the\n // styles had a rule with `ignore` set.\n readStyles(dom, marks) {\n let styles = dom.style;\n // Because many properties will only show up in 'normalized' form\n // in `style.item` (i.e. text-decoration becomes\n // text-decoration-line, text-decoration-color, etc), we directly\n // query the styles mentioned in our rules instead of iterating\n // over the items.\n if (styles && styles.length)\n for (let i = 0; i < this.parser.matchedStyles.length; i++) {\n let name = this.parser.matchedStyles[i], value = styles.getPropertyValue(name);\n if (value)\n for (let after = undefined;;) {\n let rule = this.parser.matchStyle(name, value, this, after);\n if (!rule)\n break;\n if (rule.ignore)\n return null;\n if (rule.clearMark)\n marks = marks.filter(m => !rule.clearMark(m));\n else\n marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs));\n if (rule.consuming === false)\n after = rule;\n else\n break;\n }\n }\n return marks;\n }\n // Look up a handler for the given node. If none are found, return\n // false. Otherwise, apply it, use its return value to drive the way\n // the node's content is wrapped, and return true.\n addElementByRule(dom, rule, marks, continueAfter) {\n let sync, nodeType;\n if (rule.node) {\n nodeType = this.parser.schema.nodes[rule.node];\n if (!nodeType.isLeaf) {\n let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace);\n if (inner) {\n sync = true;\n marks = inner;\n }\n }\n else if (!this.insertNode(nodeType.create(rule.attrs), marks, dom.nodeName == \"BR\")) {\n this.leafFallback(dom, marks);\n }\n }\n else {\n let markType = this.parser.schema.marks[rule.mark];\n marks = marks.concat(markType.create(rule.attrs));\n }\n let startIn = this.top;\n if (nodeType && nodeType.isLeaf) {\n this.findInside(dom);\n }\n else if (continueAfter) {\n this.addElement(dom, marks, continueAfter);\n }\n else if (rule.getContent) {\n this.findInside(dom);\n rule.getContent(dom, this.parser.schema).forEach(node => this.insertNode(node, marks, false));\n }\n else {\n let contentDOM = dom;\n if (typeof rule.contentElement == \"string\")\n contentDOM = dom.querySelector(rule.contentElement);\n else if (typeof rule.contentElement == \"function\")\n contentDOM = rule.contentElement(dom);\n else if (rule.contentElement)\n contentDOM = rule.contentElement;\n this.findAround(dom, contentDOM, true);\n this.addAll(contentDOM, marks);\n this.findAround(dom, contentDOM, false);\n }\n if (sync && this.sync(startIn))\n this.open--;\n }\n // Add all child nodes between `startIndex` and `endIndex` (or the\n // whole node, if not given). If `sync` is passed, use it to\n // synchronize after every block element.\n addAll(parent, marks, startIndex, endIndex) {\n let index = startIndex || 0;\n for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) {\n this.findAtPoint(parent, index);\n this.addDOM(dom, marks);\n }\n this.findAtPoint(parent, index);\n }\n // Try to find a way to fit the given node type into the current\n // context. May add intermediate wrappers and/or leave non-solid\n // nodes that we're in.\n findPlace(node, marks, cautious) {\n let route, sync;\n for (let depth = this.open, penalty = 0; depth >= 0; depth--) {\n let cx = this.nodes[depth];\n let found = cx.findWrapping(node);\n if (found && (!route || route.length > found.length + penalty)) {\n route = found;\n sync = cx;\n if (!found.length)\n break;\n }\n if (cx.solid) {\n if (cautious)\n break;\n penalty += 2;\n }\n }\n if (!route)\n return null;\n this.sync(sync);\n for (let i = 0; i < route.length; i++)\n marks = this.enterInner(route[i], null, marks, false);\n return marks;\n }\n // Try to insert the given node, adjusting the context when needed.\n insertNode(node, marks, cautious) {\n if (node.isInline && this.needsBlock && !this.top.type) {\n let block = this.textblockFromContext();\n if (block)\n marks = this.enterInner(block, null, marks);\n }\n let innerMarks = this.findPlace(node, marks, cautious);\n if (innerMarks) {\n this.closeExtra();\n let top = this.top;\n if (top.match)\n top.match = top.match.matchType(node.type);\n let nodeMarks = Mark.none;\n for (let m of innerMarks.concat(node.marks))\n if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, node.type))\n nodeMarks = m.addToSet(nodeMarks);\n top.content.push(node.mark(nodeMarks));\n return true;\n }\n return false;\n }\n // Try to start a node of the given type, adjusting the context when\n // necessary.\n enter(type, attrs, marks, preserveWS) {\n let innerMarks = this.findPlace(type.create(attrs), marks, false);\n if (innerMarks)\n innerMarks = this.enterInner(type, attrs, marks, true, preserveWS);\n return innerMarks;\n }\n // Open a node of the given type\n enterInner(type, attrs, marks, solid = false, preserveWS) {\n this.closeExtra();\n let top = this.top;\n top.match = top.match && top.match.matchType(type);\n let options = wsOptionsFor(type, preserveWS, top.options);\n if ((top.options & OPT_OPEN_LEFT) && top.content.length == 0)\n options |= OPT_OPEN_LEFT;\n let applyMarks = Mark.none;\n marks = marks.filter(m => {\n if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, type)) {\n applyMarks = m.addToSet(applyMarks);\n return false;\n }\n return true;\n });\n this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options));\n this.open++;\n return marks;\n }\n // Make sure all nodes above this.open are finished and added to\n // their parents\n closeExtra(openEnd = false) {\n let i = this.nodes.length - 1;\n if (i > this.open) {\n for (; i > this.open; i--)\n this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd));\n this.nodes.length = this.open + 1;\n }\n }\n finish() {\n this.open = 0;\n this.closeExtra(this.isOpen);\n return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen));\n }\n sync(to) {\n for (let i = this.open; i >= 0; i--) {\n if (this.nodes[i] == to) {\n this.open = i;\n return true;\n }\n else if (this.localPreserveWS) {\n this.nodes[i].options |= OPT_PRESERVE_WS;\n }\n }\n return false;\n }\n get currentPos() {\n this.closeExtra();\n let pos = 0;\n for (let i = this.open; i >= 0; i--) {\n let content = this.nodes[i].content;\n for (let j = content.length - 1; j >= 0; j--)\n pos += content[j].nodeSize;\n if (i)\n pos++;\n }\n return pos;\n }\n findAtPoint(parent, offset) {\n if (this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].node == parent && this.find[i].offset == offset)\n this.find[i].pos = this.currentPos;\n }\n }\n findInside(parent) {\n if (this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node))\n this.find[i].pos = this.currentPos;\n }\n }\n findAround(parent, content, before) {\n if (parent != content && this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) {\n let pos = content.compareDocumentPosition(this.find[i].node);\n if (pos & (before ? 2 : 4))\n this.find[i].pos = this.currentPos;\n }\n }\n }\n findInText(textNode) {\n if (this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].node == textNode)\n this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset);\n }\n }\n // Determines whether the given context string matches this context.\n matchesContext(context) {\n if (context.indexOf(\"|\") > -1)\n return context.split(/\\s*\\|\\s*/).some(this.matchesContext, this);\n let parts = context.split(\"/\");\n let option = this.options.context;\n let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);\n let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);\n let match = (i, depth) => {\n for (; i >= 0; i--) {\n let part = parts[i];\n if (part == \"\") {\n if (i == parts.length - 1 || i == 0)\n continue;\n for (; depth >= minDepth; depth--)\n if (match(i - 1, depth))\n return true;\n return false;\n }\n else {\n let next = depth > 0 || (depth == 0 && useRoot) ? this.nodes[depth].type\n : option && depth >= minDepth ? option.node(depth - minDepth).type\n : null;\n if (!next || (next.name != part && !next.isInGroup(part)))\n return false;\n depth--;\n }\n }\n return true;\n };\n return match(parts.length - 1, this.open);\n }\n textblockFromContext() {\n let $context = this.options.context;\n if ($context)\n for (let d = $context.depth; d >= 0; d--) {\n let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType;\n if (deflt && deflt.isTextblock && deflt.defaultAttrs)\n return deflt;\n }\n for (let name in this.parser.schema.nodes) {\n let type = this.parser.schema.nodes[name];\n if (type.isTextblock && type.defaultAttrs)\n return type;\n }\n }\n}\n// Kludge to work around directly nested list nodes produced by some\n// tools and allowed by browsers to mean that the nested list is\n// actually part of the list item above it.\nfunction normalizeList(dom) {\n for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {\n let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;\n if (name && listTags.hasOwnProperty(name) && prevItem) {\n prevItem.appendChild(child);\n child = prevItem;\n }\n else if (name == \"li\") {\n prevItem = child;\n }\n else if (name) {\n prevItem = null;\n }\n }\n}\n// Apply a CSS selector.\nfunction matches(dom, selector) {\n return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector);\n}\nfunction copy(obj) {\n let copy = {};\n for (let prop in obj)\n copy[prop] = obj[prop];\n return copy;\n}\n// Used when finding a mark at the top level of a fragment parse.\n// Checks whether it would be reasonable to apply a given mark type to\n// a given node, by looking at the way the mark occurs in the schema.\nfunction markMayApply(markType, nodeType) {\n let nodes = nodeType.schema.nodes;\n for (let name in nodes) {\n let parent = nodes[name];\n if (!parent.allowsMarkType(markType))\n continue;\n let seen = [], scan = (match) => {\n seen.push(match);\n for (let i = 0; i < match.edgeCount; i++) {\n let { type, next } = match.edge(i);\n if (type == nodeType)\n return true;\n if (seen.indexOf(next) < 0 && scan(next))\n return true;\n }\n };\n if (scan(parent.contentMatch))\n return true;\n }\n}\n\n/**\nA DOM serializer knows how to convert ProseMirror nodes and\nmarks of various types to DOM nodes.\n*/\nclass DOMSerializer {\n /**\n Create a serializer. `nodes` should map node names to functions\n that take a node and return a description of the corresponding\n DOM. `marks` does the same for mark names, but also gets an\n argument that tells it whether the mark's content is block or\n inline content (for typical use, it'll always be inline). A mark\n serializer may be `null` to indicate that marks of that type\n should not be serialized.\n */\n constructor(\n /**\n The node serialization functions.\n */\n nodes, \n /**\n The mark serialization functions.\n */\n marks) {\n this.nodes = nodes;\n this.marks = marks;\n }\n /**\n Serialize the content of this fragment to a DOM fragment. When\n not in the browser, the `document` option, containing a DOM\n document, should be passed so that the serializer can create\n nodes.\n */\n serializeFragment(fragment, options = {}, target) {\n if (!target)\n target = doc(options).createDocumentFragment();\n let top = target, active = [];\n fragment.forEach(node => {\n if (active.length || node.marks.length) {\n let keep = 0, rendered = 0;\n while (keep < active.length && rendered < node.marks.length) {\n let next = node.marks[rendered];\n if (!this.marks[next.type.name]) {\n rendered++;\n continue;\n }\n if (!next.eq(active[keep][0]) || next.type.spec.spanning === false)\n break;\n keep++;\n rendered++;\n }\n while (keep < active.length)\n top = active.pop()[1];\n while (rendered < node.marks.length) {\n let add = node.marks[rendered++];\n let markDOM = this.serializeMark(add, node.isInline, options);\n if (markDOM) {\n active.push([add, top]);\n top.appendChild(markDOM.dom);\n top = markDOM.contentDOM || markDOM.dom;\n }\n }\n }\n top.appendChild(this.serializeNodeInner(node, options));\n });\n return target;\n }\n /**\n @internal\n */\n serializeNodeInner(node, options) {\n if (node.isText)\n return doc(options).createTextNode(node.text);\n let { dom, contentDOM } = renderSpec(doc(options), this.nodes[node.type.name](node), null, node.attrs);\n if (contentDOM) {\n if (node.isLeaf)\n throw new RangeError(\"Content hole not allowed in a leaf node spec\");\n this.serializeFragment(node.content, options, contentDOM);\n }\n return dom;\n }\n /**\n Serialize this node to a DOM node. This can be useful when you\n need to serialize a part of a document, as opposed to the whole\n document. To serialize a whole document, use\n [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on\n its [content](https://prosemirror.net/docs/ref/#model.Node.content).\n */\n serializeNode(node, options = {}) {\n let dom = this.serializeNodeInner(node, options);\n for (let i = node.marks.length - 1; i >= 0; i--) {\n let wrap = this.serializeMark(node.marks[i], node.isInline, options);\n if (wrap) {\n (wrap.contentDOM || wrap.dom).appendChild(dom);\n dom = wrap.dom;\n }\n }\n return dom;\n }\n /**\n @internal\n */\n serializeMark(mark, inline, options = {}) {\n let toDOM = this.marks[mark.type.name];\n return toDOM && renderSpec(doc(options), toDOM(mark, inline), null, mark.attrs);\n }\n static renderSpec(doc, structure, xmlNS = null, blockArraysIn) {\n // Kludge for backwards-compatibility with accidental original behavious\n if (typeof structure == \"string\")\n return { dom: doc.createTextNode(structure) };\n return renderSpec(doc, structure, xmlNS, blockArraysIn);\n }\n /**\n Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM)\n properties in a schema's node and mark specs.\n */\n static fromSchema(schema) {\n return schema.cached.domSerializer ||\n (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema)));\n }\n /**\n Gather the serializers in a schema's node specs into an object.\n This can be useful as a base to build a custom serializer from.\n */\n static nodesFromSchema(schema) {\n let result = gatherToDOM(schema.nodes);\n if (!result.text)\n result.text = node => node.text;\n return result;\n }\n /**\n Gather the serializers in a schema's mark specs into an object.\n */\n static marksFromSchema(schema) {\n return gatherToDOM(schema.marks);\n }\n}\nfunction gatherToDOM(obj) {\n let result = {};\n for (let name in obj) {\n let toDOM = obj[name].spec.toDOM;\n if (toDOM)\n result[name] = toDOM;\n }\n return result;\n}\nfunction doc(options) {\n return options.document || window.document;\n}\nconst suspiciousAttributeCache = new WeakMap();\nfunction suspiciousAttributes(attrs) {\n let value = suspiciousAttributeCache.get(attrs);\n if (value === undefined)\n suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs));\n return value;\n}\nfunction suspiciousAttributesInner(attrs) {\n let result = null;\n function scan(value) {\n if (value && typeof value == \"object\") {\n if (Array.isArray(value)) {\n if (typeof value[0] == \"string\") {\n if (!result)\n result = [];\n result.push(value);\n }\n else {\n for (let i = 0; i < value.length; i++)\n scan(value[i]);\n }\n }\n else {\n for (let prop in value)\n scan(value[prop]);\n }\n }\n }\n scan(attrs);\n return result;\n}\nfunction renderSpec(doc, structure, xmlNS, blockArraysIn) {\n if (structure.nodeType == 1)\n return { dom: structure };\n if (structure.dom && structure.dom.nodeType == 1)\n return structure;\n let tagName = structure[0], suspicious;\n if (typeof tagName != \"string\")\n throw new RangeError(\"Invalid array passed to renderSpec\");\n if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) &&\n suspicious.indexOf(structure) > -1)\n throw new RangeError(\"Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.\");\n let space = tagName.indexOf(\" \");\n if (space > 0) {\n xmlNS = tagName.slice(0, space);\n tagName = tagName.slice(space + 1);\n }\n let contentDOM;\n let dom = (xmlNS ? doc.createElementNS(xmlNS, tagName) : doc.createElement(tagName));\n let attrs = structure[1], start = 1;\n if (attrs && typeof attrs == \"object\" && attrs.nodeType == null && !Array.isArray(attrs)) {\n start = 2;\n for (let name in attrs)\n if (attrs[name] != null) {\n let space = name.indexOf(\" \");\n if (space > 0)\n dom.setAttributeNS(name.slice(0, space), name.slice(space + 1), attrs[name]);\n else if (name == \"style\" && dom.style)\n dom.style.cssText = attrs[name];\n else\n dom.setAttribute(name, attrs[name]);\n }\n }\n for (let i = start; i < structure.length; i++) {\n let child = structure[i];\n if (child === 0) {\n if (i < structure.length - 1 || i > start)\n throw new RangeError(\"Content hole must be the only child of its parent node\");\n return { dom, contentDOM: dom };\n }\n else if (typeof child == \"string\") {\n dom.appendChild(doc.createTextNode(child));\n }\n else {\n let { dom: inner, contentDOM: innerContent } = renderSpec(doc, child, xmlNS, blockArraysIn);\n dom.appendChild(inner);\n if (innerContent) {\n if (contentDOM)\n throw new RangeError(\"Multiple content holes\");\n contentDOM = innerContent;\n }\n }\n }\n return { dom, contentDOM };\n}\n\nexport { ContentMatch, DOMParser, DOMSerializer, Fragment, Mark, MarkType, Node, NodeRange, NodeType, ReplaceError, ResolvedPos, Schema, Slice };\n","import { ReplaceError, Slice, Fragment, MarkType, Mark } from 'prosemirror-model';\n\n// Recovery values encode a range index and an offset. They are\n// represented as numbers, because tons of them will be created when\n// mapping, for example, a large number of decorations. The number's\n// lower 16 bits provide the index, the remaining bits the offset.\n//\n// Note: We intentionally don't use bit shift operators to en- and\n// decode these, since those clip to 32 bits, which we might in rare\n// cases want to overflow. A 64-bit float can represent 48-bit\n// integers precisely.\nconst lower16 = 0xffff;\nconst factor16 = Math.pow(2, 16);\nfunction makeRecover(index, offset) { return index + offset * factor16; }\nfunction recoverIndex(value) { return value & lower16; }\nfunction recoverOffset(value) { return (value - (value & lower16)) / factor16; }\nconst DEL_BEFORE = 1, DEL_AFTER = 2, DEL_ACROSS = 4, DEL_SIDE = 8;\n/**\nAn object representing a mapped position with extra\ninformation.\n*/\nclass MapResult {\n /**\n @internal\n */\n constructor(\n /**\n The mapped version of the position.\n */\n pos, \n /**\n @internal\n */\n delInfo, \n /**\n @internal\n */\n recover) {\n this.pos = pos;\n this.delInfo = delInfo;\n this.recover = recover;\n }\n /**\n Tells you whether the position was deleted, that is, whether the\n step removed the token on the side queried (via the `assoc`)\n argument from the document.\n */\n get deleted() { return (this.delInfo & DEL_SIDE) > 0; }\n /**\n Tells you whether the token before the mapped position was deleted.\n */\n get deletedBefore() { return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0; }\n /**\n True when the token after the mapped position was deleted.\n */\n get deletedAfter() { return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0; }\n /**\n Tells whether any of the steps mapped through deletes across the\n position (including both the token before and after the\n position).\n */\n get deletedAcross() { return (this.delInfo & DEL_ACROSS) > 0; }\n}\n/**\nA map describing the deletions and insertions made by a step, which\ncan be used to find the correspondence between positions in the\npre-step version of a document and the same position in the\npost-step version.\n*/\nclass StepMap {\n /**\n Create a position map. The modifications to the document are\n represented as an array of numbers, in which each group of three\n represents a modified chunk as `[start, oldSize, newSize]`.\n */\n constructor(\n /**\n @internal\n */\n ranges, \n /**\n @internal\n */\n inverted = false) {\n this.ranges = ranges;\n this.inverted = inverted;\n if (!ranges.length && StepMap.empty)\n return StepMap.empty;\n }\n /**\n @internal\n */\n recover(value) {\n let diff = 0, index = recoverIndex(value);\n if (!this.inverted)\n for (let i = 0; i < index; i++)\n diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1];\n return this.ranges[index * 3] + diff + recoverOffset(value);\n }\n mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n map(pos, assoc = 1) { return this._map(pos, assoc, true); }\n /**\n @internal\n */\n _map(pos, assoc, simple) {\n let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos)\n break;\n let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize;\n if (pos <= end) {\n let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;\n let result = start + diff + (side < 0 ? 0 : newSize);\n if (simple)\n return result;\n let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start);\n let del = pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;\n if (assoc < 0 ? pos != start : pos != end)\n del |= DEL_SIDE;\n return new MapResult(result, del, recover);\n }\n diff += newSize - oldSize;\n }\n return simple ? pos + diff : new MapResult(pos + diff, 0, null);\n }\n /**\n @internal\n */\n touches(pos, recover) {\n let diff = 0, index = recoverIndex(recover);\n let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos)\n break;\n let oldSize = this.ranges[i + oldIndex], end = start + oldSize;\n if (pos <= end && i == index * 3)\n return true;\n diff += this.ranges[i + newIndex] - oldSize;\n }\n return false;\n }\n /**\n Calls the given function on each of the changed ranges included in\n this map.\n */\n forEach(f) {\n let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0, diff = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff);\n let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex];\n f(oldStart, oldStart + oldSize, newStart, newStart + newSize);\n diff += newSize - oldSize;\n }\n }\n /**\n Create an inverted version of this map. The result can be used to\n map positions in the post-step document to the pre-step document.\n */\n invert() {\n return new StepMap(this.ranges, !this.inverted);\n }\n /**\n @internal\n */\n toString() {\n return (this.inverted ? \"-\" : \"\") + JSON.stringify(this.ranges);\n }\n /**\n Create a map that moves all positions by offset `n` (which may be\n negative). This can be useful when applying steps meant for a\n sub-document to a larger document, or vice-versa.\n */\n static offset(n) {\n return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);\n }\n}\n/**\nA StepMap that contains no changed ranges.\n*/\nStepMap.empty = new StepMap([]);\n/**\nA mapping represents a pipeline of zero or more [step\nmaps](https://prosemirror.net/docs/ref/#transform.StepMap). It has special provisions for losslessly\nhandling mapping positions through a series of steps in which some\nsteps are inverted versions of earlier steps. (This comes up when\n‘[rebasing](https://prosemirror.net/docs/guide/#transform.rebasing)’ steps for\ncollaboration or history management.)\n*/\nclass Mapping {\n /**\n Create a new mapping with the given position maps.\n */\n constructor(maps, \n /**\n @internal\n */\n mirror, \n /**\n The starting position in the `maps` array, used when `map` or\n `mapResult` is called.\n */\n from = 0, \n /**\n The end position in the `maps` array.\n */\n to = maps ? maps.length : 0) {\n this.mirror = mirror;\n this.from = from;\n this.to = to;\n this._maps = maps || [];\n this.ownData = !(maps || mirror);\n }\n /**\n The step maps in this mapping.\n */\n get maps() { return this._maps; }\n /**\n Create a mapping that maps only through a part of this one.\n */\n slice(from = 0, to = this.maps.length) {\n return new Mapping(this._maps, this.mirror, from, to);\n }\n /**\n Add a step map to the end of this mapping. If `mirrors` is\n given, it should be the index of the step map that is the mirror\n image of this one.\n */\n appendMap(map, mirrors) {\n if (!this.ownData) {\n this._maps = this._maps.slice();\n this.mirror = this.mirror && this.mirror.slice();\n this.ownData = true;\n }\n this.to = this._maps.push(map);\n if (mirrors != null)\n this.setMirror(this._maps.length - 1, mirrors);\n }\n /**\n Add all the step maps in a given mapping to this one (preserving\n mirroring information).\n */\n appendMapping(mapping) {\n for (let i = 0, startSize = this._maps.length; i < mapping._maps.length; i++) {\n let mirr = mapping.getMirror(i);\n this.appendMap(mapping._maps[i], mirr != null && mirr < i ? startSize + mirr : undefined);\n }\n }\n /**\n Finds the offset of the step map that mirrors the map at the\n given offset, in this mapping (as per the second argument to\n `appendMap`).\n */\n getMirror(n) {\n if (this.mirror)\n for (let i = 0; i < this.mirror.length; i++)\n if (this.mirror[i] == n)\n return this.mirror[i + (i % 2 ? -1 : 1)];\n }\n /**\n @internal\n */\n setMirror(n, m) {\n if (!this.mirror)\n this.mirror = [];\n this.mirror.push(n, m);\n }\n /**\n Append the inverse of the given mapping to this one.\n */\n appendMappingInverted(mapping) {\n for (let i = mapping.maps.length - 1, totalSize = this._maps.length + mapping._maps.length; i >= 0; i--) {\n let mirr = mapping.getMirror(i);\n this.appendMap(mapping._maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : undefined);\n }\n }\n /**\n Create an inverted version of this mapping.\n */\n invert() {\n let inverse = new Mapping;\n inverse.appendMappingInverted(this);\n return inverse;\n }\n /**\n Map a position through this mapping.\n */\n map(pos, assoc = 1) {\n if (this.mirror)\n return this._map(pos, assoc, true);\n for (let i = this.from; i < this.to; i++)\n pos = this._maps[i].map(pos, assoc);\n return pos;\n }\n /**\n Map a position through this mapping, returning a mapping\n result.\n */\n mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n /**\n @internal\n */\n _map(pos, assoc, simple) {\n let delInfo = 0;\n for (let i = this.from; i < this.to; i++) {\n let map = this._maps[i], result = map.mapResult(pos, assoc);\n if (result.recover != null) {\n let corr = this.getMirror(i);\n if (corr != null && corr > i && corr < this.to) {\n i = corr;\n pos = this._maps[corr].recover(result.recover);\n continue;\n }\n }\n delInfo |= result.delInfo;\n pos = result.pos;\n }\n return simple ? pos : new MapResult(pos, delInfo, null);\n }\n}\n\nconst stepsByID = Object.create(null);\n/**\nA step object represents an atomic change. It generally applies\nonly to the document it was created for, since the positions\nstored in it will only make sense for that document.\n\nNew steps are defined by creating classes that extend `Step`,\noverriding the `apply`, `invert`, `map`, `getMap` and `fromJSON`\nmethods, and registering your class with a unique\nJSON-serialization identifier using\n[`Step.jsonID`](https://prosemirror.net/docs/ref/#transform.Step^jsonID).\n*/\nclass Step {\n /**\n Get the step map that represents the changes made by this step,\n and which can be used to transform between positions in the old\n and the new document.\n */\n getMap() { return StepMap.empty; }\n /**\n Try to merge this step with another one, to be applied directly\n after it. Returns the merged step when possible, null if the\n steps can't be merged.\n */\n merge(other) { return null; }\n /**\n Deserialize a step from its JSON representation. Will call\n through to the step class' own implementation of this method.\n */\n static fromJSON(schema, json) {\n if (!json || !json.stepType)\n throw new RangeError(\"Invalid input for Step.fromJSON\");\n let type = stepsByID[json.stepType];\n if (!type)\n throw new RangeError(`No step type ${json.stepType} defined`);\n return type.fromJSON(schema, json);\n }\n /**\n To be able to serialize steps to JSON, each step needs a string\n ID to attach to its JSON representation. Use this method to\n register an ID for your step classes. Try to pick something\n that's unlikely to clash with steps from other modules.\n */\n static jsonID(id, stepClass) {\n if (id in stepsByID)\n throw new RangeError(\"Duplicate use of step JSON ID \" + id);\n stepsByID[id] = stepClass;\n stepClass.prototype.jsonID = id;\n return stepClass;\n }\n}\n/**\nThe result of [applying](https://prosemirror.net/docs/ref/#transform.Step.apply) a step. Contains either a\nnew document or a failure value.\n*/\nclass StepResult {\n /**\n @internal\n */\n constructor(\n /**\n The transformed document, if successful.\n */\n doc, \n /**\n The failure message, if unsuccessful.\n */\n failed) {\n this.doc = doc;\n this.failed = failed;\n }\n /**\n Create a successful step result.\n */\n static ok(doc) { return new StepResult(doc, null); }\n /**\n Create a failed step result.\n */\n static fail(message) { return new StepResult(null, message); }\n /**\n Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given\n arguments. Create a successful result if it succeeds, and a\n failed one if it throws a `ReplaceError`.\n */\n static fromReplace(doc, from, to, slice) {\n try {\n return StepResult.ok(doc.replace(from, to, slice));\n }\n catch (e) {\n if (e instanceof ReplaceError)\n return StepResult.fail(e.message);\n throw e;\n }\n }\n}\n\nfunction mapFragment(fragment, f, parent) {\n let mapped = [];\n for (let i = 0; i < fragment.childCount; i++) {\n let child = fragment.child(i);\n if (child.content.size)\n child = child.copy(mapFragment(child.content, f, child));\n if (child.isInline)\n child = f(child, parent, i);\n mapped.push(child);\n }\n return Fragment.fromArray(mapped);\n}\n/**\nAdd a mark to all inline content between two positions.\n*/\nclass AddMarkStep extends Step {\n /**\n Create a mark step.\n */\n constructor(\n /**\n The start of the marked range.\n */\n from, \n /**\n The end of the marked range.\n */\n to, \n /**\n The mark to add.\n */\n mark) {\n super();\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n apply(doc) {\n let oldSlice = doc.slice(this.from, this.to), $from = doc.resolve(this.from);\n let parent = $from.node($from.sharedDepth(this.to));\n let slice = new Slice(mapFragment(oldSlice.content, (node, parent) => {\n if (!node.isAtom || !parent.type.allowsMarkType(this.mark.type))\n return node;\n return node.mark(this.mark.addToSet(node.marks));\n }, parent), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice);\n }\n invert() {\n return new RemoveMarkStep(this.from, this.to, this.mark);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted || from.pos >= to.pos)\n return null;\n return new AddMarkStep(from.pos, to.pos, this.mark);\n }\n merge(other) {\n if (other instanceof AddMarkStep &&\n other.mark.eq(this.mark) &&\n this.from <= other.to && this.to >= other.from)\n return new AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n return null;\n }\n toJSON() {\n return { stepType: \"addMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for AddMarkStep.fromJSON\");\n return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"addMark\", AddMarkStep);\n/**\nRemove a mark from all inline content between two positions.\n*/\nclass RemoveMarkStep extends Step {\n /**\n Create a mark-removing step.\n */\n constructor(\n /**\n The start of the unmarked range.\n */\n from, \n /**\n The end of the unmarked range.\n */\n to, \n /**\n The mark to remove.\n */\n mark) {\n super();\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n apply(doc) {\n let oldSlice = doc.slice(this.from, this.to);\n let slice = new Slice(mapFragment(oldSlice.content, node => {\n return node.mark(this.mark.removeFromSet(node.marks));\n }, doc), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice);\n }\n invert() {\n return new AddMarkStep(this.from, this.to, this.mark);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted || from.pos >= to.pos)\n return null;\n return new RemoveMarkStep(from.pos, to.pos, this.mark);\n }\n merge(other) {\n if (other instanceof RemoveMarkStep &&\n other.mark.eq(this.mark) &&\n this.from <= other.to && this.to >= other.from)\n return new RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n return null;\n }\n toJSON() {\n return { stepType: \"removeMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for RemoveMarkStep.fromJSON\");\n return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"removeMark\", RemoveMarkStep);\n/**\nAdd a mark to a specific node.\n*/\nclass AddNodeMarkStep extends Step {\n /**\n Create a node mark step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The mark to add.\n */\n mark) {\n super();\n this.pos = pos;\n this.mark = mark;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at mark step's position\");\n let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks));\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n invert(doc) {\n let node = doc.nodeAt(this.pos);\n if (node) {\n let newSet = this.mark.addToSet(node.marks);\n if (newSet.length == node.marks.length) {\n for (let i = 0; i < node.marks.length; i++)\n if (!node.marks[i].isInSet(newSet))\n return new AddNodeMarkStep(this.pos, node.marks[i]);\n return new AddNodeMarkStep(this.pos, this.mark);\n }\n }\n return new RemoveNodeMarkStep(this.pos, this.mark);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark);\n }\n toJSON() {\n return { stepType: \"addNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for AddNodeMarkStep.fromJSON\");\n return new AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"addNodeMark\", AddNodeMarkStep);\n/**\nRemove a mark from a specific node.\n*/\nclass RemoveNodeMarkStep extends Step {\n /**\n Create a mark-removing step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The mark to remove.\n */\n mark) {\n super();\n this.pos = pos;\n this.mark = mark;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at mark step's position\");\n let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks));\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n invert(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node || !this.mark.isInSet(node.marks))\n return this;\n return new AddNodeMarkStep(this.pos, this.mark);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark);\n }\n toJSON() {\n return { stepType: \"removeNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for RemoveNodeMarkStep.fromJSON\");\n return new RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"removeNodeMark\", RemoveNodeMarkStep);\n\n/**\nReplace a part of the document with a slice of new content.\n*/\nclass ReplaceStep extends Step {\n /**\n The given `slice` should fit the 'gap' between `from` and\n `to`—the depths must line up, and the surrounding nodes must be\n able to be joined with the open sides of the slice. When\n `structure` is true, the step will fail if the content between\n from and to is not just a sequence of closing and then opening\n tokens (this is to guard against rebased replace steps\n overwriting something they weren't supposed to).\n */\n constructor(\n /**\n The start position of the replaced range.\n */\n from, \n /**\n The end position of the replaced range.\n */\n to, \n /**\n The slice to insert.\n */\n slice, \n /**\n @internal\n */\n structure = false) {\n super();\n this.from = from;\n this.to = to;\n this.slice = slice;\n this.structure = structure;\n }\n apply(doc) {\n if (this.structure && contentBetween(doc, this.from, this.to))\n return StepResult.fail(\"Structure replace would overwrite content\");\n return StepResult.fromReplace(doc, this.from, this.to, this.slice);\n }\n getMap() {\n return new StepMap([this.from, this.to - this.from, this.slice.size]);\n }\n invert(doc) {\n return new ReplaceStep(this.from, this.from + this.slice.size, doc.slice(this.from, this.to));\n }\n map(mapping) {\n let to = mapping.mapResult(this.to, -1);\n let from = this.from == this.to && ReplaceStep.MAP_BIAS < 0 ? to : mapping.mapResult(this.from, 1);\n if (from.deletedAcross && to.deletedAcross)\n return null;\n return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice, this.structure);\n }\n merge(other) {\n if (!(other instanceof ReplaceStep) || other.structure || this.structure)\n return null;\n if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {\n let slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);\n return new ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure);\n }\n else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {\n let slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);\n return new ReplaceStep(other.from, this.to, slice, this.structure);\n }\n else {\n return null;\n }\n }\n toJSON() {\n let json = { stepType: \"replace\", from: this.from, to: this.to };\n if (this.slice.size)\n json.slice = this.slice.toJSON();\n if (this.structure)\n json.structure = true;\n return json;\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for ReplaceStep.fromJSON\");\n return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure);\n }\n}\n/**\nBy default, for backwards compatibility, an inserting step\nmapped over an insertion at that same position fill move after\nthe inserted content. In a collaborative editing situation, that\ncan make redone insertions appear in unexpected places. You can\nset this to -1 to make such mapping keep the step before the\ninsertion instead.\n*/\nReplaceStep.MAP_BIAS = 1;\nStep.jsonID(\"replace\", ReplaceStep);\n/**\nReplace a part of the document with a slice of content, but\npreserve a range of the replaced content by moving it into the\nslice.\n*/\nclass ReplaceAroundStep extends Step {\n /**\n Create a replace-around step with the given range and gap.\n `insert` should be the point in the slice into which the content\n of the gap should be moved. `structure` has the same meaning as\n it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class.\n */\n constructor(\n /**\n The start position of the replaced range.\n */\n from, \n /**\n The end position of the replaced range.\n */\n to, \n /**\n The start of preserved range.\n */\n gapFrom, \n /**\n The end of preserved range.\n */\n gapTo, \n /**\n The slice to insert.\n */\n slice, \n /**\n The position in the slice where the preserved range should be\n inserted.\n */\n insert, \n /**\n @internal\n */\n structure = false) {\n super();\n this.from = from;\n this.to = to;\n this.gapFrom = gapFrom;\n this.gapTo = gapTo;\n this.slice = slice;\n this.insert = insert;\n this.structure = structure;\n }\n apply(doc) {\n if (this.structure && (contentBetween(doc, this.from, this.gapFrom) ||\n contentBetween(doc, this.gapTo, this.to)))\n return StepResult.fail(\"Structure gap-replace would overwrite content\");\n let gap = doc.slice(this.gapFrom, this.gapTo);\n if (gap.openStart || gap.openEnd)\n return StepResult.fail(\"Gap is not a flat range\");\n let inserted = this.slice.insertAt(this.insert, gap.content);\n if (!inserted)\n return StepResult.fail(\"Content does not fit in gap\");\n return StepResult.fromReplace(doc, this.from, this.to, inserted);\n }\n getMap() {\n return new StepMap([this.from, this.gapFrom - this.from, this.insert,\n this.gapTo, this.to - this.gapTo, this.slice.size - this.insert]);\n }\n invert(doc) {\n let gap = this.gapTo - this.gapFrom;\n return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n let gapFrom = this.from == this.gapFrom ? from.pos : mapping.map(this.gapFrom, -1);\n let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1);\n if ((from.deletedAcross && to.deletedAcross) || gapFrom < from.pos || gapTo > to.pos)\n return null;\n return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);\n }\n toJSON() {\n let json = { stepType: \"replaceAround\", from: this.from, to: this.to,\n gapFrom: this.gapFrom, gapTo: this.gapTo, insert: this.insert };\n if (this.slice.size)\n json.slice = this.slice.toJSON();\n if (this.structure)\n json.structure = true;\n return json;\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\" ||\n typeof json.gapFrom != \"number\" || typeof json.gapTo != \"number\" || typeof json.insert != \"number\")\n throw new RangeError(\"Invalid input for ReplaceAroundStep.fromJSON\");\n return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);\n }\n}\nStep.jsonID(\"replaceAround\", ReplaceAroundStep);\nfunction contentBetween(doc, from, to) {\n let $from = doc.resolve(from), dist = to - from, depth = $from.depth;\n while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {\n depth--;\n dist--;\n }\n if (dist > 0) {\n let next = $from.node(depth).maybeChild($from.indexAfter(depth));\n while (dist > 0) {\n if (!next || next.isLeaf)\n return true;\n next = next.firstChild;\n dist--;\n }\n }\n return false;\n}\n\nfunction addMark(tr, from, to, mark) {\n let removed = [], added = [];\n let removing, adding;\n tr.doc.nodesBetween(from, to, (node, pos, parent) => {\n if (!node.isInline)\n return;\n let marks = node.marks;\n if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {\n let start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to);\n let newSet = mark.addToSet(marks);\n for (let i = 0; i < marks.length; i++) {\n if (!marks[i].isInSet(newSet)) {\n if (removing && removing.to == start && removing.mark.eq(marks[i]))\n removing.to = end;\n else\n removed.push(removing = new RemoveMarkStep(start, end, marks[i]));\n }\n }\n if (adding && adding.to == start)\n adding.to = end;\n else\n added.push(adding = new AddMarkStep(start, end, mark));\n }\n });\n removed.forEach(s => tr.step(s));\n added.forEach(s => tr.step(s));\n}\nfunction removeMark(tr, from, to, mark) {\n let matched = [], step = 0;\n tr.doc.nodesBetween(from, to, (node, pos) => {\n if (!node.isInline)\n return;\n step++;\n let toRemove = null;\n if (mark instanceof MarkType) {\n let set = node.marks, found;\n while (found = mark.isInSet(set)) {\n (toRemove || (toRemove = [])).push(found);\n set = found.removeFromSet(set);\n }\n }\n else if (mark) {\n if (mark.isInSet(node.marks))\n toRemove = [mark];\n }\n else {\n toRemove = node.marks;\n }\n if (toRemove && toRemove.length) {\n let end = Math.min(pos + node.nodeSize, to);\n for (let i = 0; i < toRemove.length; i++) {\n let style = toRemove[i], found;\n for (let j = 0; j < matched.length; j++) {\n let m = matched[j];\n if (m.step == step - 1 && style.eq(matched[j].style))\n found = m;\n }\n if (found) {\n found.to = end;\n found.step = step;\n }\n else {\n matched.push({ style, from: Math.max(pos, from), to: end, step });\n }\n }\n }\n });\n matched.forEach(m => tr.step(new RemoveMarkStep(m.from, m.to, m.style)));\n}\nfunction clearIncompatible(tr, pos, parentType, match = parentType.contentMatch, clearNewlines = true) {\n let node = tr.doc.nodeAt(pos);\n let replSteps = [], cur = pos + 1;\n for (let i = 0; i < node.childCount; i++) {\n let child = node.child(i), end = cur + child.nodeSize;\n let allowed = match.matchType(child.type);\n if (!allowed) {\n replSteps.push(new ReplaceStep(cur, end, Slice.empty));\n }\n else {\n match = allowed;\n for (let j = 0; j < child.marks.length; j++)\n if (!parentType.allowsMarkType(child.marks[j].type))\n tr.step(new RemoveMarkStep(cur, end, child.marks[j]));\n if (clearNewlines && child.isText && parentType.whitespace != \"pre\") {\n let m, newline = /\\r?\\n|\\r/g, slice;\n while (m = newline.exec(child.text)) {\n if (!slice)\n slice = new Slice(Fragment.from(parentType.schema.text(\" \", parentType.allowedMarks(child.marks))), 0, 0);\n replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice));\n }\n }\n }\n cur = end;\n }\n if (!match.validEnd) {\n let fill = match.fillBefore(Fragment.empty, true);\n tr.replace(cur, cur, new Slice(fill, 0, 0));\n }\n for (let i = replSteps.length - 1; i >= 0; i--)\n tr.step(replSteps[i]);\n}\n\nfunction canCut(node, start, end) {\n return (start == 0 || node.canReplace(start, node.childCount)) &&\n (end == node.childCount || node.canReplace(0, end));\n}\n/**\nTry to find a target depth to which the content in the given range\ncan be lifted. Will not go across\n[isolating](https://prosemirror.net/docs/ref/#model.NodeSpec.isolating) parent nodes.\n*/\nfunction liftTarget(range) {\n let parent = range.parent;\n let content = parent.content.cutByIndex(range.startIndex, range.endIndex);\n for (let depth = range.depth, contentBefore = 0, contentAfter = 0;; --depth) {\n let node = range.$from.node(depth);\n let index = range.$from.index(depth) + contentBefore, endIndex = range.$to.indexAfter(depth) - contentAfter;\n if (depth < range.depth && node.canReplace(index, endIndex, content))\n return depth;\n if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex))\n break;\n if (index)\n contentBefore = 1;\n if (endIndex < node.childCount)\n contentAfter = 1;\n }\n return null;\n}\nfunction lift(tr, range, target) {\n let { $from, $to, depth } = range;\n let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);\n let start = gapStart, end = gapEnd;\n let before = Fragment.empty, openStart = 0;\n for (let d = depth, splitting = false; d > target; d--)\n if (splitting || $from.index(d) > 0) {\n splitting = true;\n before = Fragment.from($from.node(d).copy(before));\n openStart++;\n }\n else {\n start--;\n }\n let after = Fragment.empty, openEnd = 0;\n for (let d = depth, splitting = false; d > target; d--)\n if (splitting || $to.after(d + 1) < $to.end(d)) {\n splitting = true;\n after = Fragment.from($to.node(d).copy(after));\n openEnd++;\n }\n else {\n end++;\n }\n tr.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));\n}\n/**\nTry to find a valid way to wrap the content in the given range in a\nnode of the given type. May introduce extra nodes around and inside\nthe wrapper node, if necessary. Returns null if no valid wrapping\ncould be found. When `innerRange` is given, that range's content is\nused as the content to fit into the wrapping, instead of the\ncontent of `range`.\n*/\nfunction findWrapping(range, nodeType, attrs = null, innerRange = range) {\n let around = findWrappingOutside(range, nodeType);\n let inner = around && findWrappingInside(innerRange, nodeType);\n if (!inner)\n return null;\n return around.map(withAttrs)\n .concat({ type: nodeType, attrs }).concat(inner.map(withAttrs));\n}\nfunction withAttrs(type) { return { type, attrs: null }; }\nfunction findWrappingOutside(range, type) {\n let { parent, startIndex, endIndex } = range;\n let around = parent.contentMatchAt(startIndex).findWrapping(type);\n if (!around)\n return null;\n let outer = around.length ? around[0] : type;\n return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;\n}\nfunction findWrappingInside(range, type) {\n let { parent, startIndex, endIndex } = range;\n let inner = parent.child(startIndex);\n let inside = type.contentMatch.findWrapping(inner.type);\n if (!inside)\n return null;\n let lastType = inside.length ? inside[inside.length - 1] : type;\n let innerMatch = lastType.contentMatch;\n for (let i = startIndex; innerMatch && i < endIndex; i++)\n innerMatch = innerMatch.matchType(parent.child(i).type);\n if (!innerMatch || !innerMatch.validEnd)\n return null;\n return inside;\n}\nfunction wrap(tr, range, wrappers) {\n let content = Fragment.empty;\n for (let i = wrappers.length - 1; i >= 0; i--) {\n if (content.size) {\n let match = wrappers[i].type.contentMatch.matchFragment(content);\n if (!match || !match.validEnd)\n throw new RangeError(\"Wrapper type given to Transform.wrap does not form valid content of its parent wrapper\");\n }\n content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));\n }\n let start = range.start, end = range.end;\n tr.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true));\n}\nfunction setBlockType(tr, from, to, type, attrs) {\n if (!type.isTextblock)\n throw new RangeError(\"Type given to setBlockType should be a textblock\");\n let mapFrom = tr.steps.length;\n tr.doc.nodesBetween(from, to, (node, pos) => {\n let attrsHere = typeof attrs == \"function\" ? attrs(node) : attrs;\n if (node.isTextblock && !node.hasMarkup(type, attrsHere) &&\n canChangeType(tr.doc, tr.mapping.slice(mapFrom).map(pos), type)) {\n let convertNewlines = null;\n if (type.schema.linebreakReplacement) {\n let pre = type.whitespace == \"pre\", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement);\n if (pre && !supportLinebreak)\n convertNewlines = false;\n else if (!pre && supportLinebreak)\n convertNewlines = true;\n }\n // Ensure all markup that isn't allowed in the new node type is cleared\n if (convertNewlines === false)\n replaceLinebreaks(tr, node, pos, mapFrom);\n clearIncompatible(tr, tr.mapping.slice(mapFrom).map(pos, 1), type, undefined, convertNewlines === null);\n let mapping = tr.mapping.slice(mapFrom);\n let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1);\n tr.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0), 1, true));\n if (convertNewlines === true)\n replaceNewlines(tr, node, pos, mapFrom);\n return false;\n }\n });\n}\nfunction replaceNewlines(tr, node, pos, mapFrom) {\n node.forEach((child, offset) => {\n if (child.isText) {\n let m, newline = /\\r?\\n|\\r/g;\n while (m = newline.exec(child.text)) {\n let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset + m.index);\n tr.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create());\n }\n }\n });\n}\nfunction replaceLinebreaks(tr, node, pos, mapFrom) {\n node.forEach((child, offset) => {\n if (child.type == child.type.schema.linebreakReplacement) {\n let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset);\n tr.replaceWith(start, start + 1, node.type.schema.text(\"\\n\"));\n }\n });\n}\nfunction canChangeType(doc, pos, type) {\n let $pos = doc.resolve(pos), index = $pos.index();\n return $pos.parent.canReplaceWith(index, index + 1, type);\n}\n/**\nChange the type, attributes, and/or marks of the node at `pos`.\nWhen `type` isn't given, the existing node type is preserved,\n*/\nfunction setNodeMarkup(tr, pos, type, attrs, marks) {\n let node = tr.doc.nodeAt(pos);\n if (!node)\n throw new RangeError(\"No node at given position\");\n if (!type)\n type = node.type;\n let newNode = type.create(attrs, null, marks || node.marks);\n if (node.isLeaf)\n return tr.replaceWith(pos, pos + node.nodeSize, newNode);\n if (!type.validContent(node.content))\n throw new RangeError(\"Invalid content for node type \" + type.name);\n tr.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));\n}\n/**\nCheck whether splitting at the given position is allowed.\n*/\nfunction canSplit(doc, pos, depth = 1, typesAfter) {\n let $pos = doc.resolve(pos), base = $pos.depth - depth;\n let innerType = (typesAfter && typesAfter[typesAfter.length - 1]) || $pos.parent;\n if (base < 0 || $pos.parent.type.spec.isolating ||\n !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) ||\n !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount)))\n return false;\n for (let d = $pos.depth - 1, i = depth - 2; d > base; d--, i--) {\n let node = $pos.node(d), index = $pos.index(d);\n if (node.type.spec.isolating)\n return false;\n let rest = node.content.cutByIndex(index, node.childCount);\n let overrideChild = typesAfter && typesAfter[i + 1];\n if (overrideChild)\n rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs));\n let after = (typesAfter && typesAfter[i]) || node;\n if (!node.canReplace(index + 1, node.childCount) || !after.type.validContent(rest))\n return false;\n }\n let index = $pos.indexAfter(base);\n let baseType = typesAfter && typesAfter[0];\n return $pos.node(base).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base + 1).type);\n}\nfunction split(tr, pos, depth = 1, typesAfter) {\n let $pos = tr.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;\n for (let d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) {\n before = Fragment.from($pos.node(d).copy(before));\n let typeAfter = typesAfter && typesAfter[i];\n after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));\n }\n tr.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true));\n}\n/**\nTest whether the blocks before and after a given position can be\njoined.\n*/\nfunction canJoin(doc, pos) {\n let $pos = doc.resolve(pos), index = $pos.index();\n return joinable($pos.nodeBefore, $pos.nodeAfter) &&\n $pos.parent.canReplace(index, index + 1);\n}\nfunction canAppendWithSubstitutedLinebreaks(a, b) {\n if (!b.content.size)\n a.type.compatibleContent(b.type);\n let match = a.contentMatchAt(a.childCount);\n let { linebreakReplacement } = a.type.schema;\n for (let i = 0; i < b.childCount; i++) {\n let child = b.child(i);\n let type = child.type == linebreakReplacement ? a.type.schema.nodes.text : child.type;\n match = match.matchType(type);\n if (!match)\n return false;\n if (!a.type.allowsMarks(child.marks))\n return false;\n }\n return match.validEnd;\n}\nfunction joinable(a, b) {\n return !!(a && b && !a.isLeaf && canAppendWithSubstitutedLinebreaks(a, b));\n}\n/**\nFind an ancestor of the given position that can be joined to the\nblock before (or after if `dir` is positive). Returns the joinable\npoint, if any.\n*/\nfunction joinPoint(doc, pos, dir = -1) {\n let $pos = doc.resolve(pos);\n for (let d = $pos.depth;; d--) {\n let before, after, index = $pos.index(d);\n if (d == $pos.depth) {\n before = $pos.nodeBefore;\n after = $pos.nodeAfter;\n }\n else if (dir > 0) {\n before = $pos.node(d + 1);\n index++;\n after = $pos.node(d).maybeChild(index);\n }\n else {\n before = $pos.node(d).maybeChild(index - 1);\n after = $pos.node(d + 1);\n }\n if (before && !before.isTextblock && joinable(before, after) &&\n $pos.node(d).canReplace(index, index + 1))\n return pos;\n if (d == 0)\n break;\n pos = dir < 0 ? $pos.before(d) : $pos.after(d);\n }\n}\nfunction join(tr, pos, depth) {\n let convertNewlines = null;\n let { linebreakReplacement } = tr.doc.type.schema;\n let $before = tr.doc.resolve(pos - depth), beforeType = $before.node().type;\n if (linebreakReplacement && beforeType.inlineContent) {\n let pre = beforeType.whitespace == \"pre\";\n let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement);\n if (pre && !supportLinebreak)\n convertNewlines = false;\n else if (!pre && supportLinebreak)\n convertNewlines = true;\n }\n let mapFrom = tr.steps.length;\n if (convertNewlines === false) {\n let $after = tr.doc.resolve(pos + depth);\n replaceLinebreaks(tr, $after.node(), $after.before(), mapFrom);\n }\n if (beforeType.inlineContent)\n clearIncompatible(tr, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null);\n let mapping = tr.mapping.slice(mapFrom), start = mapping.map(pos - depth);\n tr.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true));\n if (convertNewlines === true) {\n let $full = tr.doc.resolve(start);\n replaceNewlines(tr, $full.node(), $full.before(), tr.steps.length);\n }\n return tr;\n}\n/**\nTry to find a point where a node of the given type can be inserted\nnear `pos`, by searching up the node hierarchy when `pos` itself\nisn't a valid place but is at the start or end of a node. Return\nnull if no position was found.\n*/\nfunction insertPoint(doc, pos, nodeType) {\n let $pos = doc.resolve(pos);\n if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType))\n return pos;\n if ($pos.parentOffset == 0)\n for (let d = $pos.depth - 1; d >= 0; d--) {\n let index = $pos.index(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType))\n return $pos.before(d + 1);\n if (index > 0)\n return null;\n }\n if ($pos.parentOffset == $pos.parent.content.size)\n for (let d = $pos.depth - 1; d >= 0; d--) {\n let index = $pos.indexAfter(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType))\n return $pos.after(d + 1);\n if (index < $pos.node(d).childCount)\n return null;\n }\n return null;\n}\n/**\nFinds a position at or around the given position where the given\nslice can be inserted. Will look at parent nodes' nearest boundary\nand try there, even if the original position wasn't directly at the\nstart or end of that node. Returns null when no position was found.\n*/\nfunction dropPoint(doc, pos, slice) {\n let $pos = doc.resolve(pos);\n if (!slice.content.size)\n return pos;\n let content = slice.content;\n for (let i = 0; i < slice.openStart; i++)\n content = content.firstChild.content;\n for (let pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) {\n for (let d = $pos.depth; d >= 0; d--) {\n let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1;\n let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0);\n let parent = $pos.node(d), fits = false;\n if (pass == 1) {\n fits = parent.canReplace(insertPos, insertPos, content);\n }\n else {\n let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type);\n fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]);\n }\n if (fits)\n return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1);\n }\n }\n return null;\n}\n\n/**\n‘Fit’ a slice into a given position in the document, producing a\n[step](https://prosemirror.net/docs/ref/#transform.Step) that inserts it. Will return null if\nthere's no meaningful way to insert the slice here, or inserting it\nwould be a no-op (an empty slice over an empty range).\n*/\nfunction replaceStep(doc, from, to = from, slice = Slice.empty) {\n if (from == to && !slice.size)\n return null;\n let $from = doc.resolve(from), $to = doc.resolve(to);\n // Optimization -- avoid work if it's obvious that it's not needed.\n if (fitsTrivially($from, $to, slice))\n return new ReplaceStep(from, to, slice);\n return new Fitter($from, $to, slice).fit();\n}\nfunction fitsTrivially($from, $to, slice) {\n return !slice.openStart && !slice.openEnd && $from.start() == $to.start() &&\n $from.parent.canReplace($from.index(), $to.index(), slice.content);\n}\n// Algorithm for 'placing' the elements of a slice into a gap:\n//\n// We consider the content of each node that is open to the left to be\n// independently placeable. I.e. in <p(\"foo\"), p(\"bar\")>, when the\n// paragraph on the left is open, \"foo\" can be placed (somewhere on\n// the left side of the replacement gap) independently from p(\"bar\").\n//\n// This class tracks the state of the placement progress in the\n// following properties:\n//\n// - `frontier` holds a stack of `{type, match}` objects that\n// represent the open side of the replacement. It starts at\n// `$from`, then moves forward as content is placed, and is finally\n// reconciled with `$to`.\n//\n// - `unplaced` is a slice that represents the content that hasn't\n// been placed yet.\n//\n// - `placed` is a fragment of placed content. Its open-start value\n// is implicit in `$from`, and its open-end value in `frontier`.\nclass Fitter {\n constructor($from, $to, unplaced) {\n this.$from = $from;\n this.$to = $to;\n this.unplaced = unplaced;\n this.frontier = [];\n this.placed = Fragment.empty;\n for (let i = 0; i <= $from.depth; i++) {\n let node = $from.node(i);\n this.frontier.push({\n type: node.type,\n match: node.contentMatchAt($from.indexAfter(i))\n });\n }\n for (let i = $from.depth; i > 0; i--)\n this.placed = Fragment.from($from.node(i).copy(this.placed));\n }\n get depth() { return this.frontier.length - 1; }\n fit() {\n // As long as there's unplaced content, try to place some of it.\n // If that fails, either increase the open score of the unplaced\n // slice, or drop nodes from it, and then try again.\n while (this.unplaced.size) {\n let fit = this.findFittable();\n if (fit)\n this.placeNodes(fit);\n else\n this.openMore() || this.dropNode();\n }\n // When there's inline content directly after the frontier _and_\n // directly after `this.$to`, we must generate a `ReplaceAround`\n // step that pulls that content into the node after the frontier.\n // That means the fitting must be done to the end of the textblock\n // node after `this.$to`, not `this.$to` itself.\n let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;\n let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));\n if (!$to)\n return null;\n // If closing to `$to` succeeded, create a step\n let content = this.placed, openStart = $from.depth, openEnd = $to.depth;\n while (openStart && openEnd && content.childCount == 1) { // Normalize by dropping open parent nodes\n content = content.firstChild.content;\n openStart--;\n openEnd--;\n }\n let slice = new Slice(content, openStart, openEnd);\n if (moveInline > -1)\n return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize);\n if (slice.size || $from.pos != this.$to.pos) // Don't generate no-op steps\n return new ReplaceStep($from.pos, $to.pos, slice);\n return null;\n }\n // Find a position on the start spine of `this.unplaced` that has\n // content that can be moved somewhere on the frontier. Returns two\n // depths, one for the slice and one for the frontier.\n findFittable() {\n let startDepth = this.unplaced.openStart;\n for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) {\n let node = cur.firstChild;\n if (cur.childCount > 1)\n openEnd = 0;\n if (node.type.spec.isolating && openEnd <= d) {\n startDepth = d;\n break;\n }\n cur = node.content;\n }\n // Only try wrapping nodes (pass 2) after finding a place without\n // wrapping failed.\n for (let pass = 1; pass <= 2; pass++) {\n for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {\n let fragment, parent = null;\n if (sliceDepth) {\n parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;\n fragment = parent.content;\n }\n else {\n fragment = this.unplaced.content;\n }\n let first = fragment.firstChild;\n for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {\n let { type, match } = this.frontier[frontierDepth], wrap, inject = null;\n // In pass 1, if the next node matches, or there is no next\n // node but the parents look compatible, we've found a\n // place.\n if (pass == 1 && (first ? match.matchType(first.type) || (inject = match.fillBefore(Fragment.from(first), false))\n : parent && type.compatibleContent(parent.type)))\n return { sliceDepth, frontierDepth, parent, inject };\n // In pass 2, look for a set of wrapping nodes that make\n // `first` fit here.\n else if (pass == 2 && first && (wrap = match.findWrapping(first.type)))\n return { sliceDepth, frontierDepth, parent, wrap };\n // Don't continue looking further up if the parent node\n // would fit here.\n if (parent && match.matchType(parent.type))\n break;\n }\n }\n }\n }\n openMore() {\n let { content, openStart, openEnd } = this.unplaced;\n if (maxOpen(content, -1) <= openStart)\n return false;\n if (this.unplaced.size > 1 && maxOpen(content, 1) > openEnd)\n openEnd++;\n this.unplaced = new Slice(content, openStart + 1, openEnd);\n return true;\n }\n dropNode() {\n let { content, openStart, openEnd } = this.unplaced;\n let inner = contentAt(content, openStart);\n if (inner.childCount <= 1 && openStart > 0) {\n let openAtEnd = content.size - openStart <= openStart + inner.size;\n this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);\n }\n else {\n this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);\n }\n }\n // Move content from the unplaced slice at `sliceDepth` to the\n // frontier node at `frontierDepth`. Close that frontier node when\n // applicable.\n placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap }) {\n while (this.depth > frontierDepth)\n this.closeFrontierNode();\n if (wrap)\n for (let i = 0; i < wrap.length; i++)\n this.openFrontierNode(wrap[i]);\n let slice = this.unplaced, fragment = parent ? parent.content : slice.content;\n let openStart = slice.openStart - sliceDepth;\n let taken = 0, add = [];\n let { match, type } = this.frontier[frontierDepth];\n if (inject) {\n for (let i = 0; i < inject.childCount; i++)\n add.push(inject.child(i));\n match = match.matchFragment(inject);\n }\n // Computes the amount of (end) open nodes at the end of the\n // fragment. When 0, the parent is open, but no more. When\n // negative, nothing is open.\n let openEndCount = (fragment.size + sliceDepth) - (slice.content.size - slice.openEnd);\n // Scan over the fragment, fitting as many child nodes as\n // possible.\n while (taken < fragment.childCount) {\n let next = fragment.child(taken), matches = match.matchType(next.type);\n if (!matches)\n break;\n taken++;\n if (taken > 1 || openStart == 0 || next.content.size) { // Drop empty open nodes\n match = matches;\n add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1));\n }\n }\n let toEnd = taken == fragment.childCount;\n if (!toEnd)\n openEndCount = -1;\n this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add));\n this.frontier[frontierDepth].match = match;\n // If the parent types match, and the entire node was moved, and\n // it's not open, close this frontier node right away.\n if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1)\n this.closeFrontierNode();\n // Add new frontier nodes for any open nodes at the end.\n for (let i = 0, cur = fragment; i < openEndCount; i++) {\n let node = cur.lastChild;\n this.frontier.push({ type: node.type, match: node.contentMatchAt(node.childCount) });\n cur = node.content;\n }\n // Update `this.unplaced`. Drop the entire node from which we\n // placed it we got to its end, otherwise just drop the placed\n // nodes.\n this.unplaced = !toEnd ? new Slice(dropFromFragment(slice.content, sliceDepth, taken), slice.openStart, slice.openEnd)\n : sliceDepth == 0 ? Slice.empty\n : new Slice(dropFromFragment(slice.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1);\n }\n mustMoveInline() {\n if (!this.$to.parent.isTextblock)\n return -1;\n let top = this.frontier[this.depth], level;\n if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) ||\n (this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth))\n return -1;\n let { depth } = this.$to, after = this.$to.after(depth);\n while (depth > 1 && after == this.$to.end(--depth))\n ++after;\n return after;\n }\n findCloseLevel($to) {\n scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) {\n let { match, type } = this.frontier[i];\n let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1));\n let fit = contentAfterFits($to, i, type, match, dropInner);\n if (!fit)\n continue;\n for (let d = i - 1; d >= 0; d--) {\n let { match, type } = this.frontier[d];\n let matches = contentAfterFits($to, d, type, match, true);\n if (!matches || matches.childCount)\n continue scan;\n }\n return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to };\n }\n }\n close($to) {\n let close = this.findCloseLevel($to);\n if (!close)\n return null;\n while (this.depth > close.depth)\n this.closeFrontierNode();\n if (close.fit.childCount)\n this.placed = addToFragment(this.placed, close.depth, close.fit);\n $to = close.move;\n for (let d = close.depth + 1; d <= $to.depth; d++) {\n let node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d));\n this.openFrontierNode(node.type, node.attrs, add);\n }\n return $to;\n }\n openFrontierNode(type, attrs = null, content) {\n let top = this.frontier[this.depth];\n top.match = top.match.matchType(type);\n this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content)));\n this.frontier.push({ type, match: type.contentMatch });\n }\n closeFrontierNode() {\n let open = this.frontier.pop();\n let add = open.match.fillBefore(Fragment.empty, true);\n if (add.childCount)\n this.placed = addToFragment(this.placed, this.frontier.length, add);\n }\n}\nfunction dropFromFragment(fragment, depth, count) {\n if (depth == 0)\n return fragment.cutByIndex(count, fragment.childCount);\n return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)));\n}\nfunction addToFragment(fragment, depth, content) {\n if (depth == 0)\n return fragment.append(content);\n return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)));\n}\nfunction contentAt(fragment, depth) {\n for (let i = 0; i < depth; i++)\n fragment = fragment.firstChild.content;\n return fragment;\n}\nfunction closeNodeStart(node, openStart, openEnd) {\n if (openStart <= 0)\n return node;\n let frag = node.content;\n if (openStart > 1)\n frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));\n if (openStart > 0) {\n frag = node.type.contentMatch.fillBefore(frag).append(frag);\n if (openEnd <= 0)\n frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));\n }\n return node.copy(frag);\n}\nfunction contentAfterFits($to, depth, type, match, open) {\n let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth);\n if (index == node.childCount && !type.compatibleContent(node.type))\n return null;\n let fit = match.fillBefore(node.content, true, index);\n return fit && !invalidMarks(type, node.content, index) ? fit : null;\n}\nfunction invalidMarks(type, fragment, start) {\n for (let i = start; i < fragment.childCount; i++)\n if (!type.allowsMarks(fragment.child(i).marks))\n return true;\n return false;\n}\nfunction definesContent(type) {\n return type.spec.defining || type.spec.definingForContent;\n}\nfunction maxOpen(frag, side) {\n for (let count = 0;; count++) {\n let ch = side < 0 ? frag.firstChild : frag.lastChild;\n if (!ch || ch.isAtom)\n return count;\n frag = ch.content;\n }\n}\nfunction replaceRange(tr, from, to, slice) {\n if (!slice.size)\n return tr.deleteRange(from, to);\n let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n if (fitsTrivially($from, $to, slice))\n return tr.step(new ReplaceStep(from, to, slice));\n let targetDepths = coveredDepths($from, $to);\n // Can't replace the whole document, so remove 0 if it's present\n if (targetDepths[targetDepths.length - 1] == 0)\n targetDepths.pop();\n // Negative numbers represent not expansion over the whole node at\n // that depth, but replacing from $from.before(-D) to $to.pos.\n let preferredTarget = -($from.depth + 1);\n targetDepths.unshift(preferredTarget);\n // This loop picks a preferred target depth, if one of the covering\n // depths is not outside of a defining node, and adds negative\n // depths for any depth that has $from at its start and does not\n // cross a defining node.\n for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {\n let spec = $from.node(d).type.spec;\n if (spec.defining || spec.definingAsContext || spec.isolating)\n break;\n if (targetDepths.indexOf(d) > -1)\n preferredTarget = d;\n else if ($from.before(d) == pos)\n targetDepths.splice(1, 0, -d);\n }\n // Try to fit each possible depth of the slice into each possible\n // target depth, starting with the preferred depths.\n let preferredTargetIndex = targetDepths.indexOf(preferredTarget);\n let leftNodes = [], preferredDepth = slice.openStart;\n for (let content = slice.content, i = 0;; i++) {\n let node = content.firstChild;\n leftNodes.push(node);\n if (i == slice.openStart)\n break;\n content = node.content;\n }\n // Back up preferredDepth to cover defining textblocks directly\n // above it, possibly skipping a non-defining textblock.\n for (let d = preferredDepth - 1; d >= 0; d--) {\n let leftNode = leftNodes[d], def = definesContent(leftNode.type);\n if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1)))\n preferredDepth = d;\n else if (def || !leftNode.type.isTextblock)\n break;\n }\n for (let j = slice.openStart; j >= 0; j--) {\n let openDepth = (j + preferredDepth + 1) % (slice.openStart + 1);\n let insert = leftNodes[openDepth];\n if (!insert)\n continue;\n for (let i = 0; i < targetDepths.length; i++) {\n // Loop over possible expansion levels, starting with the\n // preferred one\n let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true;\n if (targetDepth < 0) {\n expand = false;\n targetDepth = -targetDepth;\n }\n let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1);\n if (parent.canReplaceWith(index, index, insert.type, insert.marks))\n return tr.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth), openDepth, slice.openEnd));\n }\n }\n let startSteps = tr.steps.length;\n for (let i = targetDepths.length - 1; i >= 0; i--) {\n tr.replace(from, to, slice);\n if (tr.steps.length > startSteps)\n break;\n let depth = targetDepths[i];\n if (depth < 0)\n continue;\n from = $from.before(depth);\n to = $to.after(depth);\n }\n}\nfunction closeFragment(fragment, depth, oldOpen, newOpen, parent) {\n if (depth < oldOpen) {\n let first = fragment.firstChild;\n fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));\n }\n if (depth > newOpen) {\n let match = parent.contentMatchAt(0);\n let start = match.fillBefore(fragment).append(fragment);\n fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true));\n }\n return fragment;\n}\nfunction replaceRangeWith(tr, from, to, node) {\n if (!node.isInline && from == to && tr.doc.resolve(from).parent.content.size) {\n let point = insertPoint(tr.doc, from, node.type);\n if (point != null)\n from = to = point;\n }\n tr.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0));\n}\nfunction deleteRange(tr, from, to) {\n let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n // When the deleted range spans from the start of one textblock to\n // the start of another one, move out of the start of both blocks.\n if ($from.parent.isTextblock && $to.parent.isTextblock && $from.start() != $to.start() &&\n $from.parentOffset == 0 && $to.parentOffset == 0) {\n let shared = $from.sharedDepth(to), isolated = false;\n for (let d = $from.depth; d > shared; d--)\n if ($from.node(d).type.spec.isolating)\n isolated = true;\n for (let d = $to.depth; d > shared; d--)\n if ($to.node(d).type.spec.isolating)\n isolated = true;\n if (!isolated) {\n for (let d = $from.depth; d > 0 && from == $from.start(d); d--)\n from = $from.before(d);\n for (let d = $to.depth; d > 0 && to == $to.start(d); d--)\n to = $to.before(d);\n $from = tr.doc.resolve(from);\n $to = tr.doc.resolve(to);\n }\n }\n let covered = coveredDepths($from, $to);\n for (let i = 0; i < covered.length; i++) {\n let depth = covered[i], last = i == covered.length - 1;\n if ((last && depth == 0) || $from.node(depth).type.contentMatch.validEnd)\n return tr.delete($from.start(depth), $to.end(depth));\n if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))\n return tr.delete($from.before(depth), $to.after(depth));\n }\n for (let d = 1; d <= $from.depth && d <= $to.depth; d++) {\n if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d &&\n $from.start(d - 1) == $to.start(d - 1) && $from.node(d - 1).canReplace($from.index(d - 1), $to.index(d - 1)))\n return tr.delete($from.before(d), to);\n }\n tr.delete(from, to);\n}\n// Returns an array of all depths for which $from - $to spans the\n// whole content of the nodes at that depth.\nfunction coveredDepths($from, $to) {\n let result = [], minDepth = Math.min($from.depth, $to.depth);\n for (let d = minDepth; d >= 0; d--) {\n let start = $from.start(d);\n if (start < $from.pos - ($from.depth - d) ||\n $to.end(d) > $to.pos + ($to.depth - d) ||\n $from.node(d).type.spec.isolating ||\n $to.node(d).type.spec.isolating)\n break;\n if (start == $to.start(d) ||\n (d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent &&\n d && $to.start(d - 1) == start - 1))\n result.push(d);\n }\n return result;\n}\n\n/**\nUpdate an attribute in a specific node.\n*/\nclass AttrStep extends Step {\n /**\n Construct an attribute step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The attribute to set.\n */\n attr, \n // The attribute's new value.\n value) {\n super();\n this.pos = pos;\n this.attr = attr;\n this.value = value;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at attribute step's position\");\n let attrs = Object.create(null);\n for (let name in node.attrs)\n attrs[name] = node.attrs[name];\n attrs[this.attr] = this.value;\n let updated = node.type.create(attrs, null, node.marks);\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n getMap() {\n return StepMap.empty;\n }\n invert(doc) {\n return new AttrStep(this.pos, this.attr, doc.nodeAt(this.pos).attrs[this.attr]);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value);\n }\n toJSON() {\n return { stepType: \"attr\", pos: this.pos, attr: this.attr, value: this.value };\n }\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\" || typeof json.attr != \"string\")\n throw new RangeError(\"Invalid input for AttrStep.fromJSON\");\n return new AttrStep(json.pos, json.attr, json.value);\n }\n}\nStep.jsonID(\"attr\", AttrStep);\n/**\nUpdate an attribute in the doc node.\n*/\nclass DocAttrStep extends Step {\n /**\n Construct an attribute step.\n */\n constructor(\n /**\n The attribute to set.\n */\n attr, \n // The attribute's new value.\n value) {\n super();\n this.attr = attr;\n this.value = value;\n }\n apply(doc) {\n let attrs = Object.create(null);\n for (let name in doc.attrs)\n attrs[name] = doc.attrs[name];\n attrs[this.attr] = this.value;\n let updated = doc.type.create(attrs, doc.content, doc.marks);\n return StepResult.ok(updated);\n }\n getMap() {\n return StepMap.empty;\n }\n invert(doc) {\n return new DocAttrStep(this.attr, doc.attrs[this.attr]);\n }\n map(mapping) {\n return this;\n }\n toJSON() {\n return { stepType: \"docAttr\", attr: this.attr, value: this.value };\n }\n static fromJSON(schema, json) {\n if (typeof json.attr != \"string\")\n throw new RangeError(\"Invalid input for DocAttrStep.fromJSON\");\n return new DocAttrStep(json.attr, json.value);\n }\n}\nStep.jsonID(\"docAttr\", DocAttrStep);\n\n/**\n@internal\n*/\nlet TransformError = class extends Error {\n};\nTransformError = function TransformError(message) {\n let err = Error.call(this, message);\n err.__proto__ = TransformError.prototype;\n return err;\n};\nTransformError.prototype = Object.create(Error.prototype);\nTransformError.prototype.constructor = TransformError;\nTransformError.prototype.name = \"TransformError\";\n/**\nAbstraction to build up and track an array of\n[steps](https://prosemirror.net/docs/ref/#transform.Step) representing a document transformation.\n\nMost transforming methods return the `Transform` object itself, so\nthat they can be chained.\n*/\nclass Transform {\n /**\n Create a transform that starts with the given document.\n */\n constructor(\n /**\n The current document (the result of applying the steps in the\n transform).\n */\n doc) {\n this.doc = doc;\n /**\n The steps in this transform.\n */\n this.steps = [];\n /**\n The documents before each of the steps.\n */\n this.docs = [];\n /**\n A mapping with the maps for each of the steps in this transform.\n */\n this.mapping = new Mapping;\n }\n /**\n The starting document.\n */\n get before() { return this.docs.length ? this.docs[0] : this.doc; }\n /**\n Apply a new step in this transform, saving the result. Throws an\n error when the step fails.\n */\n step(step) {\n let result = this.maybeStep(step);\n if (result.failed)\n throw new TransformError(result.failed);\n return this;\n }\n /**\n Try to apply a step in this transformation, ignoring it if it\n fails. Returns the step result.\n */\n maybeStep(step) {\n let result = step.apply(this.doc);\n if (!result.failed)\n this.addStep(step, result.doc);\n return result;\n }\n /**\n True when the document has been changed (when there are any\n steps).\n */\n get docChanged() {\n return this.steps.length > 0;\n }\n /**\n Return a single range, in post-transform document positions,\n that covers all content changed by this transform. Returns null\n if no replacements are made. Note that this will ignore changes\n that add/remove marks without replacing the underlying content.\n */\n changedRange() {\n let from = 1e9, to = -1e9;\n for (let i = 0; i < this.mapping.maps.length; i++) {\n let map = this.mapping.maps[i];\n if (i) {\n from = map.map(from, 1);\n to = map.map(to, -1);\n }\n map.forEach((_f, _t, fromB, toB) => {\n from = Math.min(from, fromB);\n to = Math.max(to, toB);\n });\n }\n return from == 1e9 ? null : { from, to };\n }\n /**\n @internal\n */\n addStep(step, doc) {\n this.docs.push(this.doc);\n this.steps.push(step);\n this.mapping.appendMap(step.getMap());\n this.doc = doc;\n }\n /**\n Replace the part of the document between `from` and `to` with the\n given `slice`.\n */\n replace(from, to = from, slice = Slice.empty) {\n let step = replaceStep(this.doc, from, to, slice);\n if (step)\n this.step(step);\n return this;\n }\n /**\n Replace the given range with the given content, which may be a\n fragment, node, or array of nodes.\n */\n replaceWith(from, to, content) {\n return this.replace(from, to, new Slice(Fragment.from(content), 0, 0));\n }\n /**\n Delete the content between the given positions.\n */\n delete(from, to) {\n return this.replace(from, to, Slice.empty);\n }\n /**\n Insert the given content at the given position.\n */\n insert(pos, content) {\n return this.replaceWith(pos, pos, content);\n }\n /**\n Replace a range of the document with a given slice, using\n `from`, `to`, and the slice's\n [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather\n than fixed start and end points. This method may grow the\n replaced area or close open nodes in the slice in order to get a\n fit that is more in line with WYSIWYG expectations, by dropping\n fully covered parent nodes of the replaced region when they are\n marked [non-defining as\n context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an\n open parent node from the slice that _is_ marked as [defining\n its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).\n \n This is the method, for example, to handle paste. The similar\n [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more\n primitive tool which will _not_ move the start and end of its given\n range, and is useful in situations where you need more precise\n control over what happens.\n */\n replaceRange(from, to, slice) {\n replaceRange(this, from, to, slice);\n return this;\n }\n /**\n Replace the given range with a node, but use `from` and `to` as\n hints, rather than precise positions. When from and to are the same\n and are at the start or end of a parent node in which the given\n node doesn't fit, this method may _move_ them out towards a parent\n that does allow the given node to be placed. When the given range\n completely covers a parent node, this method may completely replace\n that parent node.\n */\n replaceRangeWith(from, to, node) {\n replaceRangeWith(this, from, to, node);\n return this;\n }\n /**\n Delete the given range, expanding it to cover fully covered\n parent nodes until a valid replace is found.\n */\n deleteRange(from, to) {\n deleteRange(this, from, to);\n return this;\n }\n /**\n Split the content in the given range off from its parent, if there\n is sibling content before or after it, and move it up the tree to\n the depth specified by `target`. You'll probably want to use\n [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make\n sure the lift is valid.\n */\n lift(range, target) {\n lift(this, range, target);\n return this;\n }\n /**\n Join the blocks around the given position. If depth is 2, their\n last and first siblings are also joined, and so on.\n */\n join(pos, depth = 1) {\n join(this, pos, depth);\n return this;\n }\n /**\n Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers.\n The wrappers are assumed to be valid in this position, and should\n probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping).\n */\n wrap(range, wrappers) {\n wrap(this, range, wrappers);\n return this;\n }\n /**\n Set the type of all textblocks (partly) between `from` and `to` to\n the given node type with the given attributes.\n */\n setBlockType(from, to = from, type, attrs = null) {\n setBlockType(this, from, to, type, attrs);\n return this;\n }\n /**\n Change the type, attributes, and/or marks of the node at `pos`.\n When `type` isn't given, the existing node type is preserved,\n */\n setNodeMarkup(pos, type, attrs = null, marks) {\n setNodeMarkup(this, pos, type, attrs, marks);\n return this;\n }\n /**\n Set a single attribute on a given node to a new value.\n The `pos` addresses the document content. Use `setDocAttribute`\n to set attributes on the document itself.\n */\n setNodeAttribute(pos, attr, value) {\n this.step(new AttrStep(pos, attr, value));\n return this;\n }\n /**\n Set a single attribute on the document to a new value.\n */\n setDocAttribute(attr, value) {\n this.step(new DocAttrStep(attr, value));\n return this;\n }\n /**\n Add a mark to the node at position `pos`.\n */\n addNodeMark(pos, mark) {\n this.step(new AddNodeMarkStep(pos, mark));\n return this;\n }\n /**\n Remove a mark (or all marks of the given type) from the node at\n position `pos`.\n */\n removeNodeMark(pos, mark) {\n let node = this.doc.nodeAt(pos);\n if (!node)\n throw new RangeError(\"No node at position \" + pos);\n if (mark instanceof Mark) {\n if (mark.isInSet(node.marks))\n this.step(new RemoveNodeMarkStep(pos, mark));\n }\n else {\n let set = node.marks, found, steps = [];\n while (found = mark.isInSet(set)) {\n steps.push(new RemoveNodeMarkStep(pos, found));\n set = found.removeFromSet(set);\n }\n for (let i = steps.length - 1; i >= 0; i--)\n this.step(steps[i]);\n }\n return this;\n }\n /**\n Split the node at the given position, and optionally, if `depth` is\n greater than one, any number of nodes above that. By default, the\n parts split off will inherit the node type of the original node.\n This can be changed by passing an array of types and attributes to\n use after the split (with the outermost nodes coming first).\n */\n split(pos, depth = 1, typesAfter) {\n split(this, pos, depth, typesAfter);\n return this;\n }\n /**\n Add the given mark to the inline content between `from` and `to`.\n */\n addMark(from, to, mark) {\n addMark(this, from, to, mark);\n return this;\n }\n /**\n Remove marks from inline nodes between `from` and `to`. When\n `mark` is a single mark, remove precisely that mark. When it is\n a mark type, remove all marks of that type. When it is null,\n remove all marks of any type.\n */\n removeMark(from, to, mark) {\n removeMark(this, from, to, mark);\n return this;\n }\n /**\n Removes all marks and nodes from the content of the node at\n `pos` that don't match the given new parent node type. Accepts\n an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as\n third argument.\n */\n clearIncompatible(pos, parentType, match) {\n clearIncompatible(this, pos, parentType, match);\n return this;\n }\n}\n\nexport { AddMarkStep, AddNodeMarkStep, AttrStep, DocAttrStep, MapResult, Mapping, RemoveMarkStep, RemoveNodeMarkStep, ReplaceAroundStep, ReplaceStep, Step, StepMap, StepResult, Transform, TransformError, canJoin, canSplit, dropPoint, findWrapping, insertPoint, joinPoint, liftTarget, replaceStep };\n","import { Slice, Fragment, Mark, Node } from 'prosemirror-model';\nimport { ReplaceStep, ReplaceAroundStep, Transform } from 'prosemirror-transform';\n\nconst classesById = Object.create(null);\n/**\nSuperclass for editor selections. Every selection type should\nextend this. Should not be instantiated directly.\n*/\nclass Selection {\n /**\n Initialize a selection with the head and anchor and ranges. If no\n ranges are given, constructs a single range across `$anchor` and\n `$head`.\n */\n constructor(\n /**\n The resolved anchor of the selection (the side that stays in\n place when the selection is modified).\n */\n $anchor, \n /**\n The resolved head of the selection (the side that moves when\n the selection is modified).\n */\n $head, ranges) {\n this.$anchor = $anchor;\n this.$head = $head;\n this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];\n }\n /**\n The selection's anchor, as an unresolved position.\n */\n get anchor() { return this.$anchor.pos; }\n /**\n The selection's head.\n */\n get head() { return this.$head.pos; }\n /**\n The lower bound of the selection's main range.\n */\n get from() { return this.$from.pos; }\n /**\n The upper bound of the selection's main range.\n */\n get to() { return this.$to.pos; }\n /**\n The resolved lower bound of the selection's main range.\n */\n get $from() {\n return this.ranges[0].$from;\n }\n /**\n The resolved upper bound of the selection's main range.\n */\n get $to() {\n return this.ranges[0].$to;\n }\n /**\n Indicates whether the selection contains any content.\n */\n get empty() {\n let ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++)\n if (ranges[i].$from.pos != ranges[i].$to.pos)\n return false;\n return true;\n }\n /**\n Get the content of this selection as a slice.\n */\n content() {\n return this.$from.doc.slice(this.from, this.to, true);\n }\n /**\n Replace the selection with a slice or, if no slice is given,\n delete the selection. Will append to the given transaction.\n */\n replace(tr, content = Slice.empty) {\n // Put the new selection at the position after the inserted\n // content. When that ended in an inline node, search backwards,\n // to get the position after that node. If not, search forward.\n let lastNode = content.content.lastChild, lastParent = null;\n for (let i = 0; i < content.openEnd; i++) {\n lastParent = lastNode;\n lastNode = lastNode.lastChild;\n }\n let mapFrom = tr.steps.length, ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content);\n if (i == 0)\n selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);\n }\n }\n /**\n Replace the selection with the given node, appending the changes\n to the given transaction.\n */\n replaceWith(tr, node) {\n let mapFrom = tr.steps.length, ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n let from = mapping.map($from.pos), to = mapping.map($to.pos);\n if (i) {\n tr.deleteRange(from, to);\n }\n else {\n tr.replaceRangeWith(from, to, node);\n selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1);\n }\n }\n }\n /**\n Find a valid cursor or leaf node selection starting at the given\n position and searching back if `dir` is negative, and forward if\n positive. When `textOnly` is true, only consider cursor\n selections. Will return null when no valid selection position is\n found.\n */\n static findFrom($pos, dir, textOnly = false) {\n let inner = $pos.parent.inlineContent ? new TextSelection($pos)\n : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);\n if (inner)\n return inner;\n for (let depth = $pos.depth - 1; depth >= 0; depth--) {\n let found = dir < 0\n ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly)\n : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);\n if (found)\n return found;\n }\n return null;\n }\n /**\n Find a valid cursor or leaf node selection near the given\n position. Searches forward first by default, but if `bias` is\n negative, it will search backwards first.\n */\n static near($pos, bias = 1) {\n return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));\n }\n /**\n Find the cursor or leaf node selection closest to the start of\n the given document. Will return an\n [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position\n exists.\n */\n static atStart(doc) {\n return findSelectionIn(doc, doc, 0, 0, 1) || new AllSelection(doc);\n }\n /**\n Find the cursor or leaf node selection closest to the end of the\n given document.\n */\n static atEnd(doc) {\n return findSelectionIn(doc, doc, doc.content.size, doc.childCount, -1) || new AllSelection(doc);\n }\n /**\n Deserialize the JSON representation of a selection. Must be\n implemented for custom classes (as a static class method).\n */\n static fromJSON(doc, json) {\n if (!json || !json.type)\n throw new RangeError(\"Invalid input for Selection.fromJSON\");\n let cls = classesById[json.type];\n if (!cls)\n throw new RangeError(`No selection type ${json.type} defined`);\n return cls.fromJSON(doc, json);\n }\n /**\n To be able to deserialize selections from JSON, custom selection\n classes must register themselves with an ID string, so that they\n can be disambiguated. Try to pick something that's unlikely to\n clash with classes from other modules.\n */\n static jsonID(id, selectionClass) {\n if (id in classesById)\n throw new RangeError(\"Duplicate use of selection JSON ID \" + id);\n classesById[id] = selectionClass;\n selectionClass.prototype.jsonID = id;\n return selectionClass;\n }\n /**\n Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection,\n which is a value that can be mapped without having access to a\n current document, and later resolved to a real selection for a\n given document again. (This is used mostly by the history to\n track and restore old selections.) The default implementation of\n this method just converts the selection to a text selection and\n returns the bookmark for that.\n */\n getBookmark() {\n return TextSelection.between(this.$anchor, this.$head).getBookmark();\n }\n}\nSelection.prototype.visible = true;\n/**\nRepresents a selected range in a document.\n*/\nclass SelectionRange {\n /**\n Create a range.\n */\n constructor(\n /**\n The lower bound of the range.\n */\n $from, \n /**\n The upper bound of the range.\n */\n $to) {\n this.$from = $from;\n this.$to = $to;\n }\n}\nlet warnedAboutTextSelection = false;\nfunction checkTextSelection($pos) {\n if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {\n warnedAboutTextSelection = true;\n console[\"warn\"](\"TextSelection endpoint not pointing into a node with inline content (\" + $pos.parent.type.name + \")\");\n }\n}\n/**\nA text selection represents a classical editor selection, with a\nhead (the moving side) and anchor (immobile side), both of which\npoint into textblock nodes. It can be empty (a regular cursor\nposition).\n*/\nclass TextSelection extends Selection {\n /**\n Construct a text selection between the given points.\n */\n constructor($anchor, $head = $anchor) {\n checkTextSelection($anchor);\n checkTextSelection($head);\n super($anchor, $head);\n }\n /**\n Returns a resolved position if this is a cursor selection (an\n empty text selection), and null otherwise.\n */\n get $cursor() { return this.$anchor.pos == this.$head.pos ? this.$head : null; }\n map(doc, mapping) {\n let $head = doc.resolve(mapping.map(this.head));\n if (!$head.parent.inlineContent)\n return Selection.near($head);\n let $anchor = doc.resolve(mapping.map(this.anchor));\n return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);\n }\n replace(tr, content = Slice.empty) {\n super.replace(tr, content);\n if (content == Slice.empty) {\n let marks = this.$from.marksAcross(this.$to);\n if (marks)\n tr.ensureMarks(marks);\n }\n }\n eq(other) {\n return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head;\n }\n getBookmark() {\n return new TextBookmark(this.anchor, this.head);\n }\n toJSON() {\n return { type: \"text\", anchor: this.anchor, head: this.head };\n }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.anchor != \"number\" || typeof json.head != \"number\")\n throw new RangeError(\"Invalid input for TextSelection.fromJSON\");\n return new TextSelection(doc.resolve(json.anchor), doc.resolve(json.head));\n }\n /**\n Create a text selection from non-resolved positions.\n */\n static create(doc, anchor, head = anchor) {\n let $anchor = doc.resolve(anchor);\n return new this($anchor, head == anchor ? $anchor : doc.resolve(head));\n }\n /**\n Return a text selection that spans the given positions or, if\n they aren't text positions, find a text selection near them.\n `bias` determines whether the method searches forward (default)\n or backwards (negative number) first. Will fall back to calling\n [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document\n doesn't contain a valid text position.\n */\n static between($anchor, $head, bias) {\n let dPos = $anchor.pos - $head.pos;\n if (!bias || dPos)\n bias = dPos >= 0 ? 1 : -1;\n if (!$head.parent.inlineContent) {\n let found = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);\n if (found)\n $head = found.$head;\n else\n return Selection.near($head, bias);\n }\n if (!$anchor.parent.inlineContent) {\n if (dPos == 0) {\n $anchor = $head;\n }\n else {\n $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;\n if (($anchor.pos < $head.pos) != (dPos < 0))\n $anchor = $head;\n }\n }\n return new TextSelection($anchor, $head);\n }\n}\nSelection.jsonID(\"text\", TextSelection);\nclass TextBookmark {\n constructor(anchor, head) {\n this.anchor = anchor;\n this.head = head;\n }\n map(mapping) {\n return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head));\n }\n resolve(doc) {\n return TextSelection.between(doc.resolve(this.anchor), doc.resolve(this.head));\n }\n}\n/**\nA node selection is a selection that points at a single node. All\nnodes marked [selectable](https://prosemirror.net/docs/ref/#model.NodeSpec.selectable) can be the\ntarget of a node selection. In such a selection, `from` and `to`\npoint directly before and after the selected node, `anchor` equals\n`from`, and `head` equals `to`..\n*/\nclass NodeSelection extends Selection {\n /**\n Create a node selection. Does not verify the validity of its\n argument.\n */\n constructor($pos) {\n let node = $pos.nodeAfter;\n let $end = $pos.node(0).resolve($pos.pos + node.nodeSize);\n super($pos, $end);\n this.node = node;\n }\n map(doc, mapping) {\n let { deleted, pos } = mapping.mapResult(this.anchor);\n let $pos = doc.resolve(pos);\n if (deleted)\n return Selection.near($pos);\n return new NodeSelection($pos);\n }\n content() {\n return new Slice(Fragment.from(this.node), 0, 0);\n }\n eq(other) {\n return other instanceof NodeSelection && other.anchor == this.anchor;\n }\n toJSON() {\n return { type: \"node\", anchor: this.anchor };\n }\n getBookmark() { return new NodeBookmark(this.anchor); }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.anchor != \"number\")\n throw new RangeError(\"Invalid input for NodeSelection.fromJSON\");\n return new NodeSelection(doc.resolve(json.anchor));\n }\n /**\n Create a node selection from non-resolved positions.\n */\n static create(doc, from) {\n return new NodeSelection(doc.resolve(from));\n }\n /**\n Determines whether the given node may be selected as a node\n selection.\n */\n static isSelectable(node) {\n return !node.isText && node.type.spec.selectable !== false;\n }\n}\nNodeSelection.prototype.visible = false;\nSelection.jsonID(\"node\", NodeSelection);\nclass NodeBookmark {\n constructor(anchor) {\n this.anchor = anchor;\n }\n map(mapping) {\n let { deleted, pos } = mapping.mapResult(this.anchor);\n return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos);\n }\n resolve(doc) {\n let $pos = doc.resolve(this.anchor), node = $pos.nodeAfter;\n if (node && NodeSelection.isSelectable(node))\n return new NodeSelection($pos);\n return Selection.near($pos);\n }\n}\n/**\nA selection type that represents selecting the whole document\n(which can not necessarily be expressed with a text selection, when\nthere are for example leaf block nodes at the start or end of the\ndocument).\n*/\nclass AllSelection extends Selection {\n /**\n Create an all-selection over the given document.\n */\n constructor(doc) {\n super(doc.resolve(0), doc.resolve(doc.content.size));\n }\n replace(tr, content = Slice.empty) {\n if (content == Slice.empty) {\n tr.delete(0, tr.doc.content.size);\n let sel = Selection.atStart(tr.doc);\n if (!sel.eq(tr.selection))\n tr.setSelection(sel);\n }\n else {\n super.replace(tr, content);\n }\n }\n toJSON() { return { type: \"all\" }; }\n /**\n @internal\n */\n static fromJSON(doc) { return new AllSelection(doc); }\n map(doc) { return new AllSelection(doc); }\n eq(other) { return other instanceof AllSelection; }\n getBookmark() { return AllBookmark; }\n}\nSelection.jsonID(\"all\", AllSelection);\nconst AllBookmark = {\n map() { return this; },\n resolve(doc) { return new AllSelection(doc); }\n};\n// FIXME we'll need some awareness of text direction when scanning for selections\n// Try to find a selection inside the given node. `pos` points at the\n// position where the search starts. When `text` is true, only return\n// text selections.\nfunction findSelectionIn(doc, node, pos, index, dir, text = false) {\n if (node.inlineContent)\n return TextSelection.create(doc, pos);\n for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {\n let child = node.child(i);\n if (!child.isAtom) {\n let inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text);\n if (inner)\n return inner;\n }\n else if (!text && NodeSelection.isSelectable(child)) {\n return NodeSelection.create(doc, pos - (dir < 0 ? child.nodeSize : 0));\n }\n pos += child.nodeSize * dir;\n }\n return null;\n}\nfunction selectionToInsertionEnd(tr, startLen, bias) {\n let last = tr.steps.length - 1;\n if (last < startLen)\n return;\n let step = tr.steps[last];\n if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep))\n return;\n let map = tr.mapping.maps[last], end;\n map.forEach((_from, _to, _newFrom, newTo) => { if (end == null)\n end = newTo; });\n tr.setSelection(Selection.near(tr.doc.resolve(end), bias));\n}\n\nconst UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4;\n/**\nAn editor state transaction, which can be applied to a state to\ncreate an updated state. Use\n[`EditorState.tr`](https://prosemirror.net/docs/ref/#state.EditorState.tr) to create an instance.\n\nTransactions track changes to the document (they are a subclass of\n[`Transform`](https://prosemirror.net/docs/ref/#transform.Transform)), but also other state changes,\nlike selection updates and adjustments of the set of [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks). In addition, you can store\nmetadata properties in a transaction, which are extra pieces of\ninformation that client code or plugins can use to describe what a\ntransaction represents, so that they can update their [own\nstate](https://prosemirror.net/docs/ref/#state.StateField) accordingly.\n\nThe [editor view](https://prosemirror.net/docs/ref/#view.EditorView) uses a few metadata\nproperties: it will attach a property `\"pointer\"` with the value\n`true` to selection transactions directly caused by mouse or touch\ninput, a `\"composition\"` property holding an ID identifying the\ncomposition that caused it to transactions caused by composed DOM\ninput, and a `\"uiEvent\"` property of that may be `\"paste\"`,\n`\"cut\"`, or `\"drop\"`.\n*/\nclass Transaction extends Transform {\n /**\n @internal\n */\n constructor(state) {\n super(state.doc);\n // The step count for which the current selection is valid.\n this.curSelectionFor = 0;\n // Bitfield to track which aspects of the state were updated by\n // this transaction.\n this.updated = 0;\n // Object used to store metadata properties for the transaction.\n this.meta = Object.create(null);\n this.time = Date.now();\n this.curSelection = state.selection;\n this.storedMarks = state.storedMarks;\n }\n /**\n The transaction's current selection. This defaults to the editor\n selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the\n transaction, but can be overwritten with\n [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection).\n */\n get selection() {\n if (this.curSelectionFor < this.steps.length) {\n this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));\n this.curSelectionFor = this.steps.length;\n }\n return this.curSelection;\n }\n /**\n Update the transaction's current selection. Will determine the\n selection that the editor gets when the transaction is applied.\n */\n setSelection(selection) {\n if (selection.$from.doc != this.doc)\n throw new RangeError(\"Selection passed to setSelection must point at the current document\");\n this.curSelection = selection;\n this.curSelectionFor = this.steps.length;\n this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;\n this.storedMarks = null;\n return this;\n }\n /**\n Whether the selection was explicitly updated by this transaction.\n */\n get selectionSet() {\n return (this.updated & UPDATED_SEL) > 0;\n }\n /**\n Set the current stored marks.\n */\n setStoredMarks(marks) {\n this.storedMarks = marks;\n this.updated |= UPDATED_MARKS;\n return this;\n }\n /**\n Make sure the current stored marks or, if that is null, the marks\n at the selection, match the given set of marks. Does nothing if\n this is already the case.\n */\n ensureMarks(marks) {\n if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))\n this.setStoredMarks(marks);\n return this;\n }\n /**\n Add a mark to the set of stored marks.\n */\n addStoredMark(mark) {\n return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));\n }\n /**\n Remove a mark or mark type from the set of stored marks.\n */\n removeStoredMark(mark) {\n return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));\n }\n /**\n Whether the stored marks were explicitly set for this transaction.\n */\n get storedMarksSet() {\n return (this.updated & UPDATED_MARKS) > 0;\n }\n /**\n @internal\n */\n addStep(step, doc) {\n super.addStep(step, doc);\n this.updated = this.updated & ~UPDATED_MARKS;\n this.storedMarks = null;\n }\n /**\n Update the timestamp for the transaction.\n */\n setTime(time) {\n this.time = time;\n return this;\n }\n /**\n Replace the current selection with the given slice.\n */\n replaceSelection(slice) {\n this.selection.replace(this, slice);\n return this;\n }\n /**\n Replace the selection with the given node. When `inheritMarks` is\n true and the content is inline, it inherits the marks from the\n place where it is inserted.\n */\n replaceSelectionWith(node, inheritMarks = true) {\n let selection = this.selection;\n if (inheritMarks)\n node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : (selection.$from.marksAcross(selection.$to) || Mark.none)));\n selection.replaceWith(this, node);\n return this;\n }\n /**\n Delete the selection.\n */\n deleteSelection() {\n this.selection.replace(this);\n return this;\n }\n /**\n Replace the given range, or the selection if no range is given,\n with a text node containing the given string.\n */\n insertText(text, from, to) {\n let schema = this.doc.type.schema;\n if (from == null) {\n if (!text)\n return this.deleteSelection();\n return this.replaceSelectionWith(schema.text(text), true);\n }\n else {\n if (to == null)\n to = from;\n if (!text)\n return this.deleteRange(from, to);\n let marks = this.storedMarks;\n if (!marks) {\n let $from = this.doc.resolve(from);\n marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to));\n }\n this.replaceRangeWith(from, to, schema.text(text, marks));\n if (!this.selection.empty && this.selection.to == from + text.length)\n this.setSelection(Selection.near(this.selection.$to));\n return this;\n }\n }\n /**\n Store a metadata property in this transaction, keyed either by\n name or by plugin.\n */\n setMeta(key, value) {\n this.meta[typeof key == \"string\" ? key : key.key] = value;\n return this;\n }\n /**\n Retrieve a metadata property for a given name or plugin.\n */\n getMeta(key) {\n return this.meta[typeof key == \"string\" ? key : key.key];\n }\n /**\n Returns true if this transaction doesn't contain any metadata,\n and can thus safely be extended.\n */\n get isGeneric() {\n for (let _ in this.meta)\n return false;\n return true;\n }\n /**\n Indicate that the editor should scroll the selection into view\n when updated to the state produced by this transaction.\n */\n scrollIntoView() {\n this.updated |= UPDATED_SCROLL;\n return this;\n }\n /**\n True when this transaction has had `scrollIntoView` called on it.\n */\n get scrolledIntoView() {\n return (this.updated & UPDATED_SCROLL) > 0;\n }\n}\n\nfunction bind(f, self) {\n return !self || !f ? f : f.bind(self);\n}\nclass FieldDesc {\n constructor(name, desc, self) {\n this.name = name;\n this.init = bind(desc.init, self);\n this.apply = bind(desc.apply, self);\n }\n}\nconst baseFields = [\n new FieldDesc(\"doc\", {\n init(config) { return config.doc || config.schema.topNodeType.createAndFill(); },\n apply(tr) { return tr.doc; }\n }),\n new FieldDesc(\"selection\", {\n init(config, instance) { return config.selection || Selection.atStart(instance.doc); },\n apply(tr) { return tr.selection; }\n }),\n new FieldDesc(\"storedMarks\", {\n init(config) { return config.storedMarks || null; },\n apply(tr, _marks, _old, state) { return state.selection.$cursor ? tr.storedMarks : null; }\n }),\n new FieldDesc(\"scrollToSelection\", {\n init() { return 0; },\n apply(tr, prev) { return tr.scrolledIntoView ? prev + 1 : prev; }\n })\n];\n// Object wrapping the part of a state object that stays the same\n// across transactions. Stored in the state's `config` property.\nclass Configuration {\n constructor(schema, plugins) {\n this.schema = schema;\n this.plugins = [];\n this.pluginsByKey = Object.create(null);\n this.fields = baseFields.slice();\n if (plugins)\n plugins.forEach(plugin => {\n if (this.pluginsByKey[plugin.key])\n throw new RangeError(\"Adding different instances of a keyed plugin (\" + plugin.key + \")\");\n this.plugins.push(plugin);\n this.pluginsByKey[plugin.key] = plugin;\n if (plugin.spec.state)\n this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));\n });\n }\n}\n/**\nThe state of a ProseMirror editor is represented by an object of\nthis type. A state is a persistent data structure—it isn't\nupdated, but rather a new state value is computed from an old one\nusing the [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) method.\n\nA state holds a number of built-in fields, and plugins can\n[define](https://prosemirror.net/docs/ref/#state.PluginSpec.state) additional fields.\n*/\nclass EditorState {\n /**\n @internal\n */\n constructor(\n /**\n @internal\n */\n config) {\n this.config = config;\n }\n /**\n The schema of the state's document.\n */\n get schema() {\n return this.config.schema;\n }\n /**\n The plugins that are active in this state.\n */\n get plugins() {\n return this.config.plugins;\n }\n /**\n Apply the given transaction to produce a new state.\n */\n apply(tr) {\n return this.applyTransaction(tr).state;\n }\n /**\n @internal\n */\n filterTransaction(tr, ignore = -1) {\n for (let i = 0; i < this.config.plugins.length; i++)\n if (i != ignore) {\n let plugin = this.config.plugins[i];\n if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this))\n return false;\n }\n return true;\n }\n /**\n Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that\n returns the precise transactions that were applied (which might\n be influenced by the [transaction\n hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of\n plugins) along with the new state.\n */\n applyTransaction(rootTr) {\n if (!this.filterTransaction(rootTr))\n return { state: this, transactions: [] };\n let trs = [rootTr], newState = this.applyInner(rootTr), seen = null;\n // This loop repeatedly gives plugins a chance to respond to\n // transactions as new transactions are added, making sure to only\n // pass the transactions the plugin did not see before.\n for (;;) {\n let haveNew = false;\n for (let i = 0; i < this.config.plugins.length; i++) {\n let plugin = this.config.plugins[i];\n if (plugin.spec.appendTransaction) {\n let n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this;\n let tr = n < trs.length &&\n plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);\n if (tr && newState.filterTransaction(tr, i)) {\n tr.setMeta(\"appendedTransaction\", rootTr);\n if (!seen) {\n seen = [];\n for (let j = 0; j < this.config.plugins.length; j++)\n seen.push(j < i ? { state: newState, n: trs.length } : { state: this, n: 0 });\n }\n trs.push(tr);\n newState = newState.applyInner(tr);\n haveNew = true;\n }\n if (seen)\n seen[i] = { state: newState, n: trs.length };\n }\n }\n if (!haveNew)\n return { state: newState, transactions: trs };\n }\n }\n /**\n @internal\n */\n applyInner(tr) {\n if (!tr.before.eq(this.doc))\n throw new RangeError(\"Applying a mismatched transaction\");\n let newInstance = new EditorState(this.config), fields = this.config.fields;\n for (let i = 0; i < fields.length; i++) {\n let field = fields[i];\n newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance);\n }\n return newInstance;\n }\n /**\n Accessor that constructs and returns a new [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state.\n */\n get tr() { return new Transaction(this); }\n /**\n Create a new state.\n */\n static create(config) {\n let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins);\n let instance = new EditorState($config);\n for (let i = 0; i < $config.fields.length; i++)\n instance[$config.fields[i].name] = $config.fields[i].init(config, instance);\n return instance;\n }\n /**\n Create a new state based on this one, but with an adjusted set\n of active plugins. State fields that exist in both sets of\n plugins are kept unchanged. Those that no longer exist are\n dropped, and those that are new are initialized using their\n [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new\n configuration object..\n */\n reconfigure(config) {\n let $config = new Configuration(this.schema, config.plugins);\n let fields = $config.fields, instance = new EditorState($config);\n for (let i = 0; i < fields.length; i++) {\n let name = fields[i].name;\n instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance);\n }\n return instance;\n }\n /**\n Serialize this state to JSON. If you want to serialize the state\n of plugins, pass an object mapping property names to use in the\n resulting JSON object to plugin objects. The argument may also be\n a string or number, in which case it is ignored, to support the\n way `JSON.stringify` calls `toString` methods.\n */\n toJSON(pluginFields) {\n let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() };\n if (this.storedMarks)\n result.storedMarks = this.storedMarks.map(m => m.toJSON());\n if (pluginFields && typeof pluginFields == 'object')\n for (let prop in pluginFields) {\n if (prop == \"doc\" || prop == \"selection\")\n throw new RangeError(\"The JSON fields `doc` and `selection` are reserved\");\n let plugin = pluginFields[prop], state = plugin.spec.state;\n if (state && state.toJSON)\n result[prop] = state.toJSON.call(plugin, this[plugin.key]);\n }\n return result;\n }\n /**\n Deserialize a JSON representation of a state. `config` should\n have at least a `schema` field, and should contain array of\n plugins to initialize the state with. `pluginFields` can be used\n to deserialize the state of plugins, by associating plugin\n instances with the property names they use in the JSON object.\n */\n static fromJSON(config, json, pluginFields) {\n if (!json)\n throw new RangeError(\"Invalid input for EditorState.fromJSON\");\n if (!config.schema)\n throw new RangeError(\"Required config field 'schema' missing\");\n let $config = new Configuration(config.schema, config.plugins);\n let instance = new EditorState($config);\n $config.fields.forEach(field => {\n if (field.name == \"doc\") {\n instance.doc = Node.fromJSON(config.schema, json.doc);\n }\n else if (field.name == \"selection\") {\n instance.selection = Selection.fromJSON(instance.doc, json.selection);\n }\n else if (field.name == \"storedMarks\") {\n if (json.storedMarks)\n instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON);\n }\n else {\n if (pluginFields)\n for (let prop in pluginFields) {\n let plugin = pluginFields[prop], state = plugin.spec.state;\n if (plugin.key == field.name && state && state.fromJSON &&\n Object.prototype.hasOwnProperty.call(json, prop)) {\n instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance);\n return;\n }\n }\n instance[field.name] = field.init(config, instance);\n }\n });\n return instance;\n }\n}\n\nfunction bindProps(obj, self, target) {\n for (let prop in obj) {\n let val = obj[prop];\n if (val instanceof Function)\n val = val.bind(self);\n else if (prop == \"handleDOMEvents\")\n val = bindProps(val, self, {});\n target[prop] = val;\n }\n return target;\n}\n/**\nPlugins bundle functionality that can be added to an editor.\nThey are part of the [editor state](https://prosemirror.net/docs/ref/#state.EditorState) and\nmay influence that state and the view that contains it.\n*/\nclass Plugin {\n /**\n Create a plugin.\n */\n constructor(\n /**\n The plugin's [spec object](https://prosemirror.net/docs/ref/#state.PluginSpec).\n */\n spec) {\n this.spec = spec;\n /**\n The [props](https://prosemirror.net/docs/ref/#view.EditorProps) exported by this plugin.\n */\n this.props = {};\n if (spec.props)\n bindProps(spec.props, this, this.props);\n this.key = spec.key ? spec.key.key : createKey(\"plugin\");\n }\n /**\n Extract the plugin's state field from an editor state.\n */\n getState(state) { return state[this.key]; }\n}\nconst keys = Object.create(null);\nfunction createKey(name) {\n if (name in keys)\n return name + \"$\" + ++keys[name];\n keys[name] = 0;\n return name + \"$\";\n}\n/**\nA key is used to [tag](https://prosemirror.net/docs/ref/#state.PluginSpec.key) plugins in a way\nthat makes it possible to find them, given an editor state.\nAssigning a key does mean only one plugin of that type can be\nactive in a state.\n*/\nclass PluginKey {\n /**\n Create a plugin key.\n */\n constructor(name = \"key\") { this.key = createKey(name); }\n /**\n Get the active plugin with this key, if any, from an editor\n state.\n */\n get(state) { return state.config.pluginsByKey[this.key]; }\n /**\n Get the plugin's state from an editor state.\n */\n getState(state) { return state[this.key]; }\n}\n\nexport { AllSelection, EditorState, NodeSelection, Plugin, PluginKey, Selection, SelectionRange, TextSelection, Transaction };\n","export var base = {\n 8: \"Backspace\",\n 9: \"Tab\",\n 10: \"Enter\",\n 12: \"NumLock\",\n 13: \"Enter\",\n 16: \"Shift\",\n 17: \"Control\",\n 18: \"Alt\",\n 20: \"CapsLock\",\n 27: \"Escape\",\n 32: \" \",\n 33: \"PageUp\",\n 34: \"PageDown\",\n 35: \"End\",\n 36: \"Home\",\n 37: \"ArrowLeft\",\n 38: \"ArrowUp\",\n 39: \"ArrowRight\",\n 40: \"ArrowDown\",\n 44: \"PrintScreen\",\n 45: \"Insert\",\n 46: \"Delete\",\n 59: \";\",\n 61: \"=\",\n 91: \"Meta\",\n 92: \"Meta\",\n 106: \"*\",\n 107: \"+\",\n 108: \",\",\n 109: \"-\",\n 110: \".\",\n 111: \"/\",\n 144: \"NumLock\",\n 145: \"ScrollLock\",\n 160: \"Shift\",\n 161: \"Shift\",\n 162: \"Control\",\n 163: \"Control\",\n 164: \"Alt\",\n 165: \"Alt\",\n 173: \"-\",\n 186: \";\",\n 187: \"=\",\n 188: \",\",\n 189: \"-\",\n 190: \".\",\n 191: \"/\",\n 192: \"`\",\n 219: \"[\",\n 220: \"\\\\\",\n 221: \"]\",\n 222: \"'\"\n}\n\nexport var shift = {\n 48: \")\",\n 49: \"!\",\n 50: \"@\",\n 51: \"#\",\n 52: \"$\",\n 53: \"%\",\n 54: \"^\",\n 55: \"&\",\n 56: \"*\",\n 57: \"(\",\n 59: \":\",\n 61: \"+\",\n 173: \"_\",\n 186: \":\",\n 187: \"+\",\n 188: \"<\",\n 189: \"_\",\n 190: \">\",\n 191: \"?\",\n 192: \"~\",\n 219: \"{\",\n 220: \"|\",\n 221: \"}\",\n 222: \"\\\"\"\n}\n\nvar mac = typeof navigator != \"undefined\" && /Mac/.test(navigator.platform)\nvar ie = typeof navigator != \"undefined\" && /MSIE \\d|Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(navigator.userAgent)\n\n// Fill in the digit keys\nfor (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i)\n\n// The function keys\nfor (var i = 1; i <= 24; i++) base[i + 111] = \"F\" + i\n\n// And the alphabetic keys\nfor (var i = 65; i <= 90; i++) {\n base[i] = String.fromCharCode(i + 32)\n shift[i] = String.fromCharCode(i)\n}\n\n// For each code that doesn't have a shift-equivalent, copy the base name\nfor (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]\n\nexport function keyName(event) {\n // On macOS, keys held with Shift and Cmd don't reflect the effect of Shift in `.key`.\n // On IE, shift effect is never included in `.key`.\n var ignoreKey = mac && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey ||\n ie && event.shiftKey && event.key && event.key.length == 1 ||\n event.key == \"Unidentified\"\n var name = (!ignoreKey && event.key) ||\n (event.shiftKey ? shift : base)[event.keyCode] ||\n event.key || \"Unidentified\"\n // Edge sometimes produces wrong names (Issue #3)\n if (name == \"Esc\") name = \"Escape\"\n if (name == \"Del\") name = \"Delete\"\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/\n if (name == \"Left\") name = \"ArrowLeft\"\n if (name == \"Up\") name = \"ArrowUp\"\n if (name == \"Right\") name = \"ArrowRight\"\n if (name == \"Down\") name = \"ArrowDown\"\n return name\n}\n","import { keyName, base } from 'w3c-keyname';\nimport { Plugin } from 'prosemirror-state';\n\nconst mac = typeof navigator != \"undefined\" && /Mac|iP(hone|[oa]d)/.test(navigator.platform);\nconst windows = typeof navigator != \"undefined\" && /Win/.test(navigator.platform);\nfunction normalizeKeyName(name) {\n let parts = name.split(/-(?!$)/), result = parts[parts.length - 1];\n if (result == \"Space\")\n result = \" \";\n let alt, ctrl, shift, meta;\n for (let i = 0; i < parts.length - 1; i++) {\n let mod = parts[i];\n if (/^(cmd|meta|m)$/i.test(mod))\n meta = true;\n else if (/^a(lt)?$/i.test(mod))\n alt = true;\n else if (/^(c|ctrl|control)$/i.test(mod))\n ctrl = true;\n else if (/^s(hift)?$/i.test(mod))\n shift = true;\n else if (/^mod$/i.test(mod)) {\n if (mac)\n meta = true;\n else\n ctrl = true;\n }\n else\n throw new Error(\"Unrecognized modifier name: \" + mod);\n }\n if (alt)\n result = \"Alt-\" + result;\n if (ctrl)\n result = \"Ctrl-\" + result;\n if (meta)\n result = \"Meta-\" + result;\n if (shift)\n result = \"Shift-\" + result;\n return result;\n}\nfunction normalize(map) {\n let copy = Object.create(null);\n for (let prop in map)\n copy[normalizeKeyName(prop)] = map[prop];\n return copy;\n}\nfunction modifiers(name, event, shift = true) {\n if (event.altKey)\n name = \"Alt-\" + name;\n if (event.ctrlKey)\n name = \"Ctrl-\" + name;\n if (event.metaKey)\n name = \"Meta-\" + name;\n if (shift && event.shiftKey)\n name = \"Shift-\" + name;\n return name;\n}\n/**\nCreate a keymap plugin for the given set of bindings.\n\nBindings should map key names to [command](https://prosemirror.net/docs/ref/#commands)-style\nfunctions, which will be called with `(EditorState, dispatch,\nEditorView)` arguments, and should return true when they've handled\nthe key. Note that the view argument isn't part of the command\nprotocol, but can be used as an escape hatch if a binding needs to\ndirectly interact with the UI.\n\nKey names may be strings like `\"Shift-Ctrl-Enter\"`—a key\nidentifier prefixed with zero or more modifiers. Key identifiers\nare based on the strings that can appear in\n[`KeyEvent.key`](https:developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key).\nUse lowercase letters to refer to letter keys (or uppercase letters\nif you want shift to be held). You may use `\"Space\"` as an alias\nfor the `\" \"` name.\n\nModifiers can be given in any order. `Shift-` (or `s-`), `Alt-` (or\n`a-`), `Ctrl-` (or `c-` or `Control-`) and `Cmd-` (or `m-` or\n`Meta-`) are recognized. For characters that are created by holding\nshift, the `Shift-` prefix is implied, and should not be added\nexplicitly.\n\nYou can use `Mod-` as a shorthand for `Cmd-` on Mac and `Ctrl-` on\nother platforms.\n\nYou can add multiple keymap plugins to an editor. The order in\nwhich they appear determines their precedence (the ones early in\nthe array get to dispatch first).\n*/\nfunction keymap(bindings) {\n return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } });\n}\n/**\nGiven a set of bindings (using the same format as\n[`keymap`](https://prosemirror.net/docs/ref/#keymap.keymap)), return a [keydown\nhandler](https://prosemirror.net/docs/ref/#view.EditorProps.handleKeyDown) that handles them.\n*/\nfunction keydownHandler(bindings) {\n let map = normalize(bindings);\n return function (view, event) {\n let name = keyName(event), baseName, direct = map[modifiers(name, event)];\n if (direct && direct(view.state, view.dispatch, view))\n return true;\n // A character key\n if (name.length == 1 && name != \" \") {\n if (event.shiftKey) {\n // In case the name was already modified by shift, try looking\n // it up without its shift modifier\n let noShift = map[modifiers(name, event, false)];\n if (noShift && noShift(view.state, view.dispatch, view))\n return true;\n }\n if ((event.altKey || event.metaKey || event.ctrlKey) &&\n // Ctrl-Alt may be used for AltGr on Windows\n !(windows && event.ctrlKey && event.altKey) &&\n (baseName = base[event.keyCode]) && baseName != name) {\n // Try falling back to the keyCode when there's a modifier\n // active or the character produced isn't ASCII, and our table\n // produces a different name from the the keyCode. See #668,\n // #1060, #1529.\n let fromCode = map[modifiers(baseName, event)];\n if (fromCode && fromCode(view.state, view.dispatch, view))\n return true;\n }\n }\n return false;\n };\n}\n\nexport { keydownHandler, keymap };\n","// Because working with row and column-spanning cells is not quite\n// trivial, this code builds up a descriptive structure for a given\n// table node. The structures are cached with the (persistent) table\n// nodes as key, so that they only have to be recomputed when the\n// content of the table changes.\n//\n// This does mean that they have to store table-relative, not\n// document-relative positions. So code that uses them will typically\n// compute the start position of the table and offset positions passed\n// to or gotten from this structure by that amount.\nimport type { Attrs, Node } from 'prosemirror-model';\n\nimport type { CellAttrs } from './util';\n\n/**\n * @public\n */\nexport type ColWidths = number[];\n\n/**\n * @public\n */\nexport type Problem =\n | {\n type: 'colwidth mismatch';\n pos: number;\n colwidth: ColWidths;\n }\n | {\n type: 'collision';\n pos: number;\n row: number;\n n: number;\n }\n | {\n type: 'missing';\n row: number;\n n: number;\n }\n | {\n type: 'overlong_rowspan';\n pos: number;\n n: number;\n }\n | {\n type: 'zero_sized';\n };\n\nlet readFromCache: (key: Node) => TableMap | undefined;\nlet addToCache: (key: Node, value: TableMap) => TableMap;\n\n// Prefer using a weak map to cache table maps. Fall back on a\n// fixed-size cache if that's not supported.\nif (typeof WeakMap != 'undefined') {\n let cache = new WeakMap<Node, TableMap>();\n readFromCache = (key) => cache.get(key);\n addToCache = (key, value) => {\n cache.set(key, value);\n return value;\n };\n} else {\n const cache: (Node | TableMap)[] = [];\n const cacheSize = 10;\n let cachePos = 0;\n readFromCache = (key) => {\n for (let i = 0; i < cache.length; i += 2)\n if (cache[i] == key) return cache[i + 1] as TableMap;\n };\n addToCache = (key, value) => {\n if (cachePos == cacheSize) cachePos = 0;\n cache[cachePos++] = key;\n return (cache[cachePos++] = value);\n };\n}\n\n/**\n * @public\n */\nexport interface Rect {\n left: number;\n top: number;\n right: number;\n bottom: number;\n}\n\n/**\n * A table map describes the structure of a given table. To avoid\n * recomputing them all the time, they are cached per table node. To\n * be able to do that, positions saved in the map are relative to the\n * start of the table, rather than the start of the document.\n *\n * @public\n */\nexport class TableMap {\n constructor(\n /**\n * The number of columns\n */\n public width: number,\n /**\n * The number of rows\n */\n public height: number,\n /**\n * A width * height array with the start position of\n * the cell covering that part of the table in each slot\n */\n public map: number[],\n /**\n * An optional array of problems (cell overlap or non-rectangular\n * shape) for the table, used by the table normalizer.\n */\n public problems: Problem[] | null,\n ) {}\n\n // Find the dimensions of the cell at the given position.\n findCell(pos: number): Rect {\n for (let i = 0; i < this.map.length; i++) {\n const curPos = this.map[i];\n if (curPos != pos) continue;\n\n const left = i % this.width;\n const top = (i / this.width) | 0;\n let right = left + 1;\n let bottom = top + 1;\n\n for (let j = 1; right < this.width && this.map[i + j] == curPos; j++) {\n right++;\n }\n for (\n let j = 1;\n bottom < this.height && this.map[i + this.width * j] == curPos;\n j++\n ) {\n bottom++;\n }\n\n return { left, top, right, bottom };\n }\n throw new RangeError(`No cell with offset ${pos} found`);\n }\n\n // Find the left side of the cell at the given position.\n colCount(pos: number): number {\n for (let i = 0; i < this.map.length; i++) {\n if (this.map[i] == pos) {\n return i % this.width;\n }\n }\n throw new RangeError(`No cell with offset ${pos} found`);\n }\n\n // Find the next cell in the given direction, starting from the cell\n // at `pos`, if any.\n nextCell(pos: number, axis: 'horiz' | 'vert', dir: number): null | number {\n const { left, right, top, bottom } = this.findCell(pos);\n if (axis == 'horiz') {\n if (dir < 0 ? left == 0 : right == this.width) return null;\n return this.map[top * this.width + (dir < 0 ? left - 1 : right)];\n } else {\n if (dir < 0 ? top == 0 : bottom == this.height) return null;\n return this.map[left + this.width * (dir < 0 ? top - 1 : bottom)];\n }\n }\n\n // Get the rectangle spanning the two given cells.\n rectBetween(a: number, b: number): Rect {\n const {\n left: leftA,\n right: rightA,\n top: topA,\n bottom: bottomA,\n } = this.findCell(a);\n const {\n left: leftB,\n right: rightB,\n top: topB,\n bottom: bottomB,\n } = this.findCell(b);\n return {\n left: Math.min(leftA, leftB),\n top: Math.min(topA, topB),\n right: Math.max(rightA, rightB),\n bottom: Math.max(bottomA, bottomB),\n };\n }\n\n // Return the position of all cells that have the top left corner in\n // the given rectangle.\n cellsInRect(rect: Rect): number[] {\n const result: number[] = [];\n const seen: Record<number, boolean> = {};\n for (let row = rect.top; row < rect.bottom; row++) {\n for (let col = rect.left; col < rect.right; col++) {\n const index = row * this.width + col;\n const pos = this.map[index];\n\n if (seen[pos]) continue;\n seen[pos] = true;\n\n if (\n (col == rect.left && col && this.map[index - 1] == pos) ||\n (row == rect.top && row && this.map[index - this.width] == pos)\n ) {\n continue;\n }\n result.push(pos);\n }\n }\n return result;\n }\n\n // Return the position at which the cell at the given row and column\n // starts, or would start, if a cell started there.\n positionAt(row: number, col: number, table: Node): number {\n for (let i = 0, rowStart = 0; ; i++) {\n const rowEnd = rowStart + table.child(i).nodeSize;\n if (i == row) {\n let index = col + row * this.width;\n const rowEndIndex = (row + 1) * this.width;\n // Skip past cells from previous rows (via rowspan)\n while (index < rowEndIndex && this.map[index] < rowStart) index++;\n return index == rowEndIndex ? rowEnd - 1 : this.map[index];\n }\n rowStart = rowEnd;\n }\n }\n\n // Find the table map for the given table node.\n static get(table: Node): TableMap {\n return readFromCache(table) || addToCache(table, computeMap(table));\n }\n}\n\n// Compute a table map.\nfunction computeMap(table: Node): TableMap {\n if (table.type.spec.tableRole != 'table')\n throw new RangeError('Not a table node: ' + table.type.name);\n const width = findWidth(table),\n height = table.childCount;\n const map = [];\n let mapPos = 0;\n let problems: Problem[] | null = null;\n const colWidths: ColWidths = [];\n for (let i = 0, e = width * height; i < e; i++) map[i] = 0;\n\n for (let row = 0, pos = 0; row < height; row++) {\n const rowNode = table.child(row);\n pos++;\n for (let i = 0; ; i++) {\n while (mapPos < map.length && map[mapPos] != 0) mapPos++;\n if (i == rowNode.childCount) break;\n const cellNode = rowNode.child(i);\n const { colspan, rowspan, colwidth } = cellNode.attrs;\n for (let h = 0; h < rowspan; h++) {\n if (h + row >= height) {\n (problems || (problems = [])).push({\n type: 'overlong_rowspan',\n pos,\n n: rowspan - h,\n });\n break;\n }\n const start = mapPos + h * width;\n for (let w = 0; w < colspan; w++) {\n if (map[start + w] == 0) map[start + w] = pos;\n else\n (problems || (problems = [])).push({\n type: 'collision',\n row,\n pos,\n n: colspan - w,\n });\n const colW = colwidth && colwidth[w];\n if (colW) {\n const widthIndex = ((start + w) % width) * 2,\n prev = colWidths[widthIndex];\n if (\n prev == null ||\n (prev != colW && colWidths[widthIndex + 1] == 1)\n ) {\n colWidths[widthIndex] = colW;\n colWidths[widthIndex + 1] = 1;\n } else if (prev == colW) {\n colWidths[widthIndex + 1]++;\n }\n }\n }\n }\n mapPos += colspan;\n pos += cellNode.nodeSize;\n }\n const expectedPos = (row + 1) * width;\n let missing = 0;\n while (mapPos < expectedPos) if (map[mapPos++] == 0) missing++;\n if (missing)\n (problems || (problems = [])).push({ type: 'missing', row, n: missing });\n pos++;\n }\n\n if (width === 0 || height === 0)\n (problems || (problems = [])).push({ type: 'zero_sized' });\n\n const tableMap = new TableMap(width, height, map, problems);\n let badWidths = false;\n\n // For columns that have defined widths, but whose widths disagree\n // between rows, fix up the cells whose width doesn't match the\n // computed one.\n for (let i = 0; !badWidths && i < colWidths.length; i += 2)\n if (colWidths[i] != null && colWidths[i + 1] < height) badWidths = true;\n if (badWidths) findBadColWidths(tableMap, colWidths, table);\n\n return tableMap;\n}\n\nfunction findWidth(table: Node): number {\n let width = -1;\n let hasRowSpan = false;\n for (let row = 0; row < table.childCount; row++) {\n const rowNode = table.child(row);\n let rowWidth = 0;\n if (hasRowSpan)\n for (let j = 0; j < row; j++) {\n const prevRow = table.child(j);\n for (let i = 0; i < prevRow.childCount; i++) {\n const cell = prevRow.child(i);\n if (j + cell.attrs.rowspan > row) rowWidth += cell.attrs.colspan;\n }\n }\n for (let i = 0; i < rowNode.childCount; i++) {\n const cell = rowNode.child(i);\n rowWidth += cell.attrs.colspan;\n if (cell.attrs.rowspan > 1) hasRowSpan = true;\n }\n if (width == -1) width = rowWidth;\n else if (width != rowWidth) width = Math.max(width, rowWidth);\n }\n return width;\n}\n\nfunction findBadColWidths(\n map: TableMap,\n colWidths: ColWidths,\n table: Node,\n): void {\n if (!map.problems) map.problems = [];\n const seen: Record<number, boolean> = {};\n for (let i = 0; i < map.map.length; i++) {\n const pos = map.map[i];\n if (seen[pos]) continue;\n seen[pos] = true;\n const node = table.nodeAt(pos);\n if (!node) {\n throw new RangeError(`No cell with offset ${pos} found`);\n }\n\n let updated = null;\n const attrs = node.attrs as CellAttrs;\n for (let j = 0; j < attrs.colspan; j++) {\n const col = (i + j) % map.width;\n const colWidth = colWidths[col * 2];\n if (\n colWidth != null &&\n (!attrs.colwidth || attrs.colwidth[j] != colWidth)\n )\n (updated || (updated = freshColWidth(attrs)))[j] = colWidth;\n }\n if (updated)\n map.problems.unshift({\n type: 'colwidth mismatch',\n pos,\n colwidth: updated,\n });\n }\n}\n\nfunction freshColWidth(attrs: Attrs): ColWidths {\n if (attrs.colwidth) return attrs.colwidth.slice();\n const result: ColWidths = [];\n for (let i = 0; i < attrs.colspan; i++) result.push(0);\n return result;\n}\n","// Helper for creating a schema that supports tables.\n\nimport type {\n AttributeSpec,\n Attrs,\n Node,\n NodeSpec,\n NodeType,\n Schema,\n} from 'prosemirror-model';\n\nimport type { CellAttrs, MutableAttrs } from './util';\n\nfunction getCellAttrs(dom: HTMLElement | string, extraAttrs: Attrs): Attrs {\n if (typeof dom === 'string') {\n return {};\n }\n\n const widthAttr = dom.getAttribute('data-colwidth');\n const widths =\n widthAttr && /^\\d+(,\\d+)*$/.test(widthAttr)\n ? widthAttr.split(',').map((s) => Number(s))\n : null;\n const colspan = Number(dom.getAttribute('colspan') || 1);\n const result: MutableAttrs = {\n colspan,\n rowspan: Number(dom.getAttribute('rowspan') || 1),\n colwidth: widths && widths.length == colspan ? widths : null,\n } satisfies CellAttrs;\n for (const prop in extraAttrs) {\n const getter = extraAttrs[prop].getFromDOM;\n const value = getter && getter(dom);\n if (value != null) {\n result[prop] = value;\n }\n }\n return result;\n}\n\nfunction setCellAttrs(node: Node, extraAttrs: Attrs): Attrs {\n const attrs: MutableAttrs = {};\n if (node.attrs.colspan != 1) attrs.colspan = node.attrs.colspan;\n if (node.attrs.rowspan != 1) attrs.rowspan = node.attrs.rowspan;\n if (node.attrs.colwidth)\n attrs['data-colwidth'] = node.attrs.colwidth.join(',');\n for (const prop in extraAttrs) {\n const setter = extraAttrs[prop].setDOMAttr;\n if (setter) setter(node.attrs[prop], attrs);\n }\n return attrs;\n}\n\n/**\n * @public\n */\nexport type getFromDOM = (dom: HTMLElement) => unknown;\n\n/**\n * @public\n */\nexport type setDOMAttr = (value: unknown, attrs: MutableAttrs) => void;\n\n/**\n * @public\n */\nexport interface CellAttributes {\n /**\n * The attribute's default value.\n */\n default: unknown;\n\n /**\n * A function or type name used to validate values of this attribute.\n *\n * See [validate](https://prosemirror.net/docs/ref/#model.AttributeSpec.validate).\n */\n validate?: string | ((value: unknown) => void);\n\n /**\n * A function to read the attribute's value from a DOM node.\n */\n getFromDOM?: getFromDOM;\n\n /**\n * A function to add the attribute's value to an attribute\n * object that's used to render the cell's DOM.\n */\n setDOMAttr?: setDOMAttr;\n}\n\n/**\n * @public\n */\nexport interface TableNodesOptions {\n /**\n * A group name (something like `\"block\"`) to add to the table\n * node type.\n */\n tableGroup?: string;\n\n /**\n * The content expression for table cells.\n */\n cellContent: string;\n\n /**\n * Additional attributes to add to cells. Maps attribute names to\n * objects with the following properties:\n */\n cellAttributes: { [key: string]: CellAttributes };\n}\n\n/**\n * @public\n */\nexport type TableNodes = Record<\n 'table' | 'table_row' | 'table_cell' | 'table_header',\n NodeSpec\n>;\n\nfunction validateColwidth(value: unknown) {\n if (value === null) {\n return;\n }\n if (!Array.isArray(value)) {\n throw new TypeError('colwidth must be null or an array');\n }\n for (const item of value) {\n if (typeof item !== 'number') {\n throw new TypeError('colwidth must be null or an array of numbers');\n }\n }\n}\n\n/**\n * This function creates a set of [node\n * specs](http://prosemirror.net/docs/ref/#model.SchemaSpec.nodes) for\n * `table`, `table_row`, and `table_cell` nodes types as used by this\n * module. The result can then be added to the set of nodes when\n * creating a schema.\n *\n * @public\n */\nexport function tableNodes(options: TableNodesOptions): TableNodes {\n const extraAttrs = options.cellAttributes || {};\n const cellAttrs: Record<string, AttributeSpec> = {\n colspan: { default: 1, validate: 'number' },\n rowspan: { default: 1, validate: 'number' },\n colwidth: { default: null, validate: validateColwidth },\n };\n for (const prop in extraAttrs)\n cellAttrs[prop] = {\n default: extraAttrs[prop].default,\n validate: extraAttrs[prop].validate,\n };\n\n return {\n table: {\n content: 'table_row+',\n tableRole: 'table',\n isolating: true,\n group: options.tableGroup,\n parseDOM: [{ tag: 'table' }],\n toDOM() {\n return ['table', ['tbody', 0]];\n },\n },\n table_row: {\n content: '(table_cell | table_header)*',\n tableRole: 'row',\n parseDOM: [{ tag: 'tr' }],\n toDOM() {\n return ['tr', 0];\n },\n },\n table_cell: {\n content: options.cellContent,\n attrs: cellAttrs,\n tableRole: 'cell',\n isolating: true,\n parseDOM: [\n { tag: 'td', getAttrs: (dom) => getCellAttrs(dom, extraAttrs) },\n ],\n toDOM(node) {\n return ['td', setCellAttrs(node, extraAttrs), 0];\n },\n },\n table_header: {\n content: options.cellContent,\n attrs: cellAttrs,\n tableRole: 'header_cell',\n isolating: true,\n parseDOM: [\n { tag: 'th', getAttrs: (dom) => getCellAttrs(dom, extraAttrs) },\n ],\n toDOM(node) {\n return ['th', setCellAttrs(node, extraAttrs), 0];\n },\n },\n };\n}\n\n/**\n * @public\n */\nexport type TableRole = 'table' | 'row' | 'cell' | 'header_cell';\n\n/**\n * @public\n */\nexport function tableNodeTypes(schema: Schema): Record<TableRole, NodeType> {\n let result = schema.cached.tableNodeTypes;\n if (!result) {\n result = schema.cached.tableNodeTypes = {};\n for (const name in schema.nodes) {\n const type = schema.nodes[name],\n role = type.spec.tableRole;\n if (role) result[role] = type;\n }\n }\n return result;\n}\n","// Various helper function for working with tables\n\nimport type { Attrs, Node, ResolvedPos } from 'prosemirror-model';\nimport type { EditorState, NodeSelection } from 'prosemirror-state';\nimport { PluginKey } from 'prosemirror-state';\n\nimport type { CellSelection } from './cellselection';\nimport { tableNodeTypes } from './schema';\nimport type { Rect } from './tablemap';\nimport { TableMap } from './tablemap';\n\n/**\n * @public\n */\nexport type MutableAttrs = Record<string, unknown>;\n\n/**\n * @public\n */\nexport interface CellAttrs {\n colspan: number;\n rowspan: number;\n colwidth: number[] | null;\n}\n\n/**\n * @public\n */\nexport const tableEditingKey = new PluginKey<number>('selectingCells');\n\n/**\n * @public\n */\nexport function cellAround($pos: ResolvedPos): ResolvedPos | null {\n for (let d = $pos.depth - 1; d > 0; d--)\n if ($pos.node(d).type.spec.tableRole == 'row')\n return $pos.node(0).resolve($pos.before(d + 1));\n return null;\n}\n\nexport function cellWrapping($pos: ResolvedPos): null | Node {\n for (let d = $pos.depth; d > 0; d--) {\n // Sometimes the cell can be in the same depth.\n const role = $pos.node(d).type.spec.tableRole;\n if (role === 'cell' || role === 'header_cell') return $pos.node(d);\n }\n return null;\n}\n\n/**\n * @public\n */\nexport function isInTable(state: EditorState): boolean {\n const $head = state.selection.$head;\n for (let d = $head.depth; d > 0; d--)\n if ($head.node(d).type.spec.tableRole == 'row') return true;\n return false;\n}\n\n/**\n * @internal\n */\nexport function selectionCell(state: EditorState): ResolvedPos {\n const sel = state.selection as CellSelection | NodeSelection;\n if ('$anchorCell' in sel && sel.$anchorCell) {\n return sel.$anchorCell.pos > sel.$headCell.pos\n ? sel.$anchorCell\n : sel.$headCell;\n } else if (\n 'node' in sel &&\n sel.node &&\n sel.node.type.spec.tableRole == 'cell'\n ) {\n return sel.$anchor;\n }\n const $cell = cellAround(sel.$head) || cellNear(sel.$head);\n if ($cell) {\n return $cell;\n }\n throw new RangeError(`No cell found around position ${sel.head}`);\n}\n\n/**\n * @public\n */\nexport function cellNear($pos: ResolvedPos): ResolvedPos | undefined {\n for (\n let after = $pos.nodeAfter, pos = $pos.pos;\n after;\n after = after.firstChild, pos++\n ) {\n const role = after.type.spec.tableRole;\n if (role == 'cell' || role == 'header_cell') return $pos.doc.resolve(pos);\n }\n for (\n let before = $pos.nodeBefore, pos = $pos.pos;\n before;\n before = before.lastChild, pos--\n ) {\n const role = before.type.spec.tableRole;\n if (role == 'cell' || role == 'header_cell')\n return $pos.doc.resolve(pos - before.nodeSize);\n }\n}\n\n/**\n * @public\n */\nexport function pointsAtCell($pos: ResolvedPos): boolean {\n return $pos.parent.type.spec.tableRole == 'row' && !!$pos.nodeAfter;\n}\n\n/**\n * @public\n */\nexport function moveCellForward($pos: ResolvedPos): ResolvedPos {\n return $pos.node(0).resolve($pos.pos + $pos.nodeAfter!.nodeSize);\n}\n\n/**\n * @internal\n */\nexport function inSameTable($cellA: ResolvedPos, $cellB: ResolvedPos): boolean {\n return (\n $cellA.depth == $cellB.depth &&\n $cellA.pos >= $cellB.start(-1) &&\n $cellA.pos <= $cellB.end(-1)\n );\n}\n\n/**\n * @public\n */\nexport function findCell($pos: ResolvedPos): Rect {\n return TableMap.get($pos.node(-1)).findCell($pos.pos - $pos.start(-1));\n}\n\n/**\n * @public\n */\nexport function colCount($pos: ResolvedPos): number {\n return TableMap.get($pos.node(-1)).colCount($pos.pos - $pos.start(-1));\n}\n\n/**\n * @public\n */\nexport function nextCell(\n $pos: ResolvedPos,\n axis: 'horiz' | 'vert',\n dir: number,\n): ResolvedPos | null {\n const table = $pos.node(-1);\n const map = TableMap.get(table);\n const tableStart = $pos.start(-1);\n\n const moved = map.nextCell($pos.pos - tableStart, axis, dir);\n return moved == null ? null : $pos.node(0).resolve(tableStart + moved);\n}\n\n/**\n * @public\n */\nexport function removeColSpan(attrs: CellAttrs, pos: number, n = 1): CellAttrs {\n const result: CellAttrs = { ...attrs, colspan: attrs.colspan - n };\n\n if (result.colwidth) {\n result.colwidth = result.colwidth.slice();\n result.colwidth.splice(pos, n);\n if (!result.colwidth.some((w) => w > 0)) result.colwidth = null;\n }\n return result;\n}\n\n/**\n * @public\n */\nexport function addColSpan(attrs: CellAttrs, pos: number, n = 1): Attrs {\n const result = { ...attrs, colspan: attrs.colspan + n };\n if (result.colwidth) {\n result.colwidth = result.colwidth.slice();\n for (let i = 0; i < n; i++) result.colwidth.splice(pos, 0, 0);\n }\n return result;\n}\n\n/**\n * @public\n */\nexport function columnIsHeader(\n map: TableMap,\n table: Node,\n col: number,\n): boolean {\n const headerCell = tableNodeTypes(table.type.schema).header_cell;\n for (let row = 0; row < map.height; row++)\n if (table.nodeAt(map.map[col + row * map.width])!.type != headerCell)\n return false;\n return true;\n}\n","// This file defines a ProseMirror selection subclass that models\n// table cell selections. The table plugin needs to be active to wire\n// in the user interaction part of table selections (so that you\n// actually get such selections when you select across cells).\n\nimport type { Node, ResolvedPos } from 'prosemirror-model';\nimport { Fragment, Slice } from 'prosemirror-model';\nimport type { EditorState, Transaction } from 'prosemirror-state';\nimport {\n NodeSelection,\n Selection,\n SelectionRange,\n TextSelection,\n} from 'prosemirror-state';\nimport type { Mappable } from 'prosemirror-transform';\nimport type { DecorationSource } from 'prosemirror-view';\nimport { Decoration, DecorationSet } from 'prosemirror-view';\n\nimport { TableMap } from './tablemap';\nimport type { CellAttrs } from './util';\nimport { inSameTable, pointsAtCell, removeColSpan } from './util';\n\n/**\n * @public\n */\nexport interface CellSelectionJSON {\n type: string;\n anchor: number;\n head: number;\n}\n\n/**\n * A [`Selection`](http://prosemirror.net/docs/ref/#state.Selection)\n * subclass that represents a cell selection spanning part of a table.\n * With the plugin enabled, these will be created when the user\n * selects across cells, and will be drawn by giving selected cells a\n * `selectedCell` CSS class.\n *\n * @public\n */\nexport class CellSelection extends Selection {\n // A resolved position pointing _in front of_ the anchor cell (the one\n // that doesn't move when extending the selection).\n public $anchorCell: ResolvedPos;\n\n // A resolved position pointing in front of the head cell (the one\n // moves when extending the selection).\n public $headCell: ResolvedPos;\n\n // A table selection is identified by its anchor and head cells. The\n // positions given to this constructor should point _before_ two\n // cells in the same table. They may be the same, to select a single\n // cell.\n constructor($anchorCell: ResolvedPos, $headCell: ResolvedPos = $anchorCell) {\n const table = $anchorCell.node(-1);\n const map = TableMap.get(table);\n const tableStart = $anchorCell.start(-1);\n const rect = map.rectBetween(\n $anchorCell.pos - tableStart,\n $headCell.pos - tableStart,\n );\n\n const doc = $anchorCell.node(0);\n const cells = map\n .cellsInRect(rect)\n .filter((p) => p != $headCell.pos - tableStart);\n // Make the head cell the first range, so that it counts as the\n // primary part of the selection\n cells.unshift($headCell.pos - tableStart);\n const ranges = cells.map((pos) => {\n const cell = table.nodeAt(pos);\n if (!cell) {\n throw new RangeError(`No cell with offset ${pos} found`);\n }\n const from = tableStart + pos + 1;\n return new SelectionRange(\n doc.resolve(from),\n doc.resolve(from + cell.content.size),\n );\n });\n super(ranges[0].$from, ranges[0].$to, ranges);\n this.$anchorCell = $anchorCell;\n this.$headCell = $headCell;\n }\n\n public map(doc: Node, mapping: Mappable): CellSelection | Selection {\n const $anchorCell = doc.resolve(mapping.map(this.$anchorCell.pos));\n const $headCell = doc.resolve(mapping.map(this.$headCell.pos));\n if (\n pointsAtCell($anchorCell) &&\n pointsAtCell($headCell) &&\n inSameTable($anchorCell, $headCell)\n ) {\n const tableChanged = this.$anchorCell.node(-1) != $anchorCell.node(-1);\n if (tableChanged && this.isRowSelection())\n return CellSelection.rowSelection($anchorCell, $headCell);\n else if (tableChanged && this.isColSelection())\n return CellSelection.colSelection($anchorCell, $headCell);\n else return new CellSelection($anchorCell, $headCell);\n }\n return TextSelection.between($anchorCell, $headCell);\n }\n\n // Returns a rectangular slice of table rows containing the selected\n // cells.\n public override content(): Slice {\n const table = this.$anchorCell.node(-1);\n const map = TableMap.get(table);\n const tableStart = this.$anchorCell.start(-1);\n\n const rect = map.rectBetween(\n this.$anchorCell.pos - tableStart,\n this.$headCell.pos - tableStart,\n );\n const seen: Record<number, boolean> = {};\n const rows = [];\n for (let row = rect.top; row < rect.bottom; row++) {\n const rowContent = [];\n for (\n let index = row * map.width + rect.left, col = rect.left;\n col < rect.right;\n col++, index++\n ) {\n const pos = map.map[index];\n if (seen[pos]) continue;\n seen[pos] = true;\n\n const cellRect = map.findCell(pos);\n let cell = table.nodeAt(pos);\n if (!cell) {\n throw new RangeError(`No cell with offset ${pos} found`);\n }\n\n const extraLeft = rect.left - cellRect.left;\n const extraRight = cellRect.right - rect.right;\n\n if (extraLeft > 0 || extraRight > 0) {\n let attrs = cell.attrs as CellAttrs;\n if (extraLeft > 0) {\n attrs = removeColSpan(attrs, 0, extraLeft);\n }\n if (extraRight > 0) {\n attrs = removeColSpan(\n attrs,\n attrs.colspan - extraRight,\n extraRight,\n );\n }\n if (cellRect.left < rect.left) {\n cell = cell.type.createAndFill(attrs);\n if (!cell) {\n throw new RangeError(\n `Could not create cell with attrs ${JSON.stringify(attrs)}`,\n );\n }\n } else {\n cell = cell.type.create(attrs, cell.content);\n }\n }\n if (cellRect.top < rect.top || cellRect.bottom > rect.bottom) {\n const attrs = {\n ...cell.attrs,\n rowspan:\n Math.min(cellRect.bottom, rect.bottom) -\n Math.max(cellRect.top, rect.top),\n };\n if (cellRect.top < rect.top) {\n cell = cell.type.createAndFill(attrs)!;\n } else {\n cell = cell.type.create(attrs, cell.content);\n }\n }\n rowContent.push(cell);\n }\n rows.push(table.child(row).copy(Fragment.from(rowContent)));\n }\n\n const fragment =\n this.isColSelection() && this.isRowSelection() ? table : rows;\n return new Slice(Fragment.from(fragment), 1, 1);\n }\n\n public override replace(tr: Transaction, content: Slice = Slice.empty): void {\n const mapFrom = tr.steps.length,\n ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n const { $from, $to } = ranges[i],\n mapping = tr.mapping.slice(mapFrom);\n tr.replace(\n mapping.map($from.pos),\n mapping.map($to.pos),\n i ? Slice.empty : content,\n );\n }\n const sel = Selection.findFrom(\n tr.doc.resolve(tr.mapping.slice(mapFrom).map(this.to)),\n -1,\n );\n if (sel) tr.setSelection(sel);\n }\n\n public override replaceWith(tr: Transaction, node: Node): void {\n this.replace(tr, new Slice(Fragment.from(node), 0, 0));\n }\n\n public forEachCell(f: (node: Node, pos: number) => void): void {\n const table = this.$anchorCell.node(-1);\n const map = TableMap.get(table);\n const tableStart = this.$anchorCell.start(-1);\n\n const cells = map.cellsInRect(\n map.rectBetween(\n this.$anchorCell.pos - tableStart,\n this.$headCell.pos - tableStart,\n ),\n );\n for (let i = 0; i < cells.length; i++) {\n f(table.nodeAt(cells[i])!, tableStart + cells[i]);\n }\n }\n\n // True if this selection goes all the way from the top to the\n // bottom of the table.\n public isColSelection(): boolean {\n const anchorTop = this.$anchorCell.index(-1);\n const headTop = this.$headCell.index(-1);\n if (Math.min(anchorTop, headTop) > 0) return false;\n\n const anchorBottom = anchorTop + this.$anchorCell.nodeAfter!.attrs.rowspan;\n const headBottom = headTop + this.$headCell.nodeAfter!.attrs.rowspan;\n\n return (\n Math.max(anchorBottom, headBottom) == this.$headCell.node(-1).childCount\n );\n }\n\n // Returns the smallest column selection that covers the given anchor\n // and head cell.\n public static colSelection(\n $anchorCell: ResolvedPos,\n $headCell: ResolvedPos = $anchorCell,\n ): CellSelection {\n const table = $anchorCell.node(-1);\n const map = TableMap.get(table);\n const tableStart = $anchorCell.start(-1);\n\n const anchorRect = map.findCell($anchorCell.pos - tableStart);\n const headRect = map.findCell($headCell.pos - tableStart);\n const doc = $anchorCell.node(0);\n\n if (anchorRect.top <= headRect.top) {\n if (anchorRect.top > 0)\n $anchorCell = doc.resolve(tableStart + map.map[anchorRect.left]);\n if (headRect.bottom < map.height)\n $headCell = doc.resolve(\n tableStart +\n map.map[map.width * (map.height - 1) + headRect.right - 1],\n );\n } else {\n if (headRect.top > 0)\n $headCell = doc.resolve(tableStart + map.map[headRect.left]);\n if (anchorRect.bottom < map.height)\n $anchorCell = doc.resolve(\n tableStart +\n map.map[map.width * (map.height - 1) + anchorRect.right - 1],\n );\n }\n return new CellSelection($anchorCell, $headCell);\n }\n\n // True if this selection goes all the way from the left to the\n // right of the table.\n public isRowSelection(): boolean {\n const table = this.$anchorCell.node(-1);\n const map = TableMap.get(table);\n const tableStart = this.$anchorCell.start(-1);\n\n const anchorLeft = map.colCount(this.$anchorCell.pos - tableStart);\n const headLeft = map.colCount(this.$headCell.pos - tableStart);\n if (Math.min(anchorLeft, headLeft) > 0) return false;\n\n const anchorRight = anchorLeft + this.$anchorCell.nodeAfter!.attrs.colspan;\n const headRight = headLeft + this.$headCell.nodeAfter!.attrs.colspan;\n return Math.max(anchorRight, headRight) == map.width;\n }\n\n public eq(other: unknown): boolean {\n return (\n other instanceof CellSelection &&\n other.$anchorCell.pos == this.$anchorCell.pos &&\n other.$headCell.pos == this.$headCell.pos\n );\n }\n\n // Returns the smallest row selection that covers the given anchor\n // and head cell.\n public static rowSelection(\n $anchorCell: ResolvedPos,\n $headCell: ResolvedPos = $anchorCell,\n ): CellSelection {\n const table = $anchorCell.node(-1);\n const map = TableMap.get(table);\n const tableStart = $anchorCell.start(-1);\n\n const anchorRect = map.findCell($anchorCell.pos - tableStart);\n const headRect = map.findCell($headCell.pos - tableStart);\n const doc = $anchorCell.node(0);\n\n if (anchorRect.left <= headRect.left) {\n if (anchorRect.left > 0)\n $anchorCell = doc.resolve(\n tableStart + map.map[anchorRect.top * map.width],\n );\n if (headRect.right < map.width)\n $headCell = doc.resolve(\n tableStart + map.map[map.width * (headRect.top + 1) - 1],\n );\n } else {\n if (headRect.left > 0)\n $headCell = doc.resolve(tableStart + map.map[headRect.top * map.width]);\n if (anchorRect.right < map.width)\n $anchorCell = doc.resolve(\n tableStart + map.map[map.width * (anchorRect.top + 1) - 1],\n );\n }\n return new CellSelection($anchorCell, $headCell);\n }\n\n public toJSON(): CellSelectionJSON {\n return {\n type: 'cell',\n anchor: this.$anchorCell.pos,\n head: this.$headCell.pos,\n };\n }\n\n public static override fromJSON(\n doc: Node,\n json: CellSelectionJSON,\n ): CellSelection {\n return new CellSelection(doc.resolve(json.anchor), doc.resolve(json.head));\n }\n\n static create(\n doc: Node,\n anchorCell: number,\n headCell: number = anchorCell,\n ): CellSelection {\n return new CellSelection(doc.resolve(anchorCell), doc.resolve(headCell));\n }\n\n public override getBookmark(): CellBookmark {\n return new CellBookmark(this.$anchorCell.pos, this.$headCell.pos);\n }\n}\n\nCellSelection.prototype.visible = false;\n\nSelection.jsonID('cell', CellSelection);\n\n/**\n * @public\n */\nexport class CellBookmark {\n constructor(\n public anchor: number,\n public head: number,\n ) {}\n\n map(mapping: Mappable): CellBookmark {\n return new CellBookmark(mapping.map(this.anchor), mapping.map(this.head));\n }\n\n resolve(doc: Node): CellSelection | Selection {\n const $anchorCell = doc.resolve(this.anchor),\n $headCell = doc.resolve(this.head);\n if (\n $anchorCell.parent.type.spec.tableRole == 'row' &&\n $headCell.parent.type.spec.tableRole == 'row' &&\n $anchorCell.index() < $anchorCell.parent.childCount &&\n $headCell.index() < $headCell.parent.childCount &&\n inSameTable($anchorCell, $headCell)\n )\n return new CellSelection($anchorCell, $headCell);\n else return Selection.near($headCell, 1);\n }\n}\n\nexport function drawCellSelection(state: EditorState): DecorationSource | null {\n if (!(state.selection instanceof CellSelection)) return null;\n const cells: Decoration[] = [];\n state.selection.forEachCell((node, pos) => {\n cells.push(\n Decoration.node(pos, pos + node.nodeSize, { class: 'selectedCell' }),\n );\n });\n return DecorationSet.create(state.doc, cells);\n}\n\nfunction isCellBoundarySelection({ $from, $to }: TextSelection) {\n if ($from.pos == $to.pos || $from.pos < $to.pos - 6) return false; // Cheap elimination\n let afterFrom = $from.pos;\n let beforeTo = $to.pos;\n let depth = $from.depth;\n for (; depth >= 0; depth--, afterFrom++)\n if ($from.after(depth + 1) < $from.end(depth)) break;\n for (let d = $to.depth; d >= 0; d--, beforeTo--)\n if ($to.before(d + 1) > $to.start(d)) break;\n return (\n afterFrom == beforeTo &&\n /row|table/.test($from.node(depth).type.spec.tableRole)\n );\n}\n\nfunction isTextSelectionAcrossCells({ $from, $to }: TextSelection) {\n let fromCellBoundaryNode: Node | undefined;\n let toCellBoundaryNode: Node | undefined;\n\n for (let i = $from.depth; i > 0; i--) {\n const node = $from.node(i);\n if (\n node.type.spec.tableRole === 'cell' ||\n node.type.spec.tableRole === 'header_cell'\n ) {\n fromCellBoundaryNode = node;\n break;\n }\n }\n\n for (let i = $to.depth; i > 0; i--) {\n const node = $to.node(i);\n if (\n node.type.spec.tableRole === 'cell' ||\n node.type.spec.tableRole === 'header_cell'\n ) {\n toCellBoundaryNode = node;\n break;\n }\n }\n\n return fromCellBoundaryNode !== toCellBoundaryNode && $to.parentOffset === 0;\n}\n\nexport function normalizeSelection(\n state: EditorState,\n tr: Transaction | undefined,\n allowTableNodeSelection: boolean,\n): Transaction | undefined {\n const sel = (tr || state).selection;\n const doc = (tr || state).doc;\n let normalize: Selection | undefined;\n let role: string | undefined;\n if (sel instanceof NodeSelection && (role = sel.node.type.spec.tableRole)) {\n if (role == 'cell' || role == 'header_cell') {\n normalize = CellSelection.create(doc, sel.from);\n } else if (role == 'row') {\n const $cell = doc.resolve(sel.from + 1);\n normalize = CellSelection.rowSelection($cell, $cell);\n } else if (!allowTableNodeSelection) {\n const map = TableMap.get(sel.node);\n const start = sel.from + 1;\n const lastCell = start + map.map[map.width * map.height - 1];\n normalize = CellSelection.create(doc, start + 1, lastCell);\n }\n } else if (sel instanceof TextSelection && isCellBoundarySelection(sel)) {\n normalize = TextSelection.create(doc, sel.from);\n } else if (sel instanceof TextSelection && isTextSelectionAcrossCells(sel)) {\n normalize = TextSelection.create(doc, sel.$from.start(), sel.$from.end());\n }\n if (normalize) (tr || (tr = state.tr)).setSelection(normalize);\n return tr;\n}\n","// This file defines helpers for normalizing tables, making sure no\n// cells overlap (which can happen, if you have the wrong col- and\n// rowspans) and that each row has the same width. Uses the problems\n// reported by `TableMap`.\n\nimport type { Node } from 'prosemirror-model';\nimport type { EditorState, Transaction } from 'prosemirror-state';\nimport { PluginKey } from 'prosemirror-state';\n\nimport type { TableRole } from './schema';\nimport { tableNodeTypes } from './schema';\nimport { TableMap } from './tablemap';\nimport type { CellAttrs } from './util';\nimport { removeColSpan } from './util';\n\n/**\n * @public\n */\nexport const fixTablesKey = new PluginKey<{ fixTables: boolean }>('fix-tables');\n\n/**\n * Helper for iterating through the nodes in a document that changed\n * compared to the given previous document. Useful for avoiding\n * duplicate work on each transaction.\n *\n * @public\n */\nfunction changedDescendants(\n old: Node,\n cur: Node,\n offset: number,\n f: (node: Node, pos: number) => void,\n): void {\n const oldSize = old.childCount,\n curSize = cur.childCount;\n outer: for (let i = 0, j = 0; i < curSize; i++) {\n const child = cur.child(i);\n for (let scan = j, e = Math.min(oldSize, i + 3); scan < e; scan++) {\n if (old.child(scan) == child) {\n j = scan + 1;\n offset += child.nodeSize;\n continue outer;\n }\n }\n f(child, offset);\n if (j < oldSize && old.child(j).sameMarkup(child))\n changedDescendants(old.child(j), child, offset + 1, f);\n else child.nodesBetween(0, child.content.size, f, offset + 1);\n offset += child.nodeSize;\n }\n}\n\n/**\n * Inspect all tables in the given state's document and return a\n * transaction that fixes them, if necessary. If `oldState` was\n * provided, that is assumed to hold a previous, known-good state,\n * which will be used to avoid re-scanning unchanged parts of the\n * document.\n *\n * @public\n */\nexport function fixTables(\n state: EditorState,\n oldState?: EditorState,\n): Transaction | undefined {\n let tr: Transaction | undefined;\n const check = (node: Node, pos: number) => {\n if (node.type.spec.tableRole == 'table')\n tr = fixTable(state, node, pos, tr);\n };\n if (!oldState) state.doc.descendants(check);\n else if (oldState.doc != state.doc)\n changedDescendants(oldState.doc, state.doc, 0, check);\n return tr;\n}\n\n// Fix the given table, if necessary. Will append to the transaction\n// it was given, if non-null, or create a new one if necessary.\nexport function fixTable(\n state: EditorState,\n table: Node,\n tablePos: number,\n tr: Transaction | undefined,\n): Transaction | undefined {\n const map = TableMap.get(table);\n if (!map.problems) return tr;\n if (!tr) tr = state.tr;\n\n // Track which rows we must add cells to, so that we can adjust that\n // when fixing collisions.\n const mustAdd: number[] = [];\n for (let i = 0; i < map.height; i++) mustAdd.push(0);\n for (let i = 0; i < map.problems.length; i++) {\n const prob = map.problems[i];\n if (prob.type == 'collision') {\n const cell = table.nodeAt(prob.pos);\n if (!cell) continue;\n const attrs = cell.attrs as CellAttrs;\n for (let j = 0; j < attrs.rowspan; j++) mustAdd[prob.row + j] += prob.n;\n tr.setNodeMarkup(\n tr.mapping.map(tablePos + 1 + prob.pos),\n null,\n removeColSpan(attrs, attrs.colspan - prob.n, prob.n),\n );\n } else if (prob.type == 'missing') {\n mustAdd[prob.row] += prob.n;\n } else if (prob.type == 'overlong_rowspan') {\n const cell = table.nodeAt(prob.pos);\n if (!cell) continue;\n tr.setNodeMarkup(tr.mapping.map(tablePos + 1 + prob.pos), null, {\n ...cell.attrs,\n rowspan: cell.attrs.rowspan - prob.n,\n });\n } else if (prob.type == 'colwidth mismatch') {\n const cell = table.nodeAt(prob.pos);\n if (!cell) continue;\n tr.setNodeMarkup(tr.mapping.map(tablePos + 1 + prob.pos), null, {\n ...cell.attrs,\n colwidth: prob.colwidth,\n });\n } else if (prob.type == 'zero_sized') {\n const pos = tr.mapping.map(tablePos);\n tr.delete(pos, pos + table.nodeSize);\n }\n }\n let first, last;\n for (let i = 0; i < mustAdd.length; i++)\n if (mustAdd[i]) {\n if (first == null) first = i;\n last = i;\n }\n // Add the necessary cells, using a heuristic for whether to add the\n // cells at the start or end of the rows (if it looks like a 'bite'\n // was taken out of the table, add cells at the start of the row\n // after the bite. Otherwise add them at the end).\n for (let i = 0, pos = tablePos + 1; i < map.height; i++) {\n const row = table.child(i);\n const end = pos + row.nodeSize;\n const add = mustAdd[i];\n if (add > 0) {\n let role: TableRole = 'cell';\n if (row.firstChild) {\n role = row.firstChild.type.spec.tableRole;\n }\n const nodes: Node[] = [];\n for (let j = 0; j < add; j++) {\n const node = tableNodeTypes(state.schema)[role].createAndFill();\n\n if (node) nodes.push(node);\n }\n const side = (i == 0 || first == i - 1) && last == i ? pos + 1 : end - 1;\n tr.insert(tr.mapping.map(side), nodes);\n }\n pos = end;\n }\n return tr.setMeta(fixTablesKey, { fixTables: true });\n}\n","import type { Node } from 'prosemirror-model';\n\nimport { TableMap } from '../tablemap';\n\n/**\n * This function will transform the table node into a matrix of rows and columns\n * respecting merged cells, for example this table:\n *\n * ```\n * ┌──────┬──────┬─────────────┐\n * │ A1 │ B1 │ C1 │\n * ├──────┼──────┴──────┬──────┤\n * │ A2 │ B2 │ │\n * ├──────┼─────────────┤ D1 │\n * │ A3 │ B3 │ C3 │ │\n * └──────┴──────┴──────┴──────┘\n * ```\n *\n * will be converted to the below:\n *\n * ```javascript\n * [\n * [A1, B1, C1, null],\n * [A2, B2, null, D1],\n * [A3, B3, C3, null],\n * ]\n * ```\n * @internal\n */\nexport function convertTableNodeToArrayOfRows(\n tableNode: Node,\n): (Node | null)[][] {\n const map = TableMap.get(tableNode);\n const rows: (Node | null)[][] = [];\n const rowCount = map.height;\n const colCount = map.width;\n for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {\n const row: (Node | null)[] = [];\n for (let colIndex = 0; colIndex < colCount; colIndex++) {\n const cellIndex = rowIndex * colCount + colIndex;\n const cellPos = map.map[cellIndex];\n if (rowIndex > 0) {\n const topCellIndex = cellIndex - colCount;\n const topCellPos = map.map[topCellIndex];\n if (cellPos === topCellPos) {\n row.push(null);\n continue;\n }\n }\n if (colIndex > 0) {\n const leftCellIndex = cellIndex - 1;\n const leftCellPos = map.map[leftCellIndex];\n if (cellPos === leftCellPos) {\n row.push(null);\n continue;\n }\n }\n row.push(tableNode.nodeAt(cellPos));\n }\n rows.push(row);\n }\n\n return rows;\n}\n\n/**\n * Convert an array of rows to a table node.\n *\n * @internal\n */\nexport function convertArrayOfRowsToTableNode(\n tableNode: Node,\n arrayOfNodes: (Node | null)[][],\n): Node {\n const newRows: Node[] = [];\n const map = TableMap.get(tableNode);\n const rowCount = map.height;\n const colCount = map.width;\n for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {\n const oldRow: Node = tableNode.child(rowIndex);\n const newCells: Node[] = [];\n\n for (let colIndex = 0; colIndex < colCount; colIndex++) {\n const cell = arrayOfNodes[rowIndex][colIndex];\n if (!cell) {\n continue;\n }\n\n const cellPos = map.map[rowIndex * map.width + colIndex];\n const oldCell = tableNode.nodeAt(cellPos);\n if (!oldCell) {\n continue;\n }\n\n const newCell = oldCell.type.createChecked(\n cell.attrs,\n cell.content,\n cell.marks,\n );\n newCells.push(newCell);\n }\n\n const newRow = oldRow.type.createChecked(\n oldRow.attrs,\n newCells,\n oldRow.marks,\n );\n newRows.push(newRow);\n }\n\n const newTable = tableNode.type.createChecked(\n tableNode.attrs,\n newRows,\n tableNode.marks,\n );\n return newTable;\n}\n","/**\n * Move a row in an array of rows.\n *\n * @internal\n */\nexport function moveRowInArrayOfRows<T>(\n rows: T[],\n indexesOrigin: number[],\n indexesTarget: number[],\n directionOverride: -1 | 1 | 0,\n): T[] {\n const direction = indexesOrigin[0] > indexesTarget[0] ? -1 : 1;\n\n const rowsExtracted = rows.splice(indexesOrigin[0], indexesOrigin.length);\n const positionOffset = rowsExtracted.length % 2 === 0 ? 1 : 0;\n let target: number;\n\n if (directionOverride === -1 && direction === 1) {\n target = indexesTarget[0] - 1;\n } else if (directionOverride === 1 && direction === -1) {\n target = indexesTarget[indexesTarget.length - 1] - positionOffset + 1;\n } else {\n target =\n direction === -1\n ? indexesTarget[0]\n : indexesTarget[indexesTarget.length - 1] - positionOffset;\n }\n\n rows.splice(target, 0, ...rowsExtracted);\n return rows;\n}\n","import type { Node, ResolvedPos } from 'prosemirror-model';\nimport type { Selection } from 'prosemirror-state';\n\nimport { CellSelection } from '../cellselection';\nimport { cellAround, cellNear, inSameTable } from '../util';\n\n/**\n * Checks if the given object is a `CellSelection` instance.\n *\n * @internal\n */\nfunction isCellSelection(value: unknown): value is CellSelection {\n return value instanceof CellSelection;\n}\n\n/**\n * Find the closest table node for a given position.\n *\n * @public\n */\nexport function findTable($pos: ResolvedPos): FindNodeResult | null {\n return findParentNode((node) => node.type.spec.tableRole === 'table', $pos);\n}\n\n/**\n * Try to find the anchor and head cell in the same table by using the given\n * anchor and head as hit points, or fallback to the selection's anchor and\n * head.\n *\n * @public\n */\nexport function findCellRange(\n selection: Selection,\n anchorHit?: number,\n headHit?: number,\n): [ResolvedPos, ResolvedPos] | null {\n if (anchorHit == null && headHit == null && isCellSelection(selection)) {\n return [selection.$anchorCell, selection.$headCell];\n }\n\n const anchor: number = anchorHit ?? headHit ?? selection.anchor;\n const head: number = headHit ?? anchorHit ?? selection.head;\n\n const doc = selection.$head.doc;\n\n const $anchorCell = findCellPos(doc, anchor);\n const $headCell = findCellPos(doc, head);\n\n if ($anchorCell && $headCell && inSameTable($anchorCell, $headCell)) {\n return [$anchorCell, $headCell];\n }\n return null;\n}\n\n/**\n * Try to find a resolved pos of a cell by using the given pos as a hit point.\n *\n * @public\n */\nexport function findCellPos(doc: Node, pos: number): ResolvedPos | undefined {\n const $pos = doc.resolve(pos);\n return cellAround($pos) || cellNear($pos);\n}\n\n/**\n * Result of finding a parent node.\n *\n * @public\n */\nexport interface FindNodeResult {\n /**\n * The closest parent node that satisfies the predicate.\n */\n node: Node;\n\n /**\n * The position directly before the node.\n */\n pos: number;\n\n /**\n * The position at the start of the node.\n */\n start: number;\n\n /**\n * The depth of the node.\n */\n depth: number;\n}\n\n/**\n * Find the closest parent node that satisfies the predicate.\n *\n * @internal\n */\nfunction findParentNode(\n /**\n * The predicate to test the parent node.\n */\n predicate: (node: Node) => boolean,\n /**\n * The position to start searching from.\n */\n $pos: ResolvedPos,\n): FindNodeResult | null {\n for (let depth = $pos.depth; depth >= 0; depth -= 1) {\n const node = $pos.node(depth);\n\n if (predicate(node)) {\n const pos = depth === 0 ? 0 : $pos.before(depth);\n const start = $pos.start(depth);\n return { node, pos, start, depth };\n }\n }\n\n return null;\n}\n","import type { Selection } from 'prosemirror-state';\n\nimport { TableMap } from '../tablemap';\n\nimport type { FindNodeResult } from './query';\nimport { findTable } from './query';\n\n/**\n * Returns an array of cells in a column at the specified column index.\n *\n * @internal\n */\nexport function getCellsInColumn(\n columnIndex: number,\n selection: Selection,\n): FindNodeResult[] | undefined {\n const table = findTable(selection.$from);\n if (!table) {\n return;\n }\n\n const map = TableMap.get(table.node);\n\n if (columnIndex < 0 || columnIndex > map.width - 1) {\n return;\n }\n\n const cells = map.cellsInRect({\n left: columnIndex,\n right: columnIndex + 1,\n top: 0,\n bottom: map.height,\n });\n\n return cells.map((nodePos) => {\n const node = table.node.nodeAt(nodePos)!;\n const pos = nodePos + table.start;\n return { pos, start: pos + 1, node, depth: table.depth + 2 };\n });\n}\n\n/**\n * Returns an array of cells in a row at the specified row index.\n *\n * @internal\n */\nexport function getCellsInRow(\n rowIndex: number,\n selection: Selection,\n): FindNodeResult[] | undefined {\n const table = findTable(selection.$from);\n if (!table) {\n return;\n }\n\n const map = TableMap.get(table.node);\n\n if (rowIndex < 0 || rowIndex > map.height - 1) {\n return;\n }\n\n const cells = map.cellsInRect({\n left: 0,\n right: map.width,\n top: rowIndex,\n bottom: rowIndex + 1,\n });\n\n return cells.map((nodePos) => {\n const node = table.node.nodeAt(nodePos)!;\n const pos = nodePos + table.start;\n return { pos, start: pos + 1, node, depth: table.depth + 2 };\n });\n}\n","import type { ResolvedPos } from 'prosemirror-model';\nimport type { Transaction } from 'prosemirror-state';\n\nimport { getCellsInColumn, getCellsInRow } from './get-cells';\n\nexport type CellSelectionRange = {\n $anchor: ResolvedPos;\n $head: ResolvedPos;\n // an array of column/row indexes\n indexes: number[];\n};\n\n/**\n * Returns a range of rectangular selection spanning all merged cells around a\n * column at index `columnIndex`.\n *\n * Original implementation from Atlassian (Apache License 2.0)\n *\n * https://bitbucket.org/atlassian/atlassian-frontend-mirror/src/5f91cb871e8248bc3bae5ddc30bb9fd9200fadbb/editor/editor-tables/src/utils/get-selection-range-in-column.ts#editor/editor-tables/src/utils/get-selection-range-in-column.ts\n *\n * @internal\n */\nexport function getSelectionRangeInColumn(\n tr: Transaction,\n startColIndex: number,\n endColIndex: number = startColIndex,\n): CellSelectionRange | undefined {\n let startIndex = startColIndex;\n let endIndex = endColIndex;\n\n // looking for selection start column (startIndex)\n for (let i = startColIndex; i >= 0; i--) {\n const cells = getCellsInColumn(i, tr.selection);\n if (cells) {\n cells.forEach((cell) => {\n const maybeEndIndex = cell.node.attrs.colspan + i - 1;\n if (maybeEndIndex >= startIndex) {\n startIndex = i;\n }\n if (maybeEndIndex > endIndex) {\n endIndex = maybeEndIndex;\n }\n });\n }\n }\n // looking for selection end column (endIndex)\n for (let i = startColIndex; i <= endIndex; i++) {\n const cells = getCellsInColumn(i, tr.selection);\n if (cells) {\n cells.forEach((cell) => {\n const maybeEndIndex = cell.node.attrs.colspan + i - 1;\n if (cell.node.attrs.colspan > 1 && maybeEndIndex > endIndex) {\n endIndex = maybeEndIndex;\n }\n });\n }\n }\n\n // filter out columns without cells (where all rows have colspan > 1 in the same column)\n const indexes = [];\n for (let i = startIndex; i <= endIndex; i++) {\n const maybeCells = getCellsInColumn(i, tr.selection);\n if (maybeCells && maybeCells.length > 0) {\n indexes.push(i);\n }\n }\n startIndex = indexes[0];\n endIndex = indexes[indexes.length - 1];\n\n const firstSelectedColumnCells = getCellsInColumn(startIndex, tr.selection);\n const firstRowCells = getCellsInRow(0, tr.selection);\n if (!firstSelectedColumnCells || !firstRowCells) {\n return;\n }\n\n const $anchor = tr.doc.resolve(\n firstSelectedColumnCells[firstSelectedColumnCells.length - 1].pos,\n );\n\n let headCell;\n for (let i = endIndex; i >= startIndex; i--) {\n const columnCells = getCellsInColumn(i, tr.selection);\n if (columnCells && columnCells.length > 0) {\n for (let j = firstRowCells.length - 1; j >= 0; j--) {\n if (firstRowCells[j].pos === columnCells[0].pos) {\n headCell = columnCells[0];\n break;\n }\n }\n if (headCell) {\n break;\n }\n }\n }\n if (!headCell) {\n return;\n }\n\n const $head = tr.doc.resolve(headCell.pos);\n return { $anchor, $head, indexes };\n}\n\n/**\n * Returns a range of rectangular selection spanning all merged cells around a\n * row at index `rowIndex`.\n *\n * Original implementation from Atlassian (Apache License 2.0)\n *\n * https://bitbucket.org/atlassian/atlassian-frontend-mirror/src/5f91cb871e8248bc3bae5ddc30bb9fd9200fadbb/editor/editor-tables/src/utils/get-selection-range-in-row.ts#editor/editor-tables/src/utils/get-selection-range-in-row.ts\n *\n * @internal\n */\nexport function getSelectionRangeInRow(\n tr: Transaction,\n startRowIndex: number,\n endRowIndex: number = startRowIndex,\n): CellSelectionRange | undefined {\n let startIndex = startRowIndex;\n let endIndex = endRowIndex;\n\n // looking for selection start row (startIndex)\n for (let i = startRowIndex; i >= 0; i--) {\n const cells = getCellsInRow(i, tr.selection);\n if (cells) {\n cells.forEach((cell) => {\n const maybeEndIndex = cell.node.attrs.rowspan + i - 1;\n if (maybeEndIndex >= startIndex) {\n startIndex = i;\n }\n if (maybeEndIndex > endIndex) {\n endIndex = maybeEndIndex;\n }\n });\n }\n }\n // looking for selection end row (endIndex)\n for (let i = startRowIndex; i <= endIndex; i++) {\n const cells = getCellsInRow(i, tr.selection);\n if (cells) {\n cells.forEach((cell) => {\n const maybeEndIndex = cell.node.attrs.rowspan + i - 1;\n if (cell.node.attrs.rowspan > 1 && maybeEndIndex > endIndex) {\n endIndex = maybeEndIndex;\n }\n });\n }\n }\n\n // filter out rows without cells (where all columns have rowspan > 1 in the same row)\n const indexes = [];\n for (let i = startIndex; i <= endIndex; i++) {\n const maybeCells = getCellsInRow(i, tr.selection);\n if (maybeCells && maybeCells.length > 0) {\n indexes.push(i);\n }\n }\n startIndex = indexes[0];\n endIndex = indexes[indexes.length - 1];\n\n const firstSelectedRowCells = getCellsInRow(startIndex, tr.selection);\n const firstColumnCells = getCellsInColumn(0, tr.selection);\n if (!firstSelectedRowCells || !firstColumnCells) {\n return;\n }\n\n const $anchor = tr.doc.resolve(\n firstSelectedRowCells[firstSelectedRowCells.length - 1].pos,\n );\n\n let headCell;\n for (let i = endIndex; i >= startIndex; i--) {\n const rowCells = getCellsInRow(i, tr.selection);\n if (rowCells && rowCells.length > 0) {\n for (let j = firstColumnCells.length - 1; j >= 0; j--) {\n if (firstColumnCells[j].pos === rowCells[0].pos) {\n headCell = rowCells[0];\n break;\n }\n }\n if (headCell) {\n break;\n }\n }\n }\n if (!headCell) {\n return;\n }\n\n const $head = tr.doc.resolve(headCell.pos);\n return { $anchor, $head, indexes };\n}\n","/**\n * Transposes a 2D array by flipping columns to rows.\n *\n * Transposition is a familiar algebra concept where the matrix is flipped\n * along its diagonal. For more details, see:\n * https://en.wikipedia.org/wiki/Transpose\n *\n * @example\n * ```javascript\n * const arr = [\n * ['a1', 'a2', 'a3'],\n * ['b1', 'b2', 'b3'],\n * ['c1', 'c2', 'c3'],\n * ['d1', 'd2', 'd3'],\n * ];\n *\n * const result = transpose(arr);\n * result === [\n * ['a1', 'b1', 'c1', 'd1'],\n * ['a2', 'b2', 'c2', 'd2'],\n * ['a3', 'b3', 'c3', 'd3'],\n * ]\n * ```\n */\nexport function transpose<T>(array: T[][]): T[][] {\n return array[0].map((_, i) => {\n return array.map((column) => column[i]);\n });\n}\n","import type { Node } from 'prosemirror-model';\nimport type { Transaction } from 'prosemirror-state';\n\nimport { CellSelection } from '../cellselection';\nimport { TableMap } from '../tablemap';\n\nimport {\n convertArrayOfRowsToTableNode,\n convertTableNodeToArrayOfRows,\n} from './convert';\nimport { moveRowInArrayOfRows } from './move-row-in-array-of-rows';\nimport { findTable } from './query';\nimport { getSelectionRangeInColumn } from './selection-range';\nimport { transpose } from './transpose';\n\n/**\n * Parameters for moving a column in a table.\n *\n * @internal\n */\nexport interface MoveColumnParams {\n tr: Transaction;\n originIndex: number;\n targetIndex: number;\n select: boolean;\n pos: number;\n}\n\n/**\n * Move a column from index `origin` to index `target`.\n *\n * @internal\n */\nexport function moveColumn(moveColParams: MoveColumnParams): boolean {\n const { tr, originIndex, targetIndex, select, pos } = moveColParams;\n const $pos = tr.doc.resolve(pos);\n const table = findTable($pos);\n if (!table) return false;\n\n const indexesOriginColumn = getSelectionRangeInColumn(\n tr,\n originIndex,\n )?.indexes;\n const indexesTargetColumn = getSelectionRangeInColumn(\n tr,\n targetIndex,\n )?.indexes;\n\n if (!indexesOriginColumn || !indexesTargetColumn) return false;\n\n if (indexesOriginColumn.includes(targetIndex)) return false;\n\n const newTable = moveTableColumn(\n table.node,\n indexesOriginColumn,\n indexesTargetColumn,\n 0,\n );\n\n tr.replaceWith(table.pos, table.pos + table.node.nodeSize, newTable);\n\n if (!select) return true;\n\n const map = TableMap.get(newTable);\n const start = table.start;\n const index = targetIndex;\n const lastCell = map.positionAt(map.height - 1, index, newTable);\n const $lastCell = tr.doc.resolve(start + lastCell);\n\n const firstCell = map.positionAt(0, index, newTable);\n const $firstCell = tr.doc.resolve(start + firstCell);\n\n tr.setSelection(CellSelection.colSelection($lastCell, $firstCell));\n return true;\n}\n\nfunction moveTableColumn(\n table: Node,\n indexesOrigin: number[],\n indexesTarget: number[],\n direction: -1 | 1 | 0,\n) {\n let rows = transpose(convertTableNodeToArrayOfRows(table));\n\n rows = moveRowInArrayOfRows(rows, indexesOrigin, indexesTarget, direction);\n rows = transpose(rows);\n\n return convertArrayOfRowsToTableNode(table, rows);\n}\n","import type { Node } from 'prosemirror-model';\nimport type { Transaction } from 'prosemirror-state';\n\nimport { CellSelection } from '../cellselection';\nimport { TableMap } from '../tablemap';\n\nimport {\n convertArrayOfRowsToTableNode,\n convertTableNodeToArrayOfRows,\n} from './convert';\nimport { moveRowInArrayOfRows } from './move-row-in-array-of-rows';\nimport { findTable } from './query';\nimport { getSelectionRangeInRow } from './selection-range';\n\n/**\n * Parameters for moving a row in a table.\n *\n * @internal\n */\nexport interface MoveRowParams {\n tr: Transaction;\n originIndex: number;\n targetIndex: number;\n select: boolean;\n pos: number;\n}\n\n/**\n * Move a row from index `origin` to index `target`.\n *\n * @internal\n */\nexport function moveRow(moveRowParams: MoveRowParams): boolean {\n const { tr, originIndex, targetIndex, select, pos } = moveRowParams;\n const $pos = tr.doc.resolve(pos);\n const table = findTable($pos);\n if (!table) return false;\n\n const indexesOriginRow = getSelectionRangeInRow(tr, originIndex)?.indexes;\n const indexesTargetRow = getSelectionRangeInRow(tr, targetIndex)?.indexes;\n\n if (!indexesOriginRow || !indexesTargetRow) return false;\n\n if (indexesOriginRow.includes(targetIndex)) return false;\n\n const newTable = moveTableRow(\n table.node,\n indexesOriginRow,\n indexesTargetRow,\n 0,\n );\n\n tr.replaceWith(table.pos, table.pos + table.node.nodeSize, newTable);\n\n if (!select) return true;\n\n const map = TableMap.get(newTable);\n const start = table.start;\n const index = targetIndex;\n const lastCell = map.positionAt(index, map.width - 1, newTable);\n const $lastCell = tr.doc.resolve(start + lastCell);\n\n const firstCell = map.positionAt(index, 0, newTable);\n const $firstCell = tr.doc.resolve(start + firstCell);\n\n tr.setSelection(CellSelection.rowSelection($lastCell, $firstCell));\n return true;\n}\n\nfunction moveTableRow(\n table: Node,\n indexesOrigin: number[],\n indexesTarget: number[],\n direction: -1 | 1 | 0,\n) {\n let rows = convertTableNodeToArrayOfRows(table);\n\n rows = moveRowInArrayOfRows(rows, indexesOrigin, indexesTarget, direction);\n\n return convertArrayOfRowsToTableNode(table, rows);\n}\n","// This file defines a number of table-related commands.\n\nimport type { Node, NodeType, ResolvedPos } from 'prosemirror-model';\nimport { Fragment, Slice } from 'prosemirror-model';\nimport type { Command, EditorState, Transaction } from 'prosemirror-state';\nimport { TextSelection } from 'prosemirror-state';\n\nimport { CellSelection } from './cellselection';\nimport type { Direction } from './input';\nimport type { TableRole } from './schema';\nimport { tableNodeTypes } from './schema';\nimport type { Rect } from './tablemap';\nimport { TableMap } from './tablemap';\nimport type { CellAttrs } from './util';\nimport {\n addColSpan,\n cellAround,\n cellWrapping,\n columnIsHeader,\n isInTable,\n moveCellForward,\n removeColSpan,\n selectionCell,\n} from './util';\nimport { moveColumn } from './utils/move-column';\nimport { moveRow } from './utils/move-row';\n\n/**\n * @public\n */\nexport type TableRect = Rect & {\n tableStart: number;\n map: TableMap;\n table: Node;\n};\n\n/**\n * Helper to get the selected rectangle in a table, if any. Adds table\n * map, table node, and table start offset to the object for\n * convenience.\n *\n * @public\n */\nexport function selectedRect(state: EditorState): TableRect {\n const sel = state.selection;\n const $pos = selectionCell(state);\n const table = $pos.node(-1);\n const tableStart = $pos.start(-1);\n const map = TableMap.get(table);\n const rect =\n sel instanceof CellSelection\n ? map.rectBetween(\n sel.$anchorCell.pos - tableStart,\n sel.$headCell.pos - tableStart,\n )\n : map.findCell($pos.pos - tableStart);\n return { ...rect, tableStart, map, table };\n}\n\n/**\n * Add a column at the given position in a table.\n *\n * @public\n */\nexport function addColumn(\n tr: Transaction,\n { map, tableStart, table }: TableRect,\n col: number,\n): Transaction {\n let refColumn: number | null = col > 0 ? -1 : 0;\n if (columnIsHeader(map, table, col + refColumn)) {\n refColumn = col == 0 || col == map.width ? null : 0;\n }\n\n for (let row = 0; row < map.height; row++) {\n const index = row * map.width + col;\n // If this position falls inside a col-spanning cell\n if (col > 0 && col < map.width && map.map[index - 1] == map.map[index]) {\n const pos = map.map[index];\n const cell = table.nodeAt(pos)!;\n tr.setNodeMarkup(\n tr.mapping.map(tableStart + pos),\n null,\n addColSpan(cell.attrs as CellAttrs, col - map.colCount(pos)),\n );\n // Skip ahead if rowspan > 1\n row += cell.attrs.rowspan - 1;\n } else {\n const type =\n refColumn == null\n ? tableNodeTypes(table.type.schema).cell\n : table.nodeAt(map.map[index + refColumn])!.type;\n const pos = map.positionAt(row, col, table);\n tr.insert(tr.mapping.map(tableStart + pos), type.createAndFill()!);\n }\n }\n return tr;\n}\n\n/**\n * Command to add a column before the column with the selection.\n *\n * @public\n */\nexport function addColumnBefore(\n state: EditorState,\n dispatch?: (tr: Transaction) => void,\n): boolean {\n if (!isInTable(state)) return false;\n if (dispatch) {\n const rect = selectedRect(state);\n dispatch(addColumn(state.tr, rect, rect.left));\n }\n return true;\n}\n\n/**\n * Command to add a column after the column with the selection.\n *\n * @public\n */\nexport function addColumnAfter(\n state: EditorState,\n dispatch?: (tr: Transaction) => void,\n): boolean {\n if (!isInTable(state)) return false;\n if (dispatch) {\n const rect = selectedRect(state);\n dispatch(addColumn(state.tr, rect, rect.right));\n }\n return true;\n}\n\n/**\n * @public\n */\nexport function removeColumn(\n tr: Transaction,\n { map, table, tableStart }: TableRect,\n col: number,\n) {\n const mapStart = tr.mapping.maps.length;\n for (let row = 0; row < map.height; ) {\n const index = row * map.width + col;\n const pos = map.map[index];\n const cell = table.nodeAt(pos)!;\n const attrs = cell.attrs as CellAttrs;\n // If this is part of a col-spanning cell\n if (\n (col > 0 && map.map[index - 1] == pos) ||\n (col < map.width - 1 && map.map[index + 1] == pos)\n ) {\n tr.setNodeMarkup(\n tr.mapping.slice(mapStart).map(tableStart + pos),\n null,\n removeColSpan(attrs, col - map.colCount(pos)),\n );\n } else {\n const start = tr.mapping.slice(mapStart).map(tableStart + pos);\n tr.delete(start, start + cell.nodeSize);\n }\n row += attrs.rowspan;\n }\n}\n\n/**\n * Command function that removes the selected columns from a table.\n *\n * @public\n */\nexport function deleteColumn(\n state: EditorState,\n dispatch?: (tr: Transaction) => void,\n): boolean {\n if (!isInTable(state)) return false;\n if (dispatch) {\n const rect = selectedRect(state);\n const tr = state.tr;\n if (rect.left == 0 && rect.right == rect.map.width) return false;\n for (let i = rect.right - 1; ; i--) {\n removeColumn(tr, rect, i);\n if (i == rect.left) break;\n const table = rect.tableStart\n ? tr.doc.nodeAt(rect.tableStart - 1)\n : tr.doc;\n if (!table) {\n throw new RangeError('No table found');\n }\n rect.table = table;\n rect.map = TableMap.get(table);\n }\n dispatch(tr);\n }\n return true;\n}\n\n/**\n * @public\n */\nexport function rowIsHeader(map: TableMap, table: Node, row: number): boolean {\n const headerCell = tableNodeTypes(table.type.schema).header_cell;\n for (let col = 0; col < map.width; col++)\n if (table.nodeAt(map.map[col + row * map.width])?.type != headerCell)\n return false;\n return true;\n}\n\n/**\n * @public\n */\nexport function addRow(\n tr: Transaction,\n { map, tableStart, table }: TableRect,\n row: number,\n): Transaction {\n let rowPos = tableStart;\n for (let i = 0; i < row; i++) rowPos += table.child(i).nodeSize;\n const cells = [];\n let refRow: number | null = row > 0 ? -1 : 0;\n if (rowIsHeader(map, table, row + refRow))\n refRow = row == 0 || row == map.height ? null : 0;\n for (let col = 0, index = map.width * row; col < map.width; col++, index++) {\n // Covered by a rowspan cell\n if (\n row > 0 &&\n row < map.height &&\n map.map[index] == map.map[index - map.width]\n ) {\n const pos = map.map[index];\n const attrs = table.nodeAt(pos)!.attrs;\n tr.setNodeMarkup(tableStart + pos, null, {\n ...attrs,\n rowspan: attrs.rowspan + 1,\n });\n col += attrs.colspan - 1;\n } else {\n const type =\n refRow == null\n ? tableNodeTypes(table.type.schema).cell\n : table.nodeAt(map.map[index + refRow * map.width])?.type;\n const node = type?.createAndFill();\n if (node) cells.push(node);\n }\n }\n tr.insert(rowPos, tableNodeTypes(table.type.schema).row.create(null, cells));\n return tr;\n}\n\n/**\n * Add a table row before the selection.\n *\n * @public\n */\nexport function addRowBefore(\n state: EditorState,\n dispatch?: (tr: Transaction) => void,\n): boolean {\n if (!isInTable(state)) return false;\n if (dispatch) {\n const rect = selectedRect(state);\n dispatch(addRow(state.tr, rect, rect.top));\n }\n return true;\n}\n\n/**\n * Add a table row after the selection.\n *\n * @public\n */\nexport function addRowAfter(\n state: EditorState,\n dispatch?: (tr: Transaction) => void,\n): boolean {\n if (!isInTable(state)) return false;\n if (dispatch) {\n const rect = selectedRect(state);\n dispatch(addRow(state.tr, rect, rect.bottom));\n }\n return true;\n}\n\n/**\n * @public\n */\nexport function removeRow(\n tr: Transaction,\n { map, table, tableStart }: TableRect,\n row: number,\n): void {\n let rowPos = 0;\n for (let i = 0; i < row; i++) rowPos += table.child(i).nodeSize;\n const nextRow = rowPos + table.child(row).nodeSize;\n\n const mapFrom = tr.mapping.maps.length;\n tr.delete(rowPos + tableStart, nextRow + tableStart);\n\n const seen = new Set<number>();\n\n for (let col = 0, index = row * map.width; col < map.width; col++, index++) {\n const pos = map.map[index];\n\n // Skip cells that are checked already\n if (seen.has(pos)) continue;\n seen.add(pos);\n\n if (row > 0 && pos == map.map[index - map.width]) {\n // If this cell starts in the row above, simply reduce its rowspan\n const attrs = table.nodeAt(pos)!.attrs as CellAttrs;\n tr.setNodeMarkup(tr.mapping.slice(mapFrom).map(pos + tableStart), null, {\n ...attrs,\n rowspan: attrs.rowspan - 1,\n });\n col += attrs.colspan - 1;\n } else if (row < map.height && pos == map.map[index + map.width]) {\n // Else, if it continues in the row below, it has to be moved down\n const cell = table.nodeAt(pos)!;\n const attrs = cell.attrs as CellAttrs;\n const copy = cell.type.create(\n { ...attrs, rowspan: cell.attrs.rowspan - 1 },\n cell.content,\n );\n const newPos = map.positionAt(row + 1, col, table);\n tr.insert(tr.mapping.slice(mapFrom).map(tableStart + newPos), copy);\n col += attrs.colspan - 1;\n }\n }\n}\n\n/**\n * Remove the selected rows from a table.\n *\n * @public\n */\nexport function deleteRow(\n state: EditorState,\n dispatch?: (tr: Transaction) => void,\n): boolean {\n if (!isInTable(state)) return false;\n if (dispatch) {\n const rect = selectedRect(state),\n tr = state.tr;\n if (rect.top == 0 && rect.bottom == rect.map.height) return false;\n for (let i = rect.bottom - 1; ; i--) {\n removeRow(tr, rect, i);\n if (i == rect.top) break;\n const table = rect.tableStart\n ? tr.doc.nodeAt(rect.tableStart - 1)\n : tr.doc;\n if (!table) {\n throw new RangeError('No table found');\n }\n rect.table = table;\n rect.map = TableMap.get(rect.table);\n }\n dispatch(tr);\n }\n return true;\n}\n\nfunction isEmpty(cell: Node): boolean {\n const c = cell.content;\n\n return (\n c.childCount == 1 && c.child(0).isTextblock && c.child(0).childCount == 0\n );\n}\n\nfunction cellsOverlapRectangle({ width, height, map }: TableMap, rect: Rect) {\n let indexTop = rect.top * width + rect.left,\n indexLeft = indexTop;\n let indexBottom = (rect.bottom - 1) * width + rect.left,\n indexRight = indexTop + (rect.right - rect.left - 1);\n for (let i = rect.top; i < rect.bottom; i++) {\n if (\n (rect.left > 0 && map[indexLeft] == map[indexLeft - 1]) ||\n (rect.right < width && map[indexRight] == map[indexRight + 1])\n )\n return true;\n indexLeft += width;\n indexRight += width;\n }\n for (let i = rect.left; i < rect.right; i++) {\n if (\n (rect.top > 0 && map[indexTop] == map[indexTop - width]) ||\n (rect.bottom < height && map[indexBottom] == map[indexBottom + width])\n )\n return true;\n indexTop++;\n indexBottom++;\n }\n return false;\n}\n\n/**\n * Merge the selected cells into a single cell. Only available when\n * the selected cells' outline forms a rectangle.\n *\n * @public\n */\nexport function mergeCells(\n state: EditorState,\n dispatch?: (tr: Transaction) => void,\n): boolean {\n const sel = state.selection;\n if (\n !(sel instanceof CellSelection) ||\n sel.$anchorCell.pos == sel.$headCell.pos\n )\n return false;\n const rect = selectedRect(state),\n { map } = rect;\n if (cellsOverlapRectangle(map, rect)) return false;\n if (dispatch) {\n const tr = state.tr;\n const seen: Record<number, boolean> = {};\n let content = Fragment.empty;\n let mergedPos: number | undefined;\n let mergedCell: Node | undefined;\n for (let row = rect.top; row < rect.bottom; row++) {\n for (let col = rect.left; col < rect.right; col++) {\n const cellPos = map.map[row * map.width + col];\n const cell = rect.table.nodeAt(cellPos);\n if (seen[cellPos] || !cell) continue;\n seen[cellPos] = true;\n if (mergedPos == null) {\n mergedPos = cellPos;\n mergedCell = cell;\n } else {\n if (!isEmpty(cell)) content = content.append(cell.content);\n const mapped = tr.mapping.map(cellPos + rect.tableStart);\n tr.delete(mapped, mapped + cell.nodeSize);\n }\n }\n }\n if (mergedPos == null || mergedCell == null) {\n return true;\n }\n\n tr.setNodeMarkup(mergedPos + rect.tableStart, null, {\n ...addColSpan(\n mergedCell.attrs as CellAttrs,\n mergedCell.attrs.colspan,\n rect.right - rect.left - mergedCell.attrs.colspan,\n ),\n rowspan: rect.bottom - rect.top,\n });\n if (content.size > 0) {\n const end = mergedPos + 1 + mergedCell.content.size;\n const start = isEmpty(mergedCell) ? mergedPos + 1 : end;\n tr.replaceWith(start + rect.tableStart, end + rect.tableStart, content);\n }\n tr.setSelection(\n new CellSelection(tr.doc.resolve(mergedPos + rect.tableStart)),\n );\n dispatch(tr);\n }\n return true;\n}\n\n/**\n * Split a selected cell, whose rowpan or colspan is greater than one,\n * into smaller cells. Use the first cell type for the new cells.\n *\n * @public\n */\nexport function splitCell(\n state: EditorState,\n dispatch?: (tr: Transaction) => void,\n): boolean {\n const nodeTypes = tableNodeTypes(state.schema);\n return splitCellWithType(({ node }) => {\n return nodeTypes[node.type.spec.tableRole as TableRole];\n })(state, dispatch);\n}\n\n/**\n * @public\n */\nexport interface GetCellTypeOptions {\n node: Node;\n row: number;\n col: number;\n}\n\n/**\n * Split a selected cell, whose rowpan or colspan is greater than one,\n * into smaller cells with the cell type (th, td) returned by getType function.\n *\n * @public\n */\nexport function splitCellWithType(\n getCellType: (options: GetCellTypeOptions) => NodeType,\n): Command {\n return (state, dispatch) => {\n const sel = state.selection;\n let cellNode: Node | null | undefined;\n let cellPos: number | undefined;\n if (!(sel instanceof CellSelection)) {\n cellNode = cellWrapping(sel.$from);\n if (!cellNode) return false;\n cellPos = cellAround(sel.$from)?.pos;\n } else {\n if (sel.$anchorCell.pos != sel.$headCell.pos) return false;\n cellNode = sel.$anchorCell.nodeAfter;\n cellPos = sel.$anchorCell.pos;\n }\n if (cellNode == null || cellPos == null) {\n return false;\n }\n if (cellNode.attrs.colspan == 1 && cellNode.attrs.rowspan == 1) {\n return false;\n }\n if (dispatch) {\n let baseAttrs = cellNode.attrs;\n const attrs = [];\n const colwidth = baseAttrs.colwidth;\n if (baseAttrs.rowspan > 1) baseAttrs = { ...baseAttrs, rowspan: 1 };\n if (baseAttrs.colspan > 1) baseAttrs = { ...baseAttrs, colspan: 1 };\n const rect = selectedRect(state),\n tr = state.tr;\n for (let i = 0; i < rect.right - rect.left; i++)\n attrs.push(\n colwidth\n ? {\n ...baseAttrs,\n colwidth: colwidth && colwidth[i] ? [colwidth[i]] : null,\n }\n : baseAttrs,\n );\n let lastCell;\n for (let row = rect.top; row < rect.bottom; row++) {\n let pos = rect.map.positionAt(row, rect.left, rect.table);\n if (row == rect.top) pos += cellNode.nodeSize;\n for (let col = rect.left, i = 0; col < rect.right; col++, i++) {\n if (col == rect.left && row == rect.top) continue;\n tr.insert(\n (lastCell = tr.mapping.map(pos + rect.tableStart, 1)),\n getCellType({ node: cellNode, row, col }).createAndFill(attrs[i])!,\n );\n }\n }\n tr.setNodeMarkup(\n cellPos,\n getCellType({ node: cellNode, row: rect.top, col: rect.left }),\n attrs[0],\n );\n if (sel instanceof CellSelection)\n tr.setSelection(\n new CellSelection(\n tr.doc.resolve(sel.$anchorCell.pos),\n lastCell ? tr.doc.resolve(lastCell) : undefined,\n ),\n );\n dispatch(tr);\n }\n return true;\n };\n}\n\n/**\n * Returns a command that sets the given attribute to the given value,\n * and is only available when the currently selected cell doesn't\n * already have that attribute set to that value.\n *\n * @public\n */\nexport function setCellAttr(name: string, value: unknown): Command {\n return function (state, dispatch) {\n if (!isInTable(state)) return false;\n const $cell = selectionCell(state);\n if ($cell.nodeAfter!.attrs[name] === value) return false;\n if (dispatch) {\n const tr = state.tr;\n if (state.selection instanceof CellSelection)\n state.selection.forEachCell((node, pos) => {\n if (node.attrs[name] !== value)\n tr.setNodeMarkup(pos, null, {\n ...node.attrs,\n [name]: value,\n });\n });\n else\n tr.setNodeMarkup($cell.pos, null, {\n ...$cell.nodeAfter!.attrs,\n [name]: value,\n });\n dispatch(tr);\n }\n return true;\n };\n}\n\nfunction deprecated_toggleHeader(type: ToggleHeaderType): Command {\n return function (state, dispatch) {\n if (!isInTable(state)) return false;\n if (dispatch) {\n const types = tableNodeTypes(state.schema);\n const rect = selectedRect(state),\n tr = state.tr;\n const cells = rect.map.cellsInRect(\n type == 'column'\n ? {\n left: rect.left,\n top: 0,\n right: rect.right,\n bottom: rect.map.height,\n }\n : type == 'row'\n ? {\n left: 0,\n top: rect.top,\n right: rect.map.width,\n bottom: rect.bottom,\n }\n : rect,\n );\n const nodes = cells.map((pos) => rect.table.nodeAt(pos)!);\n for (\n let i = 0;\n i < cells.length;\n i++ // Remove headers, if any\n )\n if (nodes[i].type == types.header_cell)\n tr.setNodeMarkup(\n rect.tableStart + cells[i],\n types.cell,\n nodes[i].attrs,\n );\n if (tr.steps.length === 0)\n for (\n let i = 0;\n i < cells.length;\n i++ // No headers removed, add instead\n )\n tr.setNodeMarkup(\n rect.tableStart + cells[i],\n types.header_cell,\n nodes[i].attrs,\n );\n dispatch(tr);\n }\n return true;\n };\n}\n\nfunction isHeaderEnabledByType(\n type: 'row' | 'column',\n rect: TableRect,\n types: Record<string, NodeType>,\n): boolean {\n // Get cell positions for first row or first column\n const cellPositions = rect.map.cellsInRect({\n left: 0,\n top: 0,\n right: type == 'row' ? rect.map.width : 1,\n bottom: type == 'column' ? rect.map.height : 1,\n });\n\n for (let i = 0; i < cellPositions.length; i++) {\n const cell = rect.table.nodeAt(cellPositions[i]);\n if (cell && cell.type !== types.header_cell) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * @public\n */\nexport type ToggleHeaderType = 'column' | 'row' | 'cell';\n\n/**\n * Toggles between row/column header and normal cells (Only applies to first row/column).\n * For deprecated behavior pass `useDeprecatedLogic` in options with true.\n *\n * @public\n */\nexport function toggleHeader(\n type: ToggleHeaderType,\n options?: { useDeprecatedLogic: boolean },\n): Command {\n options = options || { useDeprecatedLogic: false };\n\n if (options.useDeprecatedLogic) return deprecated_toggleHeader(type);\n\n return function (state, dispatch) {\n if (!isInTable(state)) return false;\n if (dispatch) {\n const types = tableNodeTypes(state.schema);\n const rect = selectedRect(state),\n tr = state.tr;\n\n const isHeaderRowEnabled = isHeaderEnabledByType('row', rect, types);\n const isHeaderColumnEnabled = isHeaderEnabledByType(\n 'column',\n rect,\n types,\n );\n\n const isHeaderEnabled =\n type === 'column'\n ? isHeaderRowEnabled\n : type === 'row'\n ? isHeaderColumnEnabled\n : false;\n\n const selectionStartsAt = isHeaderEnabled ? 1 : 0;\n\n const cellsRect =\n type == 'column'\n ? {\n left: 0,\n top: selectionStartsAt,\n right: 1,\n bottom: rect.map.height,\n }\n : type == 'row'\n ? {\n left: selectionStartsAt,\n top: 0,\n right: rect.map.width,\n bottom: 1,\n }\n : rect;\n\n const newType =\n type == 'column'\n ? isHeaderColumnEnabled\n ? types.cell\n : types.header_cell\n : type == 'row'\n ? isHeaderRowEnabled\n ? types.cell\n : types.header_cell\n : types.cell;\n\n rect.map.cellsInRect(cellsRect).forEach((relativeCellPos) => {\n const cellPos = relativeCellPos + rect.tableStart;\n const cell = tr.doc.nodeAt(cellPos);\n\n if (cell) {\n tr.setNodeMarkup(cellPos, newType, cell.attrs);\n }\n });\n\n dispatch(tr);\n }\n return true;\n };\n}\n\n/**\n * Toggles whether the selected row contains header cells.\n *\n * @public\n */\nexport const toggleHeaderRow: Command = toggleHeader('row', {\n useDeprecatedLogic: true,\n});\n\n/**\n * Toggles whether the selected column contains header cells.\n *\n * @public\n */\nexport const toggleHeaderColumn: Command = toggleHeader('column', {\n useDeprecatedLogic: true,\n});\n\n/**\n * Toggles whether the selected cells are header cells.\n *\n * @public\n */\nexport const toggleHeaderCell: Command = toggleHeader('cell', {\n useDeprecatedLogic: true,\n});\n\nfunction findNextCell($cell: ResolvedPos, dir: Direction): number | null {\n if (dir < 0) {\n const before = $cell.nodeBefore;\n if (before) return $cell.pos - before.nodeSize;\n for (\n let row = $cell.index(-1) - 1, rowEnd = $cell.before();\n row >= 0;\n row--\n ) {\n const rowNode = $cell.node(-1).child(row);\n const lastChild = rowNode.lastChild;\n if (lastChild) {\n return rowEnd - 1 - lastChild.nodeSize;\n }\n rowEnd -= rowNode.nodeSize;\n }\n } else {\n if ($cell.index() < $cell.parent.childCount - 1) {\n return $cell.pos + $cell.nodeAfter!.nodeSize;\n }\n const table = $cell.node(-1);\n for (\n let row = $cell.indexAfter(-1), rowStart = $cell.after();\n row < table.childCount;\n row++\n ) {\n const rowNode = table.child(row);\n if (rowNode.childCount) return rowStart + 1;\n rowStart += rowNode.nodeSize;\n }\n }\n return null;\n}\n\n/**\n * Returns a command for selecting the next (direction=1) or previous\n * (direction=-1) cell in a table.\n *\n * @public\n */\nexport function goToNextCell(direction: Direction): Command {\n return function (state, dispatch) {\n if (!isInTable(state)) return false;\n const cell = findNextCell(selectionCell(state), direction);\n if (cell == null) return false;\n if (dispatch) {\n const $cell = state.doc.resolve(cell);\n dispatch(\n state.tr\n .setSelection(TextSelection.between($cell, moveCellForward($cell)))\n .scrollIntoView(),\n );\n }\n return true;\n };\n}\n\n/**\n * Deletes the table around the selection, if any.\n *\n * @public\n */\nexport function deleteTable(\n state: EditorState,\n dispatch?: (tr: Transaction) => void,\n): boolean {\n const $pos = state.selection.$anchor;\n for (let d = $pos.depth; d > 0; d--) {\n const node = $pos.node(d);\n if (node.type.spec.tableRole == 'table') {\n if (dispatch)\n dispatch(\n state.tr.delete($pos.before(d), $pos.after(d)).scrollIntoView(),\n );\n return true;\n }\n }\n return false;\n}\n\n/**\n * Deletes the content of the selected cells, if they are not empty.\n *\n * @public\n */\nexport function deleteCellSelection(\n state: EditorState,\n dispatch?: (tr: Transaction) => void,\n): boolean {\n const sel = state.selection;\n if (!(sel instanceof CellSelection)) return false;\n if (dispatch) {\n const tr = state.tr;\n const baseContent = tableNodeTypes(state.schema).cell.createAndFill()!\n .content;\n sel.forEachCell((cell, pos) => {\n if (!cell.content.eq(baseContent))\n tr.replace(\n tr.mapping.map(pos + 1),\n tr.mapping.map(pos + cell.nodeSize - 1),\n new Slice(baseContent, 0, 0),\n );\n });\n if (tr.docChanged) dispatch(tr);\n }\n return true;\n}\n\n/**\n * Options for moveTableRow\n *\n * @public\n */\nexport interface MoveTableRowOptions {\n /**\n * The source row index to move from.\n */\n from: number;\n\n /**\n * The destination row index to move to.\n */\n to: number;\n\n /**\n * Whether to select the moved row after the operation.\n *\n * @default true\n */\n select?: boolean;\n\n /**\n * Optional position to resolve table from. If not provided, uses the current selection.\n */\n pos?: number;\n}\n\n/**\n * Move a table row from index `from` to index `to`.\n *\n * @public\n */\nexport function moveTableRow(options: MoveTableRowOptions): Command {\n return (state, dispatch) => {\n const {\n from: originIndex,\n to: targetIndex,\n select = true,\n pos = state.selection.from,\n } = options;\n const tr = state.tr;\n if (moveRow({ tr, originIndex, targetIndex, select, pos })) {\n dispatch?.(tr);\n return true;\n }\n return false;\n };\n}\n\n/**\n * Options for moveTableColumn\n *\n * @public\n */\nexport interface MoveTableColumnOptions {\n /**\n * The source column index to move from.\n */\n from: number;\n\n /**\n * The destination column index to move to.\n */\n to: number;\n\n /**\n * Whether to select the moved column after the operation.\n *\n * @default true\n */\n select?: boolean;\n\n /**\n * Optional position to resolve table from. If not provided, uses the current selection.\n */\n pos?: number;\n}\n\n/**\n * Move a table column from index `from` to index `to`.\n *\n * @public\n */\nexport function moveTableColumn(options: MoveTableColumnOptions): Command {\n return (state, dispatch) => {\n const {\n from: originIndex,\n to: targetIndex,\n select = true,\n pos = state.selection.from,\n } = options;\n const tr = state.tr;\n if (moveColumn({ tr, originIndex, targetIndex, select, pos })) {\n dispatch?.(tr);\n return true;\n }\n return false;\n };\n}\n","// Utilities used for copy/paste handling.\n//\n// This module handles pasting cell content into tables, or pasting\n// anything into a cell selection, as replacing a block of cells with\n// the content of the selection. When pasting cells into a cell, that\n// involves placing the block of pasted content so that its top left\n// aligns with the selection cell, optionally extending the table to\n// the right or bottom to make sure it is large enough. Pasting into a\n// cell selection is different, here the cells in the selection are\n// clipped to the selection's rectangle, optionally repeating the\n// pasted cells when they are smaller than the selection.\n\nimport type { Node, NodeType, Schema } from 'prosemirror-model';\nimport { Fragment, Slice } from 'prosemirror-model';\nimport type { EditorState, Transaction } from 'prosemirror-state';\nimport { Transform } from 'prosemirror-transform';\n\nimport { CellSelection } from './cellselection';\nimport { tableNodeTypes } from './schema';\nimport type { ColWidths, Rect } from './tablemap';\nimport { TableMap } from './tablemap';\nimport type { CellAttrs } from './util';\nimport { removeColSpan } from './util';\n\n/**\n * @internal\n */\nexport type Area = { width: number; height: number; rows: Fragment[] };\n\n// Utilities to help with copying and pasting table cells\n\n/**\n * Get a rectangular area of cells from a slice, or null if the outer\n * nodes of the slice aren't table cells or rows.\n *\n * @internal\n */\nexport function pastedCells(slice: Slice): Area | null {\n if (slice.size === 0) return null;\n let { content, openStart, openEnd } = slice;\n while (\n content.childCount == 1 &&\n ((openStart > 0 && openEnd > 0) ||\n content.child(0).type.spec.tableRole == 'table')\n ) {\n openStart--;\n openEnd--;\n content = content.child(0).content;\n }\n const first = content.child(0);\n const role = first.type.spec.tableRole;\n const schema = first.type.schema,\n rows = [];\n if (role == 'row') {\n for (let i = 0; i < content.childCount; i++) {\n let cells = content.child(i).content;\n const left = i ? 0 : Math.max(0, openStart - 1);\n const right = i < content.childCount - 1 ? 0 : Math.max(0, openEnd - 1);\n if (left || right)\n cells = fitSlice(\n tableNodeTypes(schema).row,\n new Slice(cells, left, right),\n ).content;\n rows.push(cells);\n }\n } else if (role == 'cell' || role == 'header_cell') {\n rows.push(\n openStart || openEnd\n ? fitSlice(\n tableNodeTypes(schema).row,\n new Slice(content, openStart, openEnd),\n ).content\n : content,\n );\n } else {\n return null;\n }\n return ensureRectangular(schema, rows);\n}\n\n// Compute the width and height of a set of cells, and make sure each\n// row has the same number of cells.\nfunction ensureRectangular(schema: Schema, rows: Fragment[]): Area {\n const widths: ColWidths = [];\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n for (let j = row.childCount - 1; j >= 0; j--) {\n const { rowspan, colspan } = row.child(j).attrs;\n for (let r = i; r < i + rowspan; r++)\n widths[r] = (widths[r] || 0) + colspan;\n }\n }\n let width = 0;\n for (let r = 0; r < widths.length; r++) width = Math.max(width, widths[r]);\n for (let r = 0; r < widths.length; r++) {\n if (r >= rows.length) rows.push(Fragment.empty);\n if (widths[r] < width) {\n const empty = tableNodeTypes(schema).cell.createAndFill()!;\n const cells = [];\n for (let i = widths[r]; i < width; i++) {\n cells.push(empty);\n }\n rows[r] = rows[r].append(Fragment.from(cells));\n }\n }\n return { height: rows.length, width, rows };\n}\n\nexport function fitSlice(nodeType: NodeType, slice: Slice): Node {\n const node = nodeType.createAndFill()!;\n const tr = new Transform(node).replace(0, node.content.size, slice);\n return tr.doc;\n}\n\n/**\n * Clip or extend (repeat) the given set of cells to cover the given\n * width and height. Will clip rowspan/colspan cells at the edges when\n * they stick out.\n *\n * @internal\n */\nexport function clipCells(\n { width, height, rows }: Area,\n newWidth: number,\n newHeight: number,\n): Area {\n if (width != newWidth) {\n const added: number[] = [];\n const newRows: Fragment[] = [];\n for (let row = 0; row < rows.length; row++) {\n const frag = rows[row],\n cells = [];\n for (let col = added[row] || 0, i = 0; col < newWidth; i++) {\n let cell = frag.child(i % frag.childCount);\n if (col + cell.attrs.colspan > newWidth)\n cell = cell.type.createChecked(\n removeColSpan(\n cell.attrs as CellAttrs,\n cell.attrs.colspan,\n col + cell.attrs.colspan - newWidth,\n ),\n cell.content,\n );\n cells.push(cell);\n col += cell.attrs.colspan;\n for (let j = 1; j < cell.attrs.rowspan; j++)\n added[row + j] = (added[row + j] || 0) + cell.attrs.colspan;\n }\n newRows.push(Fragment.from(cells));\n }\n rows = newRows;\n width = newWidth;\n }\n\n if (height != newHeight) {\n const newRows = [];\n for (let row = 0, i = 0; row < newHeight; row++, i++) {\n const cells = [],\n source = rows[i % height];\n for (let j = 0; j < source.childCount; j++) {\n let cell = source.child(j);\n if (row + cell.attrs.rowspan > newHeight)\n cell = cell.type.create(\n {\n ...cell.attrs,\n rowspan: Math.max(1, newHeight - cell.attrs.rowspan),\n },\n cell.content,\n );\n cells.push(cell);\n }\n newRows.push(Fragment.from(cells));\n }\n rows = newRows;\n height = newHeight;\n }\n\n return { width, height, rows };\n}\n\n// Make sure a table has at least the given width and height. Return\n// true if something was changed.\nfunction growTable(\n tr: Transaction,\n map: TableMap,\n table: Node,\n start: number,\n width: number,\n height: number,\n mapFrom: number,\n): boolean {\n const schema = tr.doc.type.schema;\n const types = tableNodeTypes(schema);\n let empty;\n let emptyHead;\n if (width > map.width) {\n for (let row = 0, rowEnd = 0; row < map.height; row++) {\n const rowNode = table.child(row);\n rowEnd += rowNode.nodeSize;\n const cells: Node[] = [];\n let add: Node;\n if (rowNode.lastChild == null || rowNode.lastChild.type == types.cell)\n add = empty || (empty = types.cell.createAndFill()!);\n else add = emptyHead || (emptyHead = types.header_cell.createAndFill()!);\n for (let i = map.width; i < width; i++) cells.push(add);\n tr.insert(tr.mapping.slice(mapFrom).map(rowEnd - 1 + start), cells);\n }\n }\n if (height > map.height) {\n const cells = [];\n for (\n let i = 0, start = (map.height - 1) * map.width;\n i < Math.max(map.width, width);\n i++\n ) {\n const header =\n i >= map.width\n ? false\n : table.nodeAt(map.map[start + i])!.type == types.header_cell;\n cells.push(\n header\n ? emptyHead || (emptyHead = types.header_cell.createAndFill()!)\n : empty || (empty = types.cell.createAndFill()!),\n );\n }\n\n const emptyRow = types.row.create(null, Fragment.from(cells)),\n rows = [];\n for (let i = map.height; i < height; i++) rows.push(emptyRow);\n tr.insert(tr.mapping.slice(mapFrom).map(start + table.nodeSize - 2), rows);\n }\n return !!(empty || emptyHead);\n}\n\n// Make sure the given line (left, top) to (right, top) doesn't cross\n// any rowspan cells by splitting cells that cross it. Return true if\n// something changed.\nfunction isolateHorizontal(\n tr: Transaction,\n map: TableMap,\n table: Node,\n start: number,\n left: number,\n right: number,\n top: number,\n mapFrom: number,\n): boolean {\n if (top == 0 || top == map.height) return false;\n let found = false;\n for (let col = left; col < right; col++) {\n const index = top * map.width + col,\n pos = map.map[index];\n if (map.map[index - map.width] == pos) {\n found = true;\n const cell = table.nodeAt(pos)!;\n const { top: cellTop, left: cellLeft } = map.findCell(pos);\n tr.setNodeMarkup(tr.mapping.slice(mapFrom).map(pos + start), null, {\n ...cell.attrs,\n rowspan: top - cellTop,\n });\n tr.insert(\n tr.mapping.slice(mapFrom).map(map.positionAt(top, cellLeft, table)),\n cell.type.createAndFill({\n ...cell.attrs,\n rowspan: cellTop + cell.attrs.rowspan - top,\n })!,\n );\n col += cell.attrs.colspan - 1;\n }\n }\n return found;\n}\n\n// Make sure the given line (left, top) to (left, bottom) doesn't\n// cross any colspan cells by splitting cells that cross it. Return\n// true if something changed.\nfunction isolateVertical(\n tr: Transaction,\n map: TableMap,\n table: Node,\n start: number,\n top: number,\n bottom: number,\n left: number,\n mapFrom: number,\n): boolean {\n if (left == 0 || left == map.width) return false;\n let found = false;\n for (let row = top; row < bottom; row++) {\n const index = row * map.width + left,\n pos = map.map[index];\n if (map.map[index - 1] == pos) {\n found = true;\n const cell = table.nodeAt(pos)!;\n const cellLeft = map.colCount(pos);\n const updatePos = tr.mapping.slice(mapFrom).map(pos + start);\n tr.setNodeMarkup(\n updatePos,\n null,\n removeColSpan(\n cell.attrs as CellAttrs,\n left - cellLeft,\n cell.attrs.colspan - (left - cellLeft),\n ),\n );\n tr.insert(\n updatePos + cell.nodeSize,\n cell.type.createAndFill(\n removeColSpan(cell.attrs as CellAttrs, 0, left - cellLeft),\n )!,\n );\n row += cell.attrs.rowspan - 1;\n }\n }\n return found;\n}\n\n/**\n * Insert the given set of cells (as returned by `pastedCells`) into a\n * table, at the position pointed at by rect.\n *\n * @internal\n */\nexport function insertCells(\n state: EditorState,\n dispatch: (tr: Transaction) => void,\n tableStart: number,\n rect: Rect,\n cells: Area,\n): void {\n let table = tableStart ? state.doc.nodeAt(tableStart - 1) : state.doc;\n if (!table) {\n throw new Error('No table found');\n }\n let map = TableMap.get(table);\n const { top, left } = rect;\n const right = left + cells.width,\n bottom = top + cells.height;\n const tr = state.tr;\n let mapFrom = 0;\n\n function recomp(): void {\n table = tableStart ? tr.doc.nodeAt(tableStart - 1) : tr.doc;\n if (!table) {\n throw new Error('No table found');\n }\n map = TableMap.get(table);\n mapFrom = tr.mapping.maps.length;\n }\n\n // Prepare the table to be large enough and not have any cells\n // crossing the boundaries of the rectangle that we want to\n // insert into. If anything about it changes, recompute the table\n // map so that subsequent operations can see the current shape.\n if (growTable(tr, map, table, tableStart, right, bottom, mapFrom)) recomp();\n if (isolateHorizontal(tr, map, table, tableStart, left, right, top, mapFrom))\n recomp();\n if (\n isolateHorizontal(tr, map, table, tableStart, left, right, bottom, mapFrom)\n )\n recomp();\n if (isolateVertical(tr, map, table, tableStart, top, bottom, left, mapFrom))\n recomp();\n if (isolateVertical(tr, map, table, tableStart, top, bottom, right, mapFrom))\n recomp();\n\n for (let row = top; row < bottom; row++) {\n const from = map.positionAt(row, left, table),\n to = map.positionAt(row, right, table);\n tr.replace(\n tr.mapping.slice(mapFrom).map(from + tableStart),\n tr.mapping.slice(mapFrom).map(to + tableStart),\n new Slice(cells.rows[row - top], 0, 0),\n );\n }\n recomp();\n tr.setSelection(\n new CellSelection(\n tr.doc.resolve(tableStart + map.positionAt(top, left, table)),\n tr.doc.resolve(tableStart + map.positionAt(bottom - 1, right - 1, table)),\n ),\n );\n dispatch(tr);\n}\n","// This file defines a number of helpers for wiring up user input to\n// table-related functionality.\n\nimport { keydownHandler } from 'prosemirror-keymap';\nimport type { ResolvedPos, Slice } from 'prosemirror-model';\nimport { Fragment } from 'prosemirror-model';\nimport type { Command, EditorState, Transaction } from 'prosemirror-state';\nimport { Selection, TextSelection } from 'prosemirror-state';\nimport type { EditorView } from 'prosemirror-view';\n\nimport { CellSelection } from './cellselection';\nimport { deleteCellSelection } from './commands';\nimport { clipCells, fitSlice, insertCells, pastedCells } from './copypaste';\nimport { tableNodeTypes } from './schema';\nimport { TableMap } from './tablemap';\nimport {\n cellAround,\n inSameTable,\n isInTable,\n nextCell,\n selectionCell,\n tableEditingKey,\n} from './util';\n\ntype Axis = 'horiz' | 'vert';\n\n/**\n * @public\n */\nexport type Direction = -1 | 1;\n\nexport const handleKeyDown = keydownHandler({\n ArrowLeft: arrow('horiz', -1),\n ArrowRight: arrow('horiz', 1),\n ArrowUp: arrow('vert', -1),\n ArrowDown: arrow('vert', 1),\n\n 'Shift-ArrowLeft': shiftArrow('horiz', -1),\n 'Shift-ArrowRight': shiftArrow('horiz', 1),\n 'Shift-ArrowUp': shiftArrow('vert', -1),\n 'Shift-ArrowDown': shiftArrow('vert', 1),\n\n Backspace: deleteCellSelection,\n 'Mod-Backspace': deleteCellSelection,\n Delete: deleteCellSelection,\n 'Mod-Delete': deleteCellSelection,\n});\n\nfunction maybeSetSelection(\n state: EditorState,\n dispatch: undefined | ((tr: Transaction) => void),\n selection: Selection,\n): boolean {\n if (selection.eq(state.selection)) return false;\n if (dispatch) dispatch(state.tr.setSelection(selection).scrollIntoView());\n return true;\n}\n\n/**\n * @internal\n */\nexport function arrow(axis: Axis, dir: Direction): Command {\n return (state, dispatch, view) => {\n if (!view) return false;\n const sel = state.selection;\n if (sel instanceof CellSelection) {\n return maybeSetSelection(\n state,\n dispatch,\n Selection.near(sel.$headCell, dir),\n );\n }\n if (axis != 'horiz' && !sel.empty) return false;\n const end = atEndOfCell(view, axis, dir);\n if (end == null) return false;\n if (axis == 'horiz') {\n return maybeSetSelection(\n state,\n dispatch,\n Selection.near(state.doc.resolve(sel.head + dir), dir),\n );\n } else {\n const $cell = state.doc.resolve(end);\n const $next = nextCell($cell, axis, dir);\n let newSel;\n if ($next) newSel = Selection.near($next, 1);\n else if (dir < 0)\n newSel = Selection.near(state.doc.resolve($cell.before(-1)), -1);\n else newSel = Selection.near(state.doc.resolve($cell.after(-1)), 1);\n return maybeSetSelection(state, dispatch, newSel);\n }\n };\n}\n\nfunction shiftArrow(axis: Axis, dir: Direction): Command {\n return (state, dispatch, view) => {\n if (!view) return false;\n const sel = state.selection;\n let cellSel: CellSelection;\n if (sel instanceof CellSelection) {\n cellSel = sel;\n } else {\n const end = atEndOfCell(view, axis, dir);\n if (end == null) return false;\n cellSel = new CellSelection(state.doc.resolve(end));\n }\n\n const $head = nextCell(cellSel.$headCell, axis, dir);\n if (!$head) return false;\n return maybeSetSelection(\n state,\n dispatch,\n new CellSelection(cellSel.$anchorCell, $head),\n );\n };\n}\n\nexport function handleTripleClick(view: EditorView, pos: number): boolean {\n const doc = view.state.doc,\n $cell = cellAround(doc.resolve(pos));\n if (!$cell) return false;\n view.dispatch(view.state.tr.setSelection(new CellSelection($cell)));\n return true;\n}\n\n/**\n * @public\n */\nexport function handlePaste(\n view: EditorView,\n _: ClipboardEvent,\n slice: Slice,\n): boolean {\n if (!isInTable(view.state)) return false;\n let cells = pastedCells(slice);\n const sel = view.state.selection;\n if (sel instanceof CellSelection) {\n if (!cells)\n cells = {\n width: 1,\n height: 1,\n rows: [\n Fragment.from(\n fitSlice(tableNodeTypes(view.state.schema).cell, slice),\n ),\n ],\n };\n const table = sel.$anchorCell.node(-1);\n const start = sel.$anchorCell.start(-1);\n const rect = TableMap.get(table).rectBetween(\n sel.$anchorCell.pos - start,\n sel.$headCell.pos - start,\n );\n cells = clipCells(cells, rect.right - rect.left, rect.bottom - rect.top);\n insertCells(view.state, view.dispatch, start, rect, cells);\n return true;\n } else if (cells) {\n const $cell = selectionCell(view.state);\n const start = $cell.start(-1);\n insertCells(\n view.state,\n view.dispatch,\n start,\n TableMap.get($cell.node(-1)).findCell($cell.pos - start),\n cells,\n );\n return true;\n } else {\n return false;\n }\n}\n\nexport function handleMouseDown(\n view: EditorView,\n startEvent: MouseEvent,\n): void {\n // Only handle mouse down events for the main button (usually the left button).\n // This ensures that the cell selection won't be triggered when trying to open\n // the context menu.\n if (startEvent.button != 0) return;\n\n if (startEvent.ctrlKey || startEvent.metaKey) return;\n\n const startDOMCell = domInCell(view, startEvent.target as Node);\n let $anchor;\n if (startEvent.shiftKey && view.state.selection instanceof CellSelection) {\n // Adding to an existing cell selection\n setCellSelection(view.state.selection.$anchorCell, startEvent);\n startEvent.preventDefault();\n } else if (\n startEvent.shiftKey &&\n startDOMCell &&\n ($anchor = cellAround(view.state.selection.$anchor)) != null &&\n cellUnderMouse(view, startEvent)?.pos != $anchor.pos\n ) {\n // Adding to a selection that starts in another cell (causing a\n // cell selection to be created).\n setCellSelection($anchor, startEvent);\n startEvent.preventDefault();\n } else if (!startDOMCell) {\n // Not in a cell, let the default behavior happen.\n return;\n }\n\n // Create and dispatch a cell selection between the given anchor and\n // the position under the mouse.\n function setCellSelection($anchor: ResolvedPos, event: MouseEvent): void {\n let $head = cellUnderMouse(view, event);\n const starting = tableEditingKey.getState(view.state) == null;\n if (!$head || !inSameTable($anchor, $head)) {\n if (starting) $head = $anchor;\n else return;\n }\n const selection = new CellSelection($anchor, $head);\n if (starting || !view.state.selection.eq(selection)) {\n const tr = view.state.tr.setSelection(selection);\n if (starting) tr.setMeta(tableEditingKey, $anchor.pos);\n view.dispatch(tr);\n }\n }\n\n // Stop listening to mouse motion events.\n function stop(): void {\n view.root.removeEventListener('mouseup', stop);\n view.root.removeEventListener('dragstart', stop);\n view.root.removeEventListener('mousemove', move);\n if (tableEditingKey.getState(view.state) != null)\n view.dispatch(view.state.tr.setMeta(tableEditingKey, -1));\n }\n\n function move(_event: Event): void {\n const event = _event as MouseEvent;\n const anchor = tableEditingKey.getState(view.state);\n let $anchor;\n if (anchor != null) {\n // Continuing an existing cross-cell selection\n $anchor = view.state.doc.resolve(anchor);\n } else if (domInCell(view, event.target as Node) != startDOMCell) {\n // Moving out of the initial cell -- start a new cell selection\n $anchor = cellUnderMouse(view, startEvent);\n if (!$anchor) return stop();\n }\n if ($anchor) setCellSelection($anchor, event);\n }\n\n view.root.addEventListener('mouseup', stop);\n view.root.addEventListener('dragstart', stop);\n view.root.addEventListener('mousemove', move);\n}\n\n// Check whether the cursor is at the end of a cell (so that further\n// motion would move out of the cell)\nfunction atEndOfCell(view: EditorView, axis: Axis, dir: number): null | number {\n if (!(view.state.selection instanceof TextSelection)) return null;\n const { $head } = view.state.selection;\n for (let d = $head.depth - 1; d >= 0; d--) {\n const parent = $head.node(d),\n index = dir < 0 ? $head.index(d) : $head.indexAfter(d);\n if (index != (dir < 0 ? 0 : parent.childCount)) return null;\n if (\n parent.type.spec.tableRole == 'cell' ||\n parent.type.spec.tableRole == 'header_cell'\n ) {\n const cellPos = $head.before(d);\n const dirStr: 'up' | 'down' | 'left' | 'right' =\n axis == 'vert' ? (dir > 0 ? 'down' : 'up') : dir > 0 ? 'right' : 'left';\n return view.endOfTextblock(dirStr) ? cellPos : null;\n }\n }\n return null;\n}\n\nfunction domInCell(view: EditorView, dom: Node | null): Node | null {\n for (; dom && dom != view.dom; dom = dom.parentNode) {\n if (dom.nodeName == 'TD' || dom.nodeName == 'TH') {\n return dom;\n }\n }\n return null;\n}\n\nfunction cellUnderMouse(\n view: EditorView,\n event: MouseEvent,\n): ResolvedPos | null {\n const mousePos = view.posAtCoords({\n left: event.clientX,\n top: event.clientY,\n });\n if (!mousePos) return null;\n // Prefer `inside` position for better accuracy with merged cells (rowspan/colspan),\n // but fall back to `pos` if `inside` doesn't resolve to a valid cell\n let { inside, pos } = mousePos;\n return (\n (inside >= 0 && cellAround(view.state.doc.resolve(inside))) ||\n cellAround(view.state.doc.resolve(pos))\n );\n}\n","import type { Node } from 'prosemirror-model';\nimport type { NodeView, ViewMutationRecord } from 'prosemirror-view';\n\nimport type { CellAttrs } from './util';\n\n/**\n * @public\n */\nexport class TableView implements NodeView {\n public dom: HTMLDivElement;\n public table: HTMLTableElement;\n public colgroup: HTMLTableColElement;\n public contentDOM: HTMLTableSectionElement;\n\n constructor(\n public node: Node,\n public defaultCellMinWidth: number,\n ) {\n this.dom = document.createElement('div');\n this.dom.className = 'tableWrapper';\n this.table = this.dom.appendChild(document.createElement('table'));\n this.table.style.setProperty(\n '--default-cell-min-width',\n `${defaultCellMinWidth}px`,\n );\n this.colgroup = this.table.appendChild(document.createElement('colgroup'));\n updateColumnsOnResize(node, this.colgroup, this.table, defaultCellMinWidth);\n this.contentDOM = this.table.appendChild(document.createElement('tbody'));\n }\n\n update(node: Node): boolean {\n if (node.type != this.node.type) return false;\n this.node = node;\n updateColumnsOnResize(\n node,\n this.colgroup,\n this.table,\n this.defaultCellMinWidth,\n );\n return true;\n }\n\n ignoreMutation(record: ViewMutationRecord): boolean {\n return (\n record.type == 'attributes' &&\n (record.target == this.table || this.colgroup.contains(record.target))\n );\n }\n}\n\n/**\n * @public\n */\nexport function updateColumnsOnResize(\n node: Node,\n colgroup: HTMLTableColElement,\n table: HTMLTableElement,\n defaultCellMinWidth: number,\n overrideCol?: number,\n overrideValue?: number,\n): void {\n let totalWidth = 0;\n let fixedWidth = true;\n let nextDOM = colgroup.firstChild as HTMLElement;\n const row = node.firstChild;\n if (!row) return;\n\n for (let i = 0, col = 0; i < row.childCount; i++) {\n const { colspan, colwidth } = row.child(i).attrs as CellAttrs;\n for (let j = 0; j < colspan; j++, col++) {\n const hasWidth =\n overrideCol == col ? overrideValue : colwidth && colwidth[j];\n const cssWidth = hasWidth ? hasWidth + 'px' : '';\n totalWidth += hasWidth || defaultCellMinWidth;\n if (!hasWidth) fixedWidth = false;\n if (!nextDOM) {\n const col = document.createElement('col');\n col.style.width = cssWidth;\n colgroup.appendChild(col);\n } else {\n if (nextDOM.style.width != cssWidth) {\n nextDOM.style.width = cssWidth;\n }\n nextDOM = nextDOM.nextSibling as HTMLElement;\n }\n }\n }\n\n while (nextDOM) {\n const after = nextDOM.nextSibling;\n nextDOM.parentNode?.removeChild(nextDOM);\n nextDOM = after as HTMLElement;\n }\n\n if (fixedWidth) {\n table.style.width = totalWidth + 'px';\n table.style.minWidth = '';\n } else {\n table.style.width = '';\n table.style.minWidth = totalWidth + 'px';\n }\n}\n","import type { Attrs, Node as ProsemirrorNode } from 'prosemirror-model';\nimport type { EditorState, Transaction } from 'prosemirror-state';\nimport { Plugin, PluginKey } from 'prosemirror-state';\nimport type { EditorView, NodeView } from 'prosemirror-view';\nimport { Decoration, DecorationSet } from 'prosemirror-view';\n\nimport { tableNodeTypes } from './schema';\nimport { TableMap } from './tablemap';\nimport { TableView, updateColumnsOnResize } from './tableview';\nimport type { CellAttrs } from './util';\nimport { cellAround, pointsAtCell } from './util';\n\n/**\n * @public\n */\nexport const columnResizingPluginKey = new PluginKey<ResizeState>(\n 'tableColumnResizing',\n);\n\n/**\n * @public\n */\nexport type ColumnResizingOptions = {\n handleWidth?: number;\n /**\n * Minimum width of a cell /column. The column cannot be resized smaller than this.\n */\n cellMinWidth?: number;\n /**\n * The default minWidth of a cell / column when it doesn't have an explicit width (i.e.: it has not been resized manually)\n */\n defaultCellMinWidth?: number;\n lastColumnResizable?: boolean;\n /**\n * A custom node view for the rendering table nodes. By default, the plugin\n * uses the {@link TableView} class. You can explicitly set this to `null` to\n * not use a custom node view.\n */\n View?:\n | (new (\n node: ProsemirrorNode,\n cellMinWidth: number,\n view: EditorView,\n ) => NodeView)\n | null;\n};\n\n/**\n * @public\n */\nexport type Dragging = { startX: number; startWidth: number };\n\n/**\n * @public\n */\nexport function columnResizing({\n handleWidth = 5,\n cellMinWidth = 25,\n defaultCellMinWidth = 100,\n View = TableView,\n lastColumnResizable = true,\n}: ColumnResizingOptions = {}): Plugin {\n const plugin = new Plugin<ResizeState>({\n key: columnResizingPluginKey,\n state: {\n init(_, state) {\n const nodeViews = plugin.spec?.props?.nodeViews;\n const tableName = tableNodeTypes(state.schema).table.name;\n if (View && nodeViews) {\n nodeViews[tableName] = (node, view) => {\n return new View(node, defaultCellMinWidth, view);\n };\n }\n return new ResizeState(-1, false);\n },\n apply(tr, prev) {\n return prev.apply(tr);\n },\n },\n props: {\n attributes: (state): Record<string, string> => {\n const pluginState = columnResizingPluginKey.getState(state);\n return pluginState && pluginState.activeHandle > -1\n ? { class: 'resize-cursor' }\n : {};\n },\n\n handleDOMEvents: {\n mousemove: (view, event) => {\n handleMouseMove(view, event, handleWidth, lastColumnResizable);\n },\n mouseleave: (view) => {\n handleMouseLeave(view);\n },\n mousedown: (view, event) => {\n handleMouseDown(view, event, cellMinWidth, defaultCellMinWidth);\n },\n },\n\n decorations: (state) => {\n const pluginState = columnResizingPluginKey.getState(state);\n if (pluginState && pluginState.activeHandle > -1) {\n return handleDecorations(state, pluginState.activeHandle);\n }\n },\n\n nodeViews: {},\n },\n });\n return plugin;\n}\n\n/**\n * @public\n */\nexport class ResizeState {\n constructor(\n public activeHandle: number,\n public dragging: Dragging | false,\n ) {}\n\n apply(tr: Transaction): ResizeState {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const state = this;\n const action = tr.getMeta(columnResizingPluginKey);\n if (action && action.setHandle != null)\n return new ResizeState(action.setHandle, false);\n if (action && action.setDragging !== undefined)\n return new ResizeState(state.activeHandle, action.setDragging);\n if (state.activeHandle > -1 && tr.docChanged) {\n let handle = tr.mapping.map(state.activeHandle, -1);\n if (!pointsAtCell(tr.doc.resolve(handle))) {\n handle = -1;\n }\n return new ResizeState(handle, state.dragging);\n }\n return state;\n }\n}\n\nfunction handleMouseMove(\n view: EditorView,\n event: MouseEvent,\n handleWidth: number,\n lastColumnResizable: boolean,\n): void {\n if (!view.editable) return;\n\n const pluginState = columnResizingPluginKey.getState(view.state);\n if (!pluginState) return;\n\n if (!pluginState.dragging) {\n const target = domCellAround(event.target as HTMLElement);\n let cell = -1;\n if (target) {\n const { left, right } = target.getBoundingClientRect();\n if (event.clientX - left <= handleWidth)\n cell = edgeCell(view, event, 'left', handleWidth);\n else if (right - event.clientX <= handleWidth)\n cell = edgeCell(view, event, 'right', handleWidth);\n }\n\n if (cell != pluginState.activeHandle) {\n if (!lastColumnResizable && cell !== -1) {\n const $cell = view.state.doc.resolve(cell);\n const table = $cell.node(-1);\n const map = TableMap.get(table);\n const tableStart = $cell.start(-1);\n const col =\n map.colCount($cell.pos - tableStart) +\n $cell.nodeAfter!.attrs.colspan -\n 1;\n\n if (col == map.width - 1) {\n return;\n }\n }\n\n updateHandle(view, cell);\n }\n }\n}\n\nfunction handleMouseLeave(view: EditorView): void {\n if (!view.editable) return;\n\n const pluginState = columnResizingPluginKey.getState(view.state);\n if (pluginState && pluginState.activeHandle > -1 && !pluginState.dragging)\n updateHandle(view, -1);\n}\n\nfunction handleMouseDown(\n view: EditorView,\n event: MouseEvent,\n cellMinWidth: number,\n defaultCellMinWidth: number,\n): boolean {\n if (!view.editable) return false;\n\n const win = view.dom.ownerDocument.defaultView ?? window;\n\n const pluginState = columnResizingPluginKey.getState(view.state);\n if (!pluginState || pluginState.activeHandle == -1 || pluginState.dragging)\n return false;\n\n const cell = view.state.doc.nodeAt(pluginState.activeHandle)!;\n const width = currentColWidth(view, pluginState.activeHandle, cell.attrs);\n view.dispatch(\n view.state.tr.setMeta(columnResizingPluginKey, {\n setDragging: { startX: event.clientX, startWidth: width },\n }),\n );\n\n function finish(event: MouseEvent) {\n win.removeEventListener('mouseup', finish);\n win.removeEventListener('mousemove', move);\n const pluginState = columnResizingPluginKey.getState(view.state);\n if (pluginState?.dragging) {\n updateColumnWidth(\n view,\n pluginState.activeHandle,\n draggedWidth(pluginState.dragging, event, cellMinWidth),\n );\n view.dispatch(\n view.state.tr.setMeta(columnResizingPluginKey, { setDragging: null }),\n );\n }\n }\n\n function move(event: MouseEvent): void {\n if (!event.which) return finish(event);\n const pluginState = columnResizingPluginKey.getState(view.state);\n if (!pluginState) return;\n if (pluginState.dragging) {\n const dragged = draggedWidth(pluginState.dragging, event, cellMinWidth);\n displayColumnWidth(\n view,\n pluginState.activeHandle,\n dragged,\n defaultCellMinWidth,\n );\n }\n }\n\n displayColumnWidth(\n view,\n pluginState.activeHandle,\n width,\n defaultCellMinWidth,\n );\n\n win.addEventListener('mouseup', finish);\n win.addEventListener('mousemove', move);\n event.preventDefault();\n return true;\n}\n\nfunction currentColWidth(\n view: EditorView,\n cellPos: number,\n { colspan, colwidth }: Attrs,\n): number {\n const width = colwidth && colwidth[colwidth.length - 1];\n if (width) return width;\n const dom = view.domAtPos(cellPos);\n const node = dom.node.childNodes[dom.offset] as HTMLElement;\n let domWidth = node.offsetWidth,\n parts = colspan;\n if (colwidth)\n for (let i = 0; i < colspan; i++)\n if (colwidth[i]) {\n domWidth -= colwidth[i];\n parts--;\n }\n return domWidth / parts;\n}\n\nfunction domCellAround(target: HTMLElement | null): HTMLElement | null {\n while (target && target.nodeName != 'TD' && target.nodeName != 'TH')\n target =\n target.classList && target.classList.contains('ProseMirror')\n ? null\n : (target.parentNode as HTMLElement);\n return target;\n}\n\nfunction edgeCell(\n view: EditorView,\n event: MouseEvent,\n side: 'left' | 'right',\n handleWidth: number,\n): number {\n // posAtCoords returns inconsistent positions when cursor is moving\n // across a collapsed table border. Use an offset to adjust the\n // target viewport coordinates away from the table border.\n const offset = side == 'right' ? -handleWidth : handleWidth;\n const found = view.posAtCoords({\n left: event.clientX + offset,\n top: event.clientY,\n });\n if (!found) return -1;\n const { pos } = found;\n const $cell = cellAround(view.state.doc.resolve(pos));\n if (!$cell) return -1;\n if (side == 'right') return $cell.pos;\n const map = TableMap.get($cell.node(-1)),\n start = $cell.start(-1);\n const index = map.map.indexOf($cell.pos - start);\n return index % map.width == 0 ? -1 : start + map.map[index - 1];\n}\n\nfunction draggedWidth(\n dragging: Dragging,\n event: MouseEvent,\n resizeMinWidth: number,\n): number {\n const offset = event.clientX - dragging.startX;\n return Math.max(resizeMinWidth, dragging.startWidth + offset);\n}\n\nfunction updateHandle(view: EditorView, value: number): void {\n view.dispatch(\n view.state.tr.setMeta(columnResizingPluginKey, { setHandle: value }),\n );\n}\n\nfunction updateColumnWidth(\n view: EditorView,\n cell: number,\n width: number,\n): void {\n const $cell = view.state.doc.resolve(cell);\n const table = $cell.node(-1),\n map = TableMap.get(table),\n start = $cell.start(-1);\n const col =\n map.colCount($cell.pos - start) + $cell.nodeAfter!.attrs.colspan - 1;\n const tr = view.state.tr;\n for (let row = 0; row < map.height; row++) {\n const mapIndex = row * map.width + col;\n // Rowspanning cell that has already been handled\n if (row && map.map[mapIndex] == map.map[mapIndex - map.width]) continue;\n const pos = map.map[mapIndex];\n const attrs = table.nodeAt(pos)!.attrs as CellAttrs;\n const index = attrs.colspan == 1 ? 0 : col - map.colCount(pos);\n if (attrs.colwidth && attrs.colwidth[index] == width) continue;\n const colwidth = attrs.colwidth\n ? attrs.colwidth.slice()\n : zeroes(attrs.colspan);\n colwidth[index] = width;\n tr.setNodeMarkup(start + pos, null, { ...attrs, colwidth: colwidth });\n }\n if (tr.docChanged) view.dispatch(tr);\n}\n\nfunction displayColumnWidth(\n view: EditorView,\n cell: number,\n width: number,\n defaultCellMinWidth: number,\n): void {\n const $cell = view.state.doc.resolve(cell);\n const table = $cell.node(-1),\n start = $cell.start(-1);\n const col =\n TableMap.get(table).colCount($cell.pos - start) +\n $cell.nodeAfter!.attrs.colspan -\n 1;\n let dom: Node | null = view.domAtPos($cell.start(-1)).node;\n while (dom && dom.nodeName != 'TABLE') {\n dom = dom.parentNode;\n }\n if (!dom) return;\n updateColumnsOnResize(\n table,\n dom.firstChild as HTMLTableColElement,\n dom as HTMLTableElement,\n defaultCellMinWidth,\n col,\n width,\n );\n}\n\nfunction zeroes(n: number): 0[] {\n return Array(n).fill(0);\n}\n\nexport function handleDecorations(\n state: EditorState,\n cell: number,\n): DecorationSet {\n const decorations = [];\n const $cell = state.doc.resolve(cell);\n const table = $cell.node(-1);\n if (!table) {\n return DecorationSet.empty;\n }\n const map = TableMap.get(table);\n const start = $cell.start(-1);\n const col =\n map.colCount($cell.pos - start) + $cell.nodeAfter!.attrs.colspan - 1;\n for (let row = 0; row < map.height; row++) {\n const index = col + row * map.width;\n // For positions that have either a different cell or the end\n // of the table to their right, and either the top of the table or\n // a different cell above them, add a decoration\n if (\n (col == map.width - 1 || map.map[index] != map.map[index + 1]) &&\n (row == 0 || map.map[index] != map.map[index - map.width])\n ) {\n const cellPos = map.map[index];\n const pos = start + cellPos + table.nodeAt(cellPos)!.nodeSize - 1;\n const dom = document.createElement('div');\n dom.className = 'column-resize-handle';\n if (columnResizingPluginKey.getState(state)?.dragging) {\n decorations.push(\n Decoration.node(\n start + cellPos,\n start + cellPos + table.nodeAt(cellPos)!.nodeSize,\n {\n class: 'column-resize-dragging',\n },\n ),\n );\n }\n\n decorations.push(Decoration.widget(pos, dom));\n }\n }\n return DecorationSet.create(state.doc, decorations);\n}\n","// This file defines a plugin that handles the drawing of cell\n// selections and the basic user interactions for creating and working\n// with such selections. It also makes sure that, after each\n// transaction, the shapes of tables are normalized to be rectangular\n// and not contain overlapping cells.\n\nimport { Plugin } from 'prosemirror-state';\n\nimport { drawCellSelection, normalizeSelection } from './cellselection';\nimport { fixTables, fixTablesKey } from './fixtables';\nimport {\n handleKeyDown,\n handleMouseDown,\n handlePaste,\n handleTripleClick,\n} from './input';\nimport { tableEditingKey } from './util';\n\nexport { CellBookmark, CellSelection } from './cellselection';\nexport type { CellSelectionJSON } from './cellselection';\nexport {\n columnResizing,\n columnResizingPluginKey,\n ResizeState,\n} from './columnresizing';\nexport type { ColumnResizingOptions, Dragging } from './columnresizing';\nexport * from './commands';\nexport {\n clipCells as __clipCells,\n insertCells as __insertCells,\n pastedCells as __pastedCells,\n} from './copypaste';\nexport type { Area as __Area } from './copypaste';\nexport type { Direction } from './input';\nexport { tableNodes, tableNodeTypes } from './schema';\nexport type {\n CellAttributes,\n getFromDOM,\n setDOMAttr,\n TableNodes,\n TableNodesOptions,\n TableRole,\n} from './schema';\nexport { TableMap } from './tablemap';\nexport type { ColWidths, Problem, Rect } from './tablemap';\nexport { TableView, updateColumnsOnResize } from './tableview';\nexport {\n addColSpan,\n cellAround,\n cellNear,\n colCount,\n columnIsHeader,\n findCell,\n inSameTable,\n isInTable,\n moveCellForward,\n nextCell,\n pointsAtCell,\n removeColSpan,\n selectionCell,\n} from './util';\nexport type { MutableAttrs } from './util';\nexport { findCellPos, findCellRange, findTable } from './utils/query';\nexport type { FindNodeResult } from './utils/query';\nexport { fixTables, fixTablesKey, handlePaste, tableEditingKey };\n\n/**\n * @public\n */\nexport type TableEditingOptions = {\n /**\n * Whether to allow table node selection.\n *\n * By default, any node selection wrapping a table will be converted into a\n * CellSelection wrapping all cells in the table. You can pass `true` to allow\n * the selection to remain a NodeSelection.\n *\n * @default false\n */\n allowTableNodeSelection?: boolean;\n};\n\n/**\n * Creates a [plugin](http://prosemirror.net/docs/ref/#state.Plugin)\n * that, when added to an editor, enables cell-selection, handles\n * cell-based copy/paste, and makes sure tables stay well-formed (each\n * row has the same width, and cells don't overlap).\n *\n * You should probably put this plugin near the end of your array of\n * plugins, since it handles mouse and arrow key events in tables\n * rather broadly, and other plugins, like the gap cursor or the\n * column-width dragging plugin, might want to get a turn first to\n * perform more specific behavior.\n *\n * @public\n */\nexport function tableEditing({\n allowTableNodeSelection = false,\n}: TableEditingOptions = {}): Plugin {\n return new Plugin({\n key: tableEditingKey,\n\n // This piece of state is used to remember when a mouse-drag\n // cell-selection is happening, so that it can continue even as\n // transactions (which might move its anchor cell) come in.\n state: {\n init() {\n return null;\n },\n apply(tr, cur) {\n const set = tr.getMeta(tableEditingKey);\n if (set != null) return set == -1 ? null : set;\n if (cur == null || !tr.docChanged) return cur;\n const { deleted, pos } = tr.mapping.mapResult(cur);\n return deleted ? null : pos;\n },\n },\n\n props: {\n decorations: drawCellSelection,\n\n handleDOMEvents: {\n mousedown: handleMouseDown,\n },\n\n createSelectionBetween(view) {\n return tableEditingKey.getState(view.state) != null\n ? view.state.selection\n : null;\n },\n\n handleTripleClick,\n\n handleKeyDown,\n\n handlePaste,\n },\n\n appendTransaction(_, oldState, state) {\n return normalizeSelection(\n state,\n fixTables(state, oldState),\n allowTableNodeSelection,\n );\n },\n });\n}\n","import type { Editor } from \"@tiptap/core\";\nimport type { Node as ProseMirrorNode } from \"@tiptap/pm/model\";\nimport { TableMap } from \"prosemirror-tables\";\nimport {\n DEFAULT_TABLE_ROW_HEIGHT,\n isCrossRealmHTMLElement,\n isCrossRealmTable,\n isCrossRealmTableCell,\n isCrossRealmTableRow,\n isValidProseMirrorPosition,\n resolveEventElement,\n} from \"./table-dom-utils\";\nimport { normalizeTableWidthMode, type UEditorTableWidthMode } from \"./table-width-model\";\n\nconst FALLBACK_TABLE_ROW_HEIGHT = DEFAULT_TABLE_ROW_HEIGHT;\nconst FALLBACK_TABLE_COLUMN_WIDTH = 160;\n\nfunction isTableCellElement(element: Element | null): element is HTMLTableCellElement {\n return isCrossRealmTableCell(element);\n}\n\nfunction isTableRowElement(element: Element | null): element is HTMLTableRowElement {\n return isCrossRealmTableRow(element);\n}\n\nfunction isTableElement(element: Element | null): element is HTMLTableElement {\n return isCrossRealmTable(element);\n}\n\nfunction isHTMLElement(element: Element | null): element is HTMLElement {\n return isCrossRealmHTMLElement(element);\n}\n\nexport type TableAxisHandle = {\n index: number;\n cellPos: number;\n start: number;\n size: number;\n center: number;\n};\n\nexport type TableControlLayout = {\n cellPos: number;\n cornerCellPos: number;\n activeRowIndex: number;\n activeColumnIndex: number;\n tableLeft: number;\n tableTop: number;\n tableWidth: number;\n tableHeight: number;\n wrapperLeft: number;\n wrapperTop: number;\n wrapperWidth: number;\n wrapperHeight: number;\n viewportWidth: number;\n viewportHeight: number;\n horizontalScrollbarHeight: number;\n verticalScrollbarWidth: number;\n avgRowHeight: number;\n avgColumnWidth: number;\n rowHandles: TableAxisHandle[];\n columnHandles: TableAxisHandle[];\n widthMode: UEditorTableWidthMode;\n};\n\nexport type TableInfo = {\n node: ProseMirrorNode;\n pos: number;\n start: number;\n};\n\nexport function getVisibleTableBounds(layout: Pick<\n TableControlLayout,\n \"tableLeft\" | \"tableTop\" | \"tableWidth\" | \"tableHeight\" | \"wrapperLeft\" | \"wrapperTop\" | \"viewportWidth\" | \"viewportHeight\"\n>) {\n const left = Math.max(layout.tableLeft, layout.wrapperLeft);\n const top = Math.max(layout.tableTop, layout.wrapperTop);\n const right = Math.min(layout.tableLeft + layout.tableWidth, layout.wrapperLeft + layout.viewportWidth);\n const bottom = Math.min(layout.tableTop + layout.tableHeight, layout.wrapperTop + layout.viewportHeight);\n\n return {\n left,\n top,\n right,\n bottom,\n width: Math.max(0, right - left),\n height: Math.max(0, bottom - top),\n };\n}\n\nfunction metricOrFallback(value: number, fallback: number) {\n return Number.isFinite(value) && value > 0 ? value : fallback;\n}\n\nfunction parsePixelMetric(value: string | null | undefined) {\n if (!value) return null;\n const parsed = Number.parseFloat(value);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : null;\n}\n\nfunction getPrimaryCell(table: HTMLTableElement) {\n const cell = table.querySelector(\"th,td\");\n return isTableCellElement(cell) ? cell : null;\n}\n\nfunction getLastCell(table: HTMLTableElement) {\n const lastRow = table.rows.item(table.rows.length - 1);\n if (!isTableRowElement(lastRow)) return null;\n const cell = lastRow.cells.item(lastRow.cells.length - 1);\n return isTableCellElement(cell) ? cell : null;\n}\n\nexport function getCellFromTarget(target: EventTarget | Node | null) {\n const element = resolveEventElement(target);\n if (!element) return null;\n\n const directCell = element.closest(\"th,td\");\n if (isTableCellElement(directCell)) {\n return directCell;\n }\n\n const table = element.closest(\"table\");\n if (isTableElement(table)) {\n return getPrimaryCell(table);\n }\n\n return null;\n}\n\nexport function findTableInfo(editor: Editor, pos: number): TableInfo | null {\n if (!isValidProseMirrorPosition(editor.state.doc, pos)) return null;\n\n const $pos = editor.state.doc.resolve(pos);\n\n for (let depth = $pos.depth; depth > 0; depth -= 1) {\n const node = $pos.node(depth);\n if (node.type.name === \"table\") {\n return {\n node,\n pos: $pos.before(depth),\n start: $pos.start(depth),\n };\n }\n }\n\n return null;\n}\n\nfunction getCellRelativePosFromDomPos(map: TableMap, tableStart: number, domPos: number) {\n const relativeDomPos = domPos - tableStart;\n const seen = new Set<number>();\n\n for (const relativeCellPos of map.map) {\n if (seen.has(relativeCellPos)) continue;\n seen.add(relativeCellPos);\n\n if (relativeDomPos === relativeCellPos || relativeDomPos === relativeCellPos + 1) {\n return relativeCellPos;\n }\n }\n\n return null;\n}\n\nfunction buildLogicalColumnMetrics({\n editor,\n surface,\n surfaceRect,\n tableElement,\n tableInfo,\n tableLeft,\n tableWidth,\n}: {\n editor: Editor;\n surface: HTMLDivElement;\n surfaceRect: DOMRect;\n tableElement: HTMLTableElement;\n tableInfo: TableInfo;\n tableLeft: number;\n tableWidth: number;\n}): TableAxisHandle[] {\n const map = TableMap.get(tableInfo.node);\n const fallbackWidth = metricOrFallback(tableWidth / map.width, FALLBACK_TABLE_COLUMN_WIDTH);\n const firstRow = tableElement.rows.item(0);\n const visualColumns: TableAxisHandle[] = [];\n\n if (firstRow) {\n for (const tableCell of Array.from(firstRow.cells)) {\n if (!isTableCellElement(tableCell)) continue;\n\n const cellPos = editor.view.posAtDOM(tableCell, 0);\n if (!isValidProseMirrorPosition(editor.state.doc, cellPos)) continue;\n const relativeCellPos = getCellRelativePosFromDomPos(map, tableInfo.start, cellPos);\n if (relativeCellPos == null) continue;\n\n const cellMapRect = map.findCell(relativeCellPos);\n const cellRect = tableCell.getBoundingClientRect();\n const cellStart = cellRect.width > 0\n ? cellRect.left - surfaceRect.left - surface.clientLeft + surface.scrollLeft\n : tableLeft + cellMapRect.left * fallbackWidth;\n const size = metricOrFallback(cellRect.width, fallbackWidth * Math.max(1, cellMapRect.right - cellMapRect.left));\n\n visualColumns.push({\n index: cellMapRect.left,\n cellPos: tableInfo.start + relativeCellPos,\n start: cellStart,\n size,\n center: cellStart + size / 2,\n });\n }\n }\n\n if (visualColumns.length > 0) {\n return visualColumns.sort((a, b) => a.index - b.index);\n }\n\n const cols = Array.from(tableElement.querySelectorAll<HTMLTableColElement>(\"colgroup > col\"));\n const parsedWidths = cols.slice(0, map.width).map((col) => parsePixelMetric(col.style.width) ?? parsePixelMetric(col.getAttribute(\"width\")));\n const hasCompleteColWidths = parsedWidths.length >= map.width && parsedWidths.every((width): width is number => typeof width === \"number\");\n\n let cursor = tableLeft;\n\n return Array.from({ length: map.width }, (_, index) => {\n const size = hasCompleteColWidths ? parsedWidths[index] : fallbackWidth;\n const start = hasCompleteColWidths ? cursor : tableLeft + index * fallbackWidth;\n cursor += size;\n\n return {\n index,\n cellPos: tableInfo.start + map.positionAt(0, index, tableInfo.node),\n start,\n size,\n center: start + size / 2,\n };\n });\n}\n\nfunction buildLogicalRowMetrics({\n editor,\n surface,\n surfaceRect,\n tableInfo,\n rows,\n tableTop,\n tableHeight,\n cornerCell,\n}: {\n editor: Editor;\n surface: HTMLDivElement;\n surfaceRect: DOMRect;\n tableInfo: TableInfo;\n rows: HTMLTableRowElement[];\n tableTop: number;\n tableHeight: number;\n cornerCell: HTMLTableCellElement;\n}): TableAxisHandle[] {\n const map = TableMap.get(tableInfo.node);\n const fallbackHeight = metricOrFallback(tableHeight / map.height, FALLBACK_TABLE_ROW_HEIGHT);\n const visualRows: TableAxisHandle[] = [];\n const seenCellPositions = new Set<number>();\n\n for (let rowIndex = 0; rowIndex < map.height; rowIndex += 1) {\n const relativeCellPos = map.map[rowIndex * map.width];\n if (seenCellPositions.has(relativeCellPos)) continue;\n seenCellPositions.add(relativeCellPos);\n\n const cellMapRect = map.findCell(relativeCellPos);\n const cellDom = editor.view.nodeDOM(tableInfo.start + relativeCellPos);\n const cellCandidate = cellDom as Element | null;\n const tableCell = isTableCellElement(cellCandidate) ? cellCandidate : null;\n\n if (tableCell) {\n const cellRect = tableCell.getBoundingClientRect();\n const start = cellRect.height > 0\n ? cellRect.top - surfaceRect.top - surface.clientTop + surface.scrollTop\n : tableTop + cellMapRect.top * fallbackHeight;\n const size = metricOrFallback(cellRect.height, fallbackHeight * Math.max(1, cellMapRect.bottom - cellMapRect.top));\n\n visualRows.push({\n index: cellMapRect.top,\n cellPos: tableInfo.start + relativeCellPos,\n start,\n size,\n center: start + size / 2,\n });\n }\n }\n\n if (visualRows.length > 0) {\n return visualRows.sort((a, b) => a.index - b.index);\n }\n\n return rows.flatMap((tableRow, index) => {\n const rowRect = tableRow.getBoundingClientRect();\n const anchorCell = tableRow.cells.item(0) ?? cornerCell;\n const start = rowRect.height > 0\n ? rowRect.top - surfaceRect.top - surface.clientTop + surface.scrollTop\n : tableTop + index * fallbackHeight;\n const size = metricOrFallback(rowRect.height, fallbackHeight);\n\n const cellPos = editor.view.posAtDOM(anchorCell, 0);\n if (!isValidProseMirrorPosition(editor.state.doc, cellPos)) return [];\n\n return [{\n index,\n cellPos,\n start,\n size,\n center: start + size / 2,\n }];\n });\n}\n\nexport function getLastCellPosFromState(editor: Editor, pos: number) {\n const tableInfo = findTableInfo(editor, pos);\n if (!tableInfo) return null;\n\n const map = TableMap.get(tableInfo.node);\n return tableInfo.start + map.positionAt(map.height - 1, map.width - 1, tableInfo.node);\n}\n\nexport function getTableCellTextSelectionRange(editor: Editor, cellPos: number) {\n const cellNode = editor.state.doc.nodeAt(cellPos);\n if (!cellNode || (cellNode.type.name !== \"tableCell\" && cellNode.type.name !== \"tableHeader\")) {\n return null;\n }\n\n let from: number | null = null;\n let to: number | null = null;\n\n cellNode.descendants((node, relativePos) => {\n if (!node.isText || node.nodeSize === 0) return true;\n\n const textStart = cellPos + 1 + relativePos;\n from ??= textStart;\n to = textStart + node.nodeSize;\n return true;\n });\n\n return from !== null && to !== null && from < to ? { from, to } : null;\n}\n\nexport function buildTableControlLayout(editor: Editor, surface: HTMLDivElement, cell: HTMLTableCellElement): TableControlLayout | null {\n if (!editor.view.dom.contains(cell)) return null;\n\n const row = cell.closest(\"tr\");\n const table = cell.closest(\"table\");\n if (!isTableRowElement(row) || !isTableElement(table)) {\n return null;\n }\n\n const rows = Array.from(table.rows).filter(isTableRowElement);\n const cornerCell = getLastCell(table);\n const cellPos = editor.view.posAtDOM(cell, 0);\n if (!isValidProseMirrorPosition(editor.state.doc, cellPos)) return null;\n const tableInfo = findTableInfo(editor, cellPos);\n if (rows.length === 0 || !tableInfo || !isTableCellElement(cornerCell)) {\n return null;\n }\n\n const map = TableMap.get(tableInfo.node);\n const surfaceRect = surface.getBoundingClientRect();\n // Absolute controls are positioned against the surface padding box, not its\n // viewport border edge. Keep rect measurements and CSS coordinates in sync\n // when a popup/editor surface has a border or its own scroll offset.\n const surfaceOriginLeft = surfaceRect.left + surface.clientLeft;\n const surfaceOriginTop = surfaceRect.top + surface.clientTop;\n const tableRect = table.getBoundingClientRect();\n const explicitColumnWidths = Array.from(table.querySelectorAll<HTMLTableColElement>(\"colgroup > col\"))\n .slice(0, map.width)\n .map((column) => parsePixelMetric(column.style.width));\n const explicitTableWidth = parsePixelMetric(table.style.width)\n ?? (explicitColumnWidths.length === map.width && explicitColumnWidths.every((width): width is number => width !== null)\n ? explicitColumnWidths.reduce((sum, width) => sum + width, 0)\n : null);\n const explicitRowHeights = rows.map((tableRow) => (\n parsePixelMetric(tableRow.getAttribute(\"data-row-height\"))\n ?? parsePixelMetric(tableRow.style.height)\n ));\n const explicitTableHeight = explicitRowHeights.every((height): height is number => height !== null)\n ? explicitRowHeights.reduce((sum, height) => sum + height, 0)\n : null;\n const wrapperElement = table.closest(\".tableWrapper\");\n const wrapper = isHTMLElement(wrapperElement) ? wrapperElement : null;\n const wrapperRect = wrapper?.getBoundingClientRect() ?? tableRect;\n const tableLeft = tableRect.left - surfaceOriginLeft + surface.scrollLeft;\n const tableTop = tableRect.top - surfaceOriginTop + surface.scrollTop;\n const tableWidth = metricOrFallback(tableRect.width, explicitTableWidth ?? FALLBACK_TABLE_COLUMN_WIDTH * map.width);\n const tableHeight = metricOrFallback(tableRect.height, explicitTableHeight ?? FALLBACK_TABLE_ROW_HEIGHT * rows.length);\n const avgRowHeight = metricOrFallback(tableHeight / rows.length, FALLBACK_TABLE_ROW_HEIGHT);\n const avgColumnWidth = metricOrFallback(tableWidth / map.width, FALLBACK_TABLE_COLUMN_WIDTH);\n const wrapperLeft = wrapperRect.left - surfaceOriginLeft + surface.scrollLeft;\n const wrapperTop = wrapperRect.top - surfaceOriginTop + surface.scrollTop;\n const wrapperWidth = metricOrFallback(wrapperRect.width, tableWidth);\n const wrapperHeight = metricOrFallback(wrapperRect.height, tableHeight);\n const viewportWidth = metricOrFallback(wrapper?.clientWidth ?? wrapperRect.width, tableWidth);\n const viewportHeight = metricOrFallback(wrapper?.clientHeight ?? wrapperRect.height, tableHeight);\n const verticalScrollbarWidth = Math.max(0, Math.round(wrapperWidth - viewportWidth));\n const horizontalScrollbarHeight = Math.max(0, Math.round(wrapperHeight - viewportHeight));\n\n const rowHandles = buildLogicalRowMetrics({\n editor,\n surface,\n surfaceRect,\n tableInfo,\n rows,\n tableTop,\n tableHeight,\n cornerCell,\n });\n\n const columnHandles = buildLogicalColumnMetrics({\n editor,\n surface,\n surfaceRect,\n tableElement: table,\n tableInfo,\n tableLeft,\n tableWidth,\n });\n const activeCellRelativePos = getCellRelativePosFromDomPos(map, tableInfo.start, cellPos);\n const activeCellRect = activeCellRelativePos != null ? map.findCell(activeCellRelativePos) : { left: cell.cellIndex, top: row.rowIndex };\n const normalizedCellPos = activeCellRelativePos != null ? tableInfo.start + activeCellRelativePos : cellPos;\n\n return {\n cellPos: normalizedCellPos,\n cornerCellPos: tableInfo.start + map.positionAt(map.height - 1, map.width - 1, tableInfo.node),\n activeRowIndex: activeCellRect.top,\n activeColumnIndex: activeCellRect.left,\n tableLeft,\n tableTop,\n tableWidth,\n tableHeight,\n wrapperLeft,\n wrapperTop,\n wrapperWidth,\n wrapperHeight,\n viewportWidth,\n viewportHeight,\n horizontalScrollbarHeight,\n verticalScrollbarWidth,\n avgRowHeight,\n avgColumnWidth,\n rowHandles,\n columnHandles,\n widthMode: normalizeTableWidthMode(tableInfo.node.attrs.widthMode),\n };\n}\n","import type { Editor } from \"@tiptap/core\";\nimport type { Node as ProseMirrorNode } from \"@tiptap/pm/model\";\nimport { TableMap } from \"prosemirror-tables\";\nimport { MIN_RESIZED_TABLE_COLUMN_WIDTH } from \"./table-column-resize\";\nimport { MIN_TABLE_ROW_HEIGHT } from \"./table-dom-utils\";\nimport { findTableInfo } from \"./table-layout-model\";\nimport {\n clampResponsiveTableWidthBp,\n getResponsiveTableOffsetBp,\n getResponsiveTableWidthBp,\n getTableColumnRatios,\n normalizeColumnRatios,\n normalizeTableWidthMode,\n resolveResponsiveTableOffsetBp,\n TABLE_WIDTH_BASIS_POINTS,\n type UEditorTableWidthMode,\n} from \"./table-width-model\";\n\nconst MAX_TABLE_DIMENSION = 8192;\n\nexport type TableSizeSnapshot = {\n anchorPos: number;\n tablePos: number;\n startWidth: number;\n startHeight: number;\n columnWidths: number[];\n rowHeights: number[];\n minWidth: number;\n minHeight: number;\n containerWidth: number;\n widthMode: UEditorTableWidthMode;\n widthBp: number;\n offsetBp: number;\n columnRatios: number[];\n};\n\nexport type TableResizeDimensions = {\n width: number;\n height: number;\n widthBp?: number;\n offsetBp?: number;\n leftDelta?: number;\n};\n\nexport type TableResizeEdge = \"both\" | \"left\" | \"right\";\n\nfunction positiveMetric(value: unknown, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0 ? value : fallback;\n}\n\nexport function normalizeWeightsToTotal(values: number[], total: number, minimum: number) {\n if (values.length === 0) return [];\n\n const safeTotal = Math.max(values.length * minimum, Math.round(total));\n const positiveValues = values.map((value) => positiveMetric(value, 1));\n const weightSum = positiveValues.reduce((sum, value) => sum + value, 0);\n const raw = positiveValues.map((value) => (value / weightSum) * safeTotal);\n const normalized = raw.map((value) => Math.max(minimum, Math.round(value)));\n\n let difference = safeTotal - normalized.reduce((sum, value) => sum + value, 0);\n while (difference !== 0) {\n let changed = false;\n\n for (let index = normalized.length - 1; index >= 0 && difference !== 0; index -= 1) {\n if (difference < 0 && normalized[index] <= minimum) continue;\n normalized[index] += difference > 0 ? 1 : -1;\n difference += difference > 0 ? -1 : 1;\n changed = true;\n }\n\n if (!changed) break;\n }\n\n return normalized;\n}\n\nfunction getLogicalColumnWidths(table: ProseMirrorNode, tableMap: TableMap, fallback: number) {\n return Array.from({ length: tableMap.width }, (_, columnIndex) => {\n const relativeCellPos = tableMap.positionAt(0, columnIndex, table);\n const cell = table.nodeAt(relativeCellPos);\n if (!cell) return fallback;\n\n const cellStartColumn = tableMap.colCount(relativeCellPos);\n const widthIndex = columnIndex - cellStartColumn;\n const colwidth = cell.attrs.colwidth as number[] | null | undefined;\n return positiveMetric(colwidth?.[widthIndex], fallback);\n });\n}\n\nfunction getLogicalRowHeights(table: ProseMirrorNode, fallback: number) {\n const heights: number[] = [];\n table.forEach((row) => {\n heights.push(positiveMetric(row.attrs.rowHeight, fallback));\n });\n return heights;\n}\n\nexport function createTableSizeSnapshot(\n editor: Editor,\n anchorPos: number,\n startWidth: number,\n startHeight: number,\n containerWidth = startWidth,\n): TableSizeSnapshot | null {\n const tableInfo = findTableInfo(editor, anchorPos);\n if (!tableInfo) return null;\n\n const tableMap = TableMap.get(tableInfo.node);\n if (tableMap.width === 0 || tableMap.height === 0) return null;\n\n const safeWidth = Math.max(tableMap.width * MIN_RESIZED_TABLE_COLUMN_WIDTH, Math.round(startWidth));\n const safeHeight = Math.max(tableMap.height * MIN_TABLE_ROW_HEIGHT, Math.round(startHeight));\n const fallbackColumnWidth = safeWidth / tableMap.width;\n const fallbackRowHeight = safeHeight / tableMap.height;\n const widthMode = normalizeTableWidthMode(tableInfo.node.attrs.widthMode);\n const safeContainerWidth = Math.max(1, Math.round(containerWidth));\n const columnWeights = widthMode === \"responsive\"\n ? getTableColumnRatios(tableInfo.node)\n : getLogicalColumnWidths(tableInfo.node, tableMap, fallbackColumnWidth);\n\n return {\n anchorPos,\n tablePos: tableInfo.pos,\n startWidth: safeWidth,\n startHeight: safeHeight,\n columnWidths: normalizeWeightsToTotal(\n columnWeights,\n safeWidth,\n MIN_RESIZED_TABLE_COLUMN_WIDTH,\n ),\n rowHeights: normalizeWeightsToTotal(\n getLogicalRowHeights(tableInfo.node, fallbackRowHeight),\n safeHeight,\n MIN_TABLE_ROW_HEIGHT,\n ),\n minWidth: tableMap.width * MIN_RESIZED_TABLE_COLUMN_WIDTH,\n minHeight: tableMap.height * MIN_TABLE_ROW_HEIGHT,\n containerWidth: safeContainerWidth,\n widthMode,\n widthBp: getResponsiveTableWidthBp(tableInfo.node),\n offsetBp: getResponsiveTableOffsetBp(tableInfo.node),\n columnRatios: getTableColumnRatios(tableInfo.node),\n };\n}\n\nexport function resolveTableResizeDimensions({\n deltaX,\n deltaY,\n lockAxis,\n preserveRatio,\n edge = \"both\",\n snapshot,\n}: {\n deltaX: number;\n deltaY: number;\n lockAxis: boolean;\n preserveRatio: boolean;\n edge?: TableResizeEdge;\n snapshot: TableSizeSnapshot;\n}): TableResizeDimensions {\n const horizontalDelta = edge === \"left\" ? -deltaX : deltaX;\n let width = snapshot.startWidth + horizontalDelta;\n let height = edge === \"both\" ? snapshot.startHeight + deltaY : snapshot.startHeight;\n\n if (preserveRatio) {\n const horizontalDrag = edge !== \"both\" || Math.abs(deltaX) >= Math.abs(deltaY);\n const scale = horizontalDrag\n ? width / snapshot.startWidth\n : height / snapshot.startHeight;\n\n const minScale = Math.max(\n snapshot.minWidth / snapshot.startWidth,\n snapshot.minHeight / snapshot.startHeight,\n );\n const maxScale = Math.min(\n MAX_TABLE_DIMENSION / snapshot.startWidth,\n MAX_TABLE_DIMENSION / snapshot.startHeight,\n );\n const safeScale = Math.min(Math.max(scale, minScale), maxScale);\n width = snapshot.startWidth * safeScale;\n height = snapshot.startHeight * safeScale;\n } else if (lockAxis && edge === \"both\") {\n if (Math.abs(deltaX) >= Math.abs(deltaY)) {\n height = snapshot.startHeight;\n } else {\n width = snapshot.startWidth;\n }\n }\n\n let nextWidth = Math.min(MAX_TABLE_DIMENSION, Math.max(snapshot.minWidth, Math.round(width)));\n const nextHeight = Math.min(MAX_TABLE_DIMENSION, Math.max(snapshot.minHeight, Math.round(height)));\n\n if (snapshot.widthMode !== \"responsive\") {\n return { width: nextWidth, height: nextHeight };\n }\n\n const containerWidth = Math.max(1, snapshot.containerWidth);\n const startOffset = (snapshot.offsetBp / TABLE_WIDTH_BASIS_POINTS) * containerWidth;\n let nextOffset = startOffset;\n\n if (edge === \"left\") {\n const fixedRightEdge = startOffset + snapshot.startWidth;\n nextOffset = Math.min(\n fixedRightEdge - snapshot.minWidth,\n Math.max(0, startOffset + deltaX),\n );\n nextWidth = fixedRightEdge - nextOffset;\n }\n\n const widthBp = clampResponsiveTableWidthBp(\n (nextWidth / containerWidth) * TABLE_WIDTH_BASIS_POINTS,\n );\n const offsetBp = resolveResponsiveTableOffsetBp(\n widthBp,\n null,\n (nextOffset / containerWidth) * TABLE_WIDTH_BASIS_POINTS,\n );\n\n return {\n width: Math.round((widthBp / TABLE_WIDTH_BASIS_POINTS) * containerWidth),\n height: nextHeight,\n widthBp,\n offsetBp,\n leftDelta: nextOffset - startOffset,\n };\n}\n\nfunction arraysEqual(left: unknown, right: number[]) {\n return Array.isArray(left)\n && left.length === right.length\n && left.every((value, index) => value === right[index]);\n}\n\nfunction getResponsiveResizeAlignment(widthBp: number, offsetBp: number) {\n const gap = Math.max(0, TABLE_WIDTH_BASIS_POINTS - widthBp);\n if (offsetBp === 0) return \"left\";\n if (offsetBp === gap) return \"right\";\n if (Math.abs(offsetBp * 2 - gap) <= 1) return \"center\";\n return null;\n}\n\nexport function applyTableSize(\n editor: Editor,\n snapshot: TableSizeSnapshot,\n dimensions: TableResizeDimensions,\n options: { widthMode?: UEditorTableWidthMode } = {},\n) {\n const table = editor.state.doc.nodeAt(snapshot.tablePos);\n if (!table || table.type.name !== \"table\") return false;\n\n const tableMap = TableMap.get(table);\n if (tableMap.width !== snapshot.columnWidths.length || tableMap.height !== snapshot.rowHeights.length) {\n return false;\n }\n\n const resizeWidth = dimensions.width !== snapshot.startWidth;\n const resizeHeight = dimensions.height !== snapshot.startHeight;\n const widthMode = options.widthMode ?? snapshot.widthMode;\n const widthModeChanged = normalizeTableWidthMode(table.attrs.widthMode) !== widthMode\n || (widthMode === \"responsive\" && table.attrs.widthMode !== \"responsive\");\n const widthBp = dimensions.widthBp\n ?? clampResponsiveTableWidthBp(\n (dimensions.width / Math.max(1, snapshot.containerWidth)) * TABLE_WIDTH_BASIS_POINTS,\n );\n const offsetBp = resolveResponsiveTableOffsetBp(\n widthBp,\n null,\n dimensions.offsetBp ?? snapshot.offsetBp,\n );\n const responsiveLayoutChanged = widthMode === \"responsive\"\n && (table.attrs.widthBp !== widthBp || table.attrs.offsetBp !== offsetBp);\n if (!resizeWidth && !resizeHeight && !widthModeChanged && !responsiveLayoutChanged) return false;\n\n const tableStart = snapshot.tablePos + 1;\n const transaction = editor.state.tr;\n\n if (widthModeChanged || responsiveLayoutChanged) {\n transaction.setNodeMarkup(snapshot.tablePos, undefined, {\n ...table.attrs,\n widthMode,\n ...(widthMode === \"responsive\"\n ? {\n widthBp,\n offsetBp,\n columnRatios: normalizeColumnRatios(snapshot.columnRatios, tableMap.width),\n textAlign: getResponsiveResizeAlignment(widthBp, offsetBp),\n }\n : null),\n });\n }\n\n if (resizeWidth) {\n const nextColumnWidths = normalizeWeightsToTotal(\n snapshot.columnWidths,\n dimensions.width,\n MIN_RESIZED_TABLE_COLUMN_WIDTH,\n );\n const seenCellPositions = new Set<number>();\n\n for (const relativeCellPos of tableMap.map) {\n if (seenCellPositions.has(relativeCellPos)) continue;\n seenCellPositions.add(relativeCellPos);\n\n const cell = table.nodeAt(relativeCellPos);\n if (!cell) continue;\n\n const cellRect = tableMap.findCell(relativeCellPos);\n const colwidth = nextColumnWidths.slice(cellRect.left, cellRect.right);\n if (arraysEqual(cell.attrs.colwidth, colwidth)) continue;\n\n transaction.setNodeMarkup(tableStart + relativeCellPos, undefined, {\n ...cell.attrs,\n colwidth,\n });\n }\n }\n\n if (resizeHeight) {\n const nextRowHeights = normalizeWeightsToTotal(\n snapshot.rowHeights,\n dimensions.height,\n MIN_TABLE_ROW_HEIGHT,\n );\n\n table.forEach((row, offset, rowIndex) => {\n const rowHeight = nextRowHeights[rowIndex];\n if (row.attrs.rowHeight === rowHeight) return;\n\n transaction.setNodeMarkup(tableStart + offset, undefined, {\n ...row.attrs,\n rowHeight,\n });\n });\n }\n\n if (!transaction.docChanged) return false;\n editor.view.dispatch(transaction);\n return true;\n}\n","export type TableCellAddress = {\n column: number;\n row: number;\n label: string;\n};\n\nexport type TableCellRange = {\n from: TableCellAddress;\n to: TableCellAddress;\n};\n\nexport type FormulaEvaluationResult =\n | {\n value: number;\n error: null;\n }\n | {\n value: null;\n error: \"empty\" | \"invalid-reference\" | \"invalid-formula\" | \"division-by-zero\" | \"circular-reference\";\n };\n\nexport type TableFormulaCell = {\n label: string;\n formula: string;\n};\n\nexport type TableFormulaDependencyGraph = {\n dependencies: Map<string, Set<string>>;\n dependents: Map<string, Set<string>>;\n formulas: Map<string, string>;\n};\n\nexport type TableNumberFormat = \"text\" | \"number\" | \"currency\" | \"percent\" | \"date\";\n\ntype FormulaToken =\n | { type: \"number\"; value: number }\n | { type: \"cell\"; value: string }\n | { type: \"range\"; value: string }\n | { type: \"function\"; value: string }\n | { type: \"operator\"; value: \"+\" | \"-\" | \"*\" | \"/\" }\n | { type: \"paren\"; value: \"(\" | \")\" }\n | { type: \"comma\"; value: \",\" };\n\nconst CELL_ADDRESS_RE = /^(\\$?)([A-Z]+)(\\$?)([1-9]\\d*)$/i;\nconst CELL_RANGE_RE = /^(\\$?[A-Z]+\\$?[1-9]\\d*):(\\$?[A-Z]+\\$?[1-9]\\d*)$/i;\nconst SUPPORTED_FUNCTIONS = new Set([\"SUM\", \"AVG\", \"MIN\", \"MAX\", \"COUNT\"]);\n\nexport function columnNameToIndex(columnName: string) {\n const normalized = columnName.trim().toUpperCase();\n if (!/^[A-Z]+$/.test(normalized)) {\n return -1;\n }\n\n let index = 0;\n for (const char of normalized) {\n index = index * 26 + char.charCodeAt(0) - 64;\n }\n return index - 1;\n}\n\nexport function indexToColumnName(index: number) {\n if (!Number.isInteger(index) || index < 0) {\n return \"\";\n }\n\n let value = index + 1;\n let name = \"\";\n while (value > 0) {\n const remainder = (value - 1) % 26;\n name = String.fromCharCode(65 + remainder) + name;\n value = Math.floor((value - 1) / 26);\n }\n return name;\n}\n\nexport function parseTableCellAddress(input: string): TableCellAddress | null {\n const match = input.trim().match(CELL_ADDRESS_RE);\n if (!match) {\n return null;\n }\n\n const column = columnNameToIndex(match[2] ?? \"\");\n const row = Number.parseInt(match[4] ?? \"\", 10) - 1;\n if (column < 0 || row < 0) {\n return null;\n }\n\n return {\n column,\n row,\n label: `${indexToColumnName(column)}${row + 1}`,\n };\n}\n\nexport function parseTableCellRange(input: string): TableCellRange | null {\n const match = input.trim().match(CELL_RANGE_RE);\n if (!match) {\n return null;\n }\n\n const from = parseTableCellAddress(match[1] ?? \"\");\n const to = parseTableCellAddress(match[2] ?? \"\");\n if (!from || !to) {\n return null;\n }\n\n return { from, to };\n}\n\nexport function getTableCellRangeLabels(range: TableCellRange) {\n const startColumn = Math.min(range.from.column, range.to.column);\n const endColumn = Math.max(range.from.column, range.to.column);\n const startRow = Math.min(range.from.row, range.to.row);\n const endRow = Math.max(range.from.row, range.to.row);\n const labels: string[] = [];\n\n for (let row = startRow; row <= endRow; row += 1) {\n for (let column = startColumn; column <= endColumn; column += 1) {\n labels.push(`${indexToColumnName(column)}${row + 1}`);\n }\n }\n\n return labels;\n}\n\nexport function normalizeTableFormula(formula: string) {\n return formula.trim().replace(/^=/, \"\").trim();\n}\n\nexport function isDraftTableFormula(formula: string) {\n const normalized = normalizeTableFormula(formula);\n if (!normalized) return true;\n\n let depth = 0;\n for (const char of normalized) {\n if (char === \"(\") depth += 1;\n if (char === \")\") depth -= 1;\n if (depth < 0) return false;\n }\n\n if (depth > 0) return true;\n if (/^[A-Z]+\\(\\s*\\)$/i.test(normalized)) return true;\n if (/[+\\-*/,(]\\s*$/.test(normalized)) return true;\n\n return false;\n}\n\nexport function formatFormulaError(error: NonNullable<FormulaEvaluationResult[\"error\"]>) {\n return `#${error.toUpperCase()}`;\n}\n\nexport function normalizeTableNumberFormat(format: unknown): TableNumberFormat {\n return format === \"text\" || format === \"number\" || format === \"currency\" || format === \"percent\" || format === \"date\"\n ? format\n : \"text\";\n}\n\nexport function formatTableFormulaDisplayValue(value: string | number, numberFormat: unknown) {\n const stringValue = String(value);\n if (stringValue.startsWith(\"#\")) {\n return stringValue;\n }\n\n const normalizedFormat = normalizeTableNumberFormat(numberFormat);\n if (normalizedFormat === \"text\") {\n return stringValue;\n }\n\n const numericValue = typeof value === \"number\" ? value : Number.parseFloat(stringValue.replace(/,/g, \"\"));\n if (!Number.isFinite(numericValue)) {\n return stringValue;\n }\n\n if (normalizedFormat === \"number\") {\n return new Intl.NumberFormat(\"en-US\", { maximumFractionDigits: 6 }).format(numericValue);\n }\n\n if (normalizedFormat === \"currency\") {\n return new Intl.NumberFormat(\"en-US\", {\n style: \"currency\",\n currency: \"USD\",\n maximumFractionDigits: 2,\n }).format(numericValue);\n }\n\n if (normalizedFormat === \"percent\") {\n return new Intl.NumberFormat(\"en-US\", {\n style: \"percent\",\n maximumFractionDigits: 2,\n }).format(numericValue);\n }\n\n const excelEpochMs = Date.UTC(1899, 11, 30);\n const date = new Date(excelEpochMs + numericValue * 24 * 60 * 60 * 1000);\n if (Number.isNaN(date.getTime())) {\n return stringValue;\n }\n\n return new Intl.DateTimeFormat(\"en-US\", {\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n timeZone: \"UTC\",\n }).format(date);\n}\n\nexport function getTableFormulaReferences(formula: string) {\n const normalized = normalizeTableFormula(formula);\n if (!normalized) return [];\n\n const tokens = tokenizeFormula(normalized);\n if (!tokens) return [];\n\n const references = new Set<string>();\n for (const token of tokens) {\n if (token.type === \"cell\") {\n const address = parseTableCellAddress(token.value);\n if (address) references.add(address.label);\n } else if (token.type === \"range\") {\n const range = parseTableCellRange(token.value);\n if (!range) continue;\n for (const label of getTableCellRangeLabels(range)) {\n references.add(label);\n }\n }\n }\n\n return Array.from(references);\n}\n\nexport function buildTableFormulaDependencyGraph(cells: TableFormulaCell[]): TableFormulaDependencyGraph {\n const dependencies = new Map<string, Set<string>>();\n const dependents = new Map<string, Set<string>>();\n const formulas = new Map<string, string>();\n\n for (const cell of cells) {\n const label = cell.label.toUpperCase();\n formulas.set(label, cell.formula);\n dependencies.set(label, new Set(getTableFormulaReferences(cell.formula)));\n if (!dependents.has(label)) {\n dependents.set(label, new Set());\n }\n }\n\n for (const [label, refs] of dependencies) {\n for (const ref of refs) {\n if (!dependents.has(ref)) {\n dependents.set(ref, new Set());\n }\n dependents.get(ref)?.add(label);\n }\n }\n\n return { dependencies, dependents, formulas };\n}\n\nexport function getTableFormulaCircularReferences(graph: TableFormulaDependencyGraph) {\n const circular = new Set<string>();\n const visited = new Set<string>();\n const finishOrder: string[] = [];\n\n for (const startLabel of graph.formulas.keys()) {\n if (visited.has(startLabel)) continue;\n\n visited.add(startLabel);\n const stack: Array<{ label: string; references: string[]; nextIndex: number }> = [\n {\n label: startLabel,\n references: Array.from(graph.dependencies.get(startLabel) ?? []).filter((ref) => graph.formulas.has(ref)),\n nextIndex: 0,\n },\n ];\n while (stack.length > 0) {\n const frame = stack[stack.length - 1];\n if (!frame) break;\n\n const reference = frame.references[frame.nextIndex];\n if (reference) {\n frame.nextIndex += 1;\n if (!visited.has(reference)) {\n visited.add(reference);\n stack.push({\n label: reference,\n references: Array.from(graph.dependencies.get(reference) ?? []).filter((ref) => graph.formulas.has(ref)),\n nextIndex: 0,\n });\n }\n continue;\n }\n\n stack.pop();\n finishOrder.push(frame.label);\n }\n }\n\n const assigned = new Set<string>();\n for (let index = finishOrder.length - 1; index >= 0; index -= 1) {\n const startLabel = finishOrder[index];\n if (!startLabel || assigned.has(startLabel)) continue;\n\n const component: string[] = [];\n const stack = [startLabel];\n assigned.add(startLabel);\n while (stack.length > 0) {\n const label = stack.pop();\n if (!label) continue;\n component.push(label);\n\n for (const dependent of graph.dependents.get(label) ?? []) {\n if (!graph.formulas.has(dependent) || assigned.has(dependent)) continue;\n assigned.add(dependent);\n stack.push(dependent);\n }\n }\n\n if (component.length > 1) {\n for (const label of component) circular.add(label);\n } else {\n const label = component[0];\n if (label && graph.dependencies.get(label)?.has(label)) circular.add(label);\n }\n }\n\n return circular;\n}\n\nexport function getTableFormulaRecalculationOrder(graph: TableFormulaDependencyGraph) {\n const circular = getTableFormulaCircularReferences(graph);\n const visiting = new Set<string>();\n const visited = new Set<string>();\n const order: string[] = [];\n\n for (const startLabel of graph.formulas.keys()) {\n if (visited.has(startLabel) || circular.has(startLabel)) continue;\n\n const stack: Array<{ label: string; references: string[]; nextIndex: number }> = [];\n const push = (label: string) => {\n visiting.add(label);\n stack.push({\n label,\n references: Array.from(graph.dependencies.get(label) ?? []).filter((ref) => graph.formulas.has(ref) && !circular.has(ref)),\n nextIndex: 0,\n });\n };\n\n push(startLabel);\n while (stack.length > 0) {\n const frame = stack[stack.length - 1];\n if (!frame) break;\n\n const reference = frame.references[frame.nextIndex];\n if (reference) {\n frame.nextIndex += 1;\n if (!visited.has(reference) && !visiting.has(reference)) {\n push(reference);\n }\n continue;\n }\n\n stack.pop();\n visiting.delete(frame.label);\n visited.add(frame.label);\n order.push(frame.label);\n }\n }\n\n return { order, circular };\n}\n\nexport function getAffectedTableFormulaLabels(graph: TableFormulaDependencyGraph, changedLabels: Iterable<string>) {\n const affected = new Set<string>();\n const queue = Array.from(changedLabels, (label) => label.toUpperCase());\n\n for (const label of queue) {\n if (graph.formulas.has(label)) {\n affected.add(label);\n }\n }\n\n for (let index = 0; index < queue.length; index += 1) {\n const label = queue[index];\n if (!label) continue;\n\n for (const dependent of graph.dependents.get(label) ?? []) {\n if (affected.has(dependent)) continue;\n affected.add(dependent);\n queue.push(dependent);\n }\n }\n\n return affected;\n}\n\nexport function evaluateBasicTableFormula(\n formula: string,\n getCellValue: (label: string) => string | number | null | undefined,\n): FormulaEvaluationResult {\n const normalized = normalizeTableFormula(formula);\n if (!normalized) {\n return { value: null, error: \"empty\" };\n }\n if (normalized.includes(\"#REF!\")) {\n return { value: null, error: \"invalid-reference\" };\n }\n\n const tokens = tokenizeFormula(normalized);\n if (!tokens) {\n return { value: null, error: \"invalid-formula\" };\n }\n\n const parser = new FormulaParser(tokens, getCellValue);\n const result = parser.parseExpression();\n if (result.error) {\n return result;\n }\n if (!parser.isComplete()) {\n return { value: null, error: \"invalid-formula\" };\n }\n return result;\n}\n\nfunction tokenizeFormula(formula: string): FormulaToken[] | null {\n const tokens: FormulaToken[] = [];\n let index = 0;\n\n while (index < formula.length) {\n const char = formula[index];\n if (!char) break;\n\n if (/\\s/.test(char)) {\n index += 1;\n continue;\n }\n\n if (char === \",\" || char === \"+\" || char === \"-\" || char === \"*\" || char === \"/\" || char === \"(\" || char === \")\") {\n if (char === \",\") tokens.push({ type: \"comma\", value: char });\n else if (char === \"(\" || char === \")\") tokens.push({ type: \"paren\", value: char });\n else tokens.push({ type: \"operator\", value: char });\n index += 1;\n continue;\n }\n\n const numberMatch = formula.slice(index).match(/^(?:\\d+(?:\\.\\d*)?|\\.\\d+)/);\n if (numberMatch?.[0]) {\n const value = Number.parseFloat(numberMatch[0]);\n if (!Number.isFinite(value)) return null;\n tokens.push({ type: \"number\", value });\n index += numberMatch[0].length;\n continue;\n }\n\n const identifierMatch = formula.slice(index).match(/^\\$?[A-Z]+\\$?[1-9]\\d*(?::\\$?[A-Z]+\\$?[1-9]\\d*)?|^[A-Z]+/i);\n if (identifierMatch?.[0]) {\n const value = identifierMatch[0].toUpperCase();\n if (CELL_RANGE_RE.test(value)) tokens.push({ type: \"range\", value });\n else if (parseTableCellAddress(value)) tokens.push({ type: \"cell\", value });\n else if (SUPPORTED_FUNCTIONS.has(value)) tokens.push({ type: \"function\", value });\n else return null;\n index += identifierMatch[0].length;\n continue;\n }\n\n return null;\n }\n\n return tokens;\n}\n\nfunction toFiniteFormulaResult(value: number): FormulaEvaluationResult {\n return Number.isFinite(value) ? { value, error: null } : { value: null, error: \"invalid-formula\" };\n}\n\nfunction parseTableCellNumericValue(value: string | number | null | undefined) {\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? value : null;\n }\n\n let normalized = String(value ?? \"\").trim();\n if (!normalized || normalized.startsWith(\"#\")) return null;\n\n const isPercent = normalized.endsWith(\"%\");\n if (isPercent) normalized = normalized.slice(0, -1).trim();\n\n const currencyMatch = normalized.match(/^([+-]?)\\$(.+)$/);\n if (currencyMatch) {\n normalized = `${currencyMatch[1] ?? \"\"}${currencyMatch[2] ?? \"\"}`.trim();\n }\n\n const groupedNumber = /^[+-]?\\d{1,3}(?:,\\d{3})+(?:\\.\\d*)?(?:[eE][+-]?\\d+)?$/;\n const plainNumber = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?$/;\n if (!groupedNumber.test(normalized) && !plainNumber.test(normalized)) return null;\n\n const parsed = Number(normalized.replace(/,/g, \"\"));\n if (!Number.isFinite(parsed)) return null;\n return isPercent ? parsed / 100 : parsed;\n}\n\nclass FormulaParser {\n private index = 0;\n\n constructor(\n private tokens: FormulaToken[],\n private getCellValue: (label: string) => string | number | null | undefined,\n ) {}\n\n isComplete() {\n return this.index >= this.tokens.length;\n }\n\n parseExpression(): FormulaEvaluationResult {\n let left = this.parseTerm();\n\n while (!left.error) {\n const operator = this.peekOperator([\"+\", \"-\"]);\n if (!operator) break;\n this.index += 1;\n\n const right = this.parseTerm();\n if (right.error) return right;\n left = toFiniteFormulaResult(operator.value === \"+\" ? left.value + right.value : left.value - right.value);\n }\n\n return left;\n }\n\n private parseTerm(): FormulaEvaluationResult {\n let left = this.parseFactor();\n\n while (!left.error) {\n const operator = this.peekOperator([\"*\", \"/\"]);\n if (!operator) break;\n this.index += 1;\n\n const right = this.parseFactor();\n if (right.error) return right;\n if (operator.value === \"/\" && right.value === 0) {\n return { value: null, error: \"division-by-zero\" };\n }\n left = toFiniteFormulaResult(operator.value === \"*\" ? left.value * right.value : left.value / right.value);\n }\n\n return left;\n }\n\n private parseFactor(): FormulaEvaluationResult {\n const token = this.tokens[this.index];\n if (!token) {\n return { value: null, error: \"invalid-formula\" };\n }\n\n if (token.type === \"operator\" && (token.value === \"-\" || token.value === \"+\")) {\n this.index += 1;\n const value = this.parseFactor();\n if (value.error) return value;\n return toFiniteFormulaResult(token.value === \"-\" ? -value.value : value.value);\n }\n\n if (token.type === \"number\") {\n this.index += 1;\n return { value: token.value, error: null };\n }\n\n if (token.type === \"cell\") {\n this.index += 1;\n return this.readCellNumber(token.value);\n }\n\n if (token.type === \"function\") {\n return this.parseFunction(token.value);\n }\n\n if (token.type === \"paren\" && token.value === \"(\") {\n this.index += 1;\n const value = this.parseExpression();\n if (value.error) return value;\n if (!this.consumeParen(\")\")) {\n return { value: null, error: \"invalid-formula\" };\n }\n return value;\n }\n\n return { value: null, error: \"invalid-formula\" };\n }\n\n private parseFunction(name: string): FormulaEvaluationResult {\n this.index += 1;\n if (!this.consumeParen(\"(\")) {\n return { value: null, error: \"invalid-formula\" };\n }\n\n const values: number[] = [];\n while (true) {\n const token = this.tokens[this.index];\n if (!token) {\n return { value: null, error: \"invalid-formula\" };\n }\n\n if (token.type === \"range\") {\n this.index += 1;\n const range = parseTableCellRange(token.value);\n if (!range) return { value: null, error: \"invalid-reference\" };\n for (const label of getTableCellRangeLabels(range)) {\n if (name === \"COUNT\") {\n const cellValue = this.readOptionalCellNumber(label);\n if (cellValue != null) values.push(cellValue);\n continue;\n }\n\n const cellValue = this.readOptionalCellNumber(label);\n if (cellValue != null) values.push(cellValue);\n }\n } else if (token.type === \"cell\") {\n this.index += 1;\n const cellValue = this.readOptionalCellNumber(token.value);\n if (cellValue != null) values.push(cellValue);\n } else {\n const value = this.parseExpression();\n if (value.error) return value;\n values.push(value.value);\n }\n\n if (this.consumeComma()) {\n continue;\n }\n if (this.consumeParen(\")\")) {\n break;\n }\n return { value: null, error: \"invalid-formula\" };\n }\n\n if (name === \"SUM\") return toFiniteFormulaResult(values.reduce((sum, value) => sum + value, 0));\n if (name === \"AVG\") {\n return values.length > 0\n ? toFiniteFormulaResult(values.reduce((sum, value) => sum + value, 0) / values.length)\n : { value: null, error: \"division-by-zero\" };\n }\n if (name === \"MIN\") return toFiniteFormulaResult(values.length > 0 ? Math.min(...values) : 0);\n if (name === \"MAX\") return toFiniteFormulaResult(values.length > 0 ? Math.max(...values) : 0);\n if (name === \"COUNT\") return { value: values.length, error: null };\n\n return { value: null, error: \"invalid-formula\" };\n }\n\n private readCellNumber(label: string): FormulaEvaluationResult {\n const address = parseTableCellAddress(label);\n const parsed = address ? parseTableCellNumericValue(this.getCellValue(address.label)) : null;\n if (parsed == null) {\n return { value: null, error: \"invalid-reference\" };\n }\n return { value: parsed, error: null };\n }\n\n private readOptionalCellNumber(label: string) {\n const address = parseTableCellAddress(label);\n return address ? parseTableCellNumericValue(this.getCellValue(address.label)) : null;\n }\n\n private peekOperator(operators: Array<\"+\" | \"-\" | \"*\" | \"/\">) {\n const token = this.tokens[this.index];\n return token?.type === \"operator\" && operators.includes(token.value) ? token : null;\n }\n\n private consumeComma() {\n if (this.tokens[this.index]?.type !== \"comma\") {\n return false;\n }\n this.index += 1;\n return true;\n }\n\n private consumeParen(value: \"(\" | \")\") {\n const token = this.tokens[this.index];\n if (token?.type !== \"paren\" || token.value !== value) {\n return false;\n }\n this.index += 1;\n return true;\n }\n}\n","import type { Node as ProseMirrorNode } from \"@tiptap/pm/model\";\nimport { columnNameToIndex, indexToColumnName } from \"./table-formula\";\n\nexport type TableFormulaAxis = \"row\" | \"column\";\n\ntype TableCellCoordinate = {\n column: number;\n row: number;\n columnAbsolute: boolean;\n rowAbsolute: boolean;\n};\n\ntype MappedTableCellCoordinate = Pick<TableCellCoordinate, \"column\" | \"row\">;\ntype CoordinateMapper = (coordinate: TableCellCoordinate) => MappedTableCellCoordinate | null;\n\nconst CELL_REFERENCE_RE = /(^|[^A-Z0-9_])(\\$?)([A-Z]+)(\\$?)([1-9]\\d*)\\b/gi;\n\nexport function rewriteTableFormulaReferences(formula: string, mapCoordinate: CoordinateMapper) {\n return formula.replace(CELL_REFERENCE_RE, (\n _match,\n prefix: string,\n columnMarker: string,\n columnName: string,\n rowMarker: string,\n rowNumber: string,\n ) => {\n const column = columnNameToIndex(columnName);\n const row = Number.parseInt(rowNumber, 10) - 1;\n if (column < 0 || row < 0) return _match;\n\n const mapped = mapCoordinate({\n column,\n row,\n columnAbsolute: columnMarker === \"$\",\n rowAbsolute: rowMarker === \"$\",\n });\n if (!mapped) return `${prefix}#REF!`;\n return `${prefix}${columnMarker}${indexToColumnName(mapped.column)}${rowMarker}${mapped.row + 1}`;\n });\n}\n\nfunction rewriteNodeFormulas(node: ProseMirrorNode, mapCoordinate: CoordinateMapper): ProseMirrorNode {\n if (node.type.name === \"tableCell\" || node.type.name === \"tableHeader\") {\n const formula = typeof node.attrs.formula === \"string\" ? node.attrs.formula : \"\";\n if (!formula) return node;\n const nextFormula = rewriteTableFormulaReferences(formula, mapCoordinate);\n if (nextFormula === formula) return node;\n return node.type.create({ ...node.attrs, formula: nextFormula, computedValue: null }, node.content, node.marks);\n }\n\n if (node.childCount === 0) return node;\n const children: ProseMirrorNode[] = [];\n let changed = false;\n node.forEach((child) => {\n const nextChild = rewriteNodeFormulas(child, mapCoordinate);\n children.push(nextChild);\n if (nextChild !== child) changed = true;\n });\n return changed ? node.type.create(node.attrs, children, node.marks) : node;\n}\n\nexport function rewriteTableNodeFormulaReferences(\n tableNode: ProseMirrorNode,\n mapCoordinate: CoordinateMapper,\n) {\n return rewriteNodeFormulas(tableNode, mapCoordinate);\n}\n\nexport function rewriteTableNodeFormulaReferencesForInsertion(\n tableNode: ProseMirrorNode,\n axis: TableFormulaAxis,\n index: number,\n count = 1,\n) {\n return rewriteTableNodeFormulaReferences(tableNode, (coordinate) => {\n const current = coordinate[axis];\n return current >= index ? { ...coordinate, [axis]: current + count } : coordinate;\n });\n}\n\nexport function rewriteTableNodeFormulaReferencesForDeletion(\n tableNode: ProseMirrorNode,\n axis: TableFormulaAxis,\n index: number,\n count = 1,\n) {\n const end = index + count;\n return rewriteTableNodeFormulaReferences(tableNode, (coordinate) => {\n const current = coordinate[axis];\n if (current >= index && current < end) return null;\n return current >= end ? { ...coordinate, [axis]: current - count } : coordinate;\n });\n}\n\nexport function rewriteTableNodeFormulaReferencesForMove(\n tableNode: ProseMirrorNode,\n axis: TableFormulaAxis,\n from: number,\n to: number,\n) {\n if (from === to) return tableNode;\n return rewriteTableNodeFormulaReferences(tableNode, (coordinate) => {\n const current = coordinate[axis];\n if (current === from) return { ...coordinate, [axis]: to };\n if (from < to && current > from && current <= to) {\n return { ...coordinate, [axis]: current - 1 };\n }\n if (from > to && current >= to && current < from) {\n return { ...coordinate, [axis]: current + 1 };\n }\n return coordinate;\n });\n}\n\nexport function shiftCopiedTableNodeFormulaReferences(\n node: ProseMirrorNode,\n axis: TableFormulaAxis,\n amount: number,\n) {\n return rewriteNodeFormulas(node, (coordinate) => {\n const isAbsolute = axis === \"column\" ? coordinate.columnAbsolute : coordinate.rowAbsolute;\n return {\n ...coordinate,\n [axis]: isAbsolute ? coordinate[axis] : Math.max(0, coordinate[axis] + amount),\n };\n });\n}\n","\"use client\";\n\nimport React, { useEffect, useId, useRef, useState } from \"react\";\nimport { useSmartTranslations } from \"../../hooks/useSmartTranslations\";\nimport { Check, X } from \"lucide-react\";\nimport { sanitizeUEditorUrl } from \"./url-safety\";\nimport { formControlOutlineClass } from \"../../constants/form-control-size\";\n\nfunction normalizeUrl(raw: string) {\n return sanitizeUEditorUrl(raw, \"link\");\n}\n\nexport const LinkInput = ({\n onSubmit,\n onCancel,\n initialUrl = \"\",\n}: {\n onSubmit: (url: string) => void;\n onCancel: () => void;\n initialUrl?: string;\n}) => {\n const t = useSmartTranslations(\"UEditor\");\n const [url, setUrl] = useState(initialUrl);\n const [error, setError] = useState(\"\");\n const inputRef = useRef<HTMLInputElement>(null);\n const inputId = useId();\n const errorId = useId();\n\n useEffect(() => {\n inputRef.current?.focus();\n inputRef.current?.select();\n }, []);\n\n const handleSubmit = (e: React.FormEvent) => {\n e.preventDefault();\n const normalized = normalizeUrl(url);\n if (!normalized) {\n setError(t(\"linkInput.invalid\"));\n return;\n }\n\n setError(\"\");\n onSubmit(normalized);\n };\n\n return (\n <form onSubmit={handleSubmit} className=\"p-2\">\n <label htmlFor={inputId} className=\"sr-only\">{t(\"toolbar.link\")}</label>\n <div className=\"flex items-center gap-2\">\n <input\n ref={inputRef}\n id={inputId}\n type=\"text\"\n inputMode=\"url\"\n name=\"link-url\"\n autoComplete=\"off\"\n value={url}\n onChange={(e) => {\n setUrl(e.target.value);\n if (error) setError(\"\");\n }}\n placeholder={t(\"linkInput.placeholder\")}\n aria-invalid={Boolean(error)}\n aria-describedby={error ? errorId : undefined}\n className={`flex-1 rounded-lg bg-muted/50 px-3 py-2 text-sm ${formControlOutlineClass} aria-invalid:border-destructive`}\n />\n <button type=\"submit\" aria-label={t(\"toolbar.link\")} className=\"p-2 rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 transition-colors\">\n <Check aria-hidden=\"true\" className=\"w-4 h-4\" />\n </button>\n <button type=\"button\" aria-label={t(\"imageInput.cancelBtn\")} onClick={onCancel} className=\"p-2 rounded-lg hover:bg-muted transition-colors text-muted-foreground\">\n <X aria-hidden=\"true\" className=\"w-4 h-4\" />\n </button>\n </div>\n {error ? <p id={errorId} role=\"alert\" className=\"mt-1.5 px-1 text-xs text-destructive\">{error}</p> : null}\n </form>\n );\n};\n\nexport const ImageInput = ({ onSubmit, onCancel }: { onSubmit: (url: string, alt?: string) => void; onCancel: () => void }) => {\n const t = useSmartTranslations(\"UEditor\");\n const [url, setUrl] = useState(\"\");\n const [alt, setAlt] = useState(\"\");\n const [error, setError] = useState(\"\");\n const inputRef = useRef<HTMLInputElement>(null);\n const urlId = useId();\n const altId = useId();\n const errorId = useId();\n\n useEffect(() => {\n inputRef.current?.focus();\n }, []);\n\n const handleSubmit = (e: React.FormEvent) => {\n e.preventDefault();\n const safeUrl = sanitizeUEditorUrl(url, \"image\");\n if (safeUrl) {\n setError(\"\");\n onSubmit(safeUrl, alt);\n } else {\n setError(t(\"imageInput.invalid\"));\n }\n };\n\n return (\n <form onSubmit={handleSubmit} className=\"p-3 space-y-3\">\n <div>\n <label htmlFor={urlId} className=\"text-xs font-medium text-muted-foreground\">{t(\"imageInput.urlLabel\")}</label>\n <input\n ref={inputRef}\n id={urlId}\n type=\"text\"\n inputMode=\"url\"\n name=\"image-url\"\n autoComplete=\"off\"\n value={url}\n onChange={(e) => {\n setUrl(e.target.value);\n if (error) setError(\"\");\n }}\n placeholder={t(\"imageInput.urlPlaceholder\")}\n aria-invalid={Boolean(error)}\n aria-describedby={error ? errorId : undefined}\n className={`mt-1 w-full rounded-lg bg-muted/50 px-3 py-2 text-sm ${formControlOutlineClass}`}\n />\n </div>\n <div>\n <label htmlFor={altId} className=\"text-xs font-medium text-muted-foreground\">{t(\"imageInput.altLabel\")}</label>\n <input\n id={altId}\n type=\"text\"\n name=\"image-alt\"\n autoComplete=\"off\"\n value={alt}\n onChange={(e) => setAlt(e.target.value)}\n placeholder={t(\"imageInput.altPlaceholder\")}\n className={`mt-1 w-full rounded-lg bg-muted/50 px-3 py-2 text-sm ${formControlOutlineClass}`}\n />\n </div>\n {error ? <p id={errorId} role=\"alert\" className=\"text-xs text-destructive\">{error}</p> : null}\n <div className=\"flex gap-2\">\n <button\n type=\"submit\"\n disabled={!url}\n className=\"flex-1 py-2 rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50\"\n >\n {t(\"imageInput.addBtn\")}\n </button>\n <button type=\"button\" onClick={onCancel} className=\"px-4 py-2 rounded-lg hover:bg-muted transition-colors text-muted-foreground\">\n {t(\"imageInput.cancelBtn\")}\n </button>\n </div>\n </form>\n );\n};\n","import type { Editor } from \"@tiptap/core\";\nimport { TextSelection } from \"@tiptap/pm/state\";\n\nexport function applyEditorLink(editor: Editor, href: string) {\n const isEditingLink = editor.isActive(\"link\");\n const hasSelectedText = !editor.state.selection.empty;\n const chain = editor.chain().focus();\n\n if (isEditingLink) {\n chain.extendMarkRange(\"link\");\n }\n\n chain.setLink({ href });\n\n if (!hasSelectedText && !isEditingLink) {\n chain.insertContent(href);\n }\n\n return chain\n .command(({ tr }) => {\n tr.setSelection(TextSelection.create(tr.doc, tr.selection.to));\n tr.removeStoredMark(editor.schema.marks.link);\n return true;\n })\n .run();\n}\n","\"use client\";\n\nimport React, { useRef, useState } from \"react\";\nimport type { Editor } from \"@tiptap/core\";\nimport { useEditorState } from \"@tiptap/react\";\nimport { useSmartTranslations } from \"../../hooks/useSmartTranslations\";\nimport {\n AlignCenter,\n AlignJustify,\n AlignLeft,\n AlignRight,\n ArrowDown,\n ArrowLeft,\n ArrowRight,\n ArrowUp,\n Circle,\n CircleCheckBig,\n CircleDot,\n FileCode,\n Heading1 as Heading1Icon,\n Heading2 as Heading2Icon,\n Heading3 as Heading3Icon,\n IndentDecrease,\n IndentIncrease,\n Link as LinkIcon,\n List as ListIcon,\n ListOrdered as ListOrderedIcon,\n ListTodo,\n Minus,\n PanelTopClose,\n PanelTopOpen,\n Quote as QuoteIcon,\n RotateCcw,\n Square,\n SquareCheckBig,\n TableCellsMerge,\n Trash2,\n Type,\n Upload,\n WrapText,\n} from \"lucide-react\";\nimport { setCellAttr } from \"@tiptap/pm/tables\";\nimport { cn } from \"../../utils/cn\";\nimport { DropdownMenu, DropdownMenuItem } from \"../DropdownMenu\";\nimport { Tooltip } from \"../Tooltip\";\nimport { EditorColorPalette, HighlightColorIcon, TextColorIcon, useEditorColors } from \"./colors\";\nimport { DEFAULT_UEDITOR_IMAGE_MAX_FILE_SIZE, DEFAULT_UEDITOR_IMAGE_MIME_TYPES } from \"./clipboard-images\";\nimport { applyImageLayout, applyImageWidthPreset, deleteSelectedImage, resetImageSize, type UEditorImageWidthPreset } from \"./image-commands\";\nimport { ImageInput, LinkInput } from \"./inputs\";\nimport { applyEditorLink } from \"./link-commands\";\nimport { trackEditorInsertionPosition } from \"./async-insertion-position\";\nimport { resolveUEditorImageFiles } from \"./image-file-upload\";\nimport { findTableNodeInfoFromState } from \"./table-align-utils\";\nimport { isCrossRealmTableCell, isValidProseMirrorPosition, resolveEventElement } from \"./table-dom-utils\";\nimport { mergeTableCellsPreservingColumnWidths } from \"./table-cell-commands\";\nimport { TableVerticalAlignBottomIcon, TableVerticalAlignMiddleIcon, TableVerticalAlignTopIcon } from \"./table-vertical-align-icons\";\nimport {\n FigmaAlignLeftIcon,\n FigmaBoldIcon,\n FigmaChevronDownIcon,\n FigmaCodeIcon,\n FigmaImageIcon,\n FigmaItalicIcon,\n FigmaLetterSpacingIcon,\n FigmaLineHeightIcon,\n FigmaLinkIcon,\n FigmaListIcon,\n FigmaQuoteIcon,\n FigmaRedoIcon,\n FigmaStrikeIcon,\n FigmaSubscriptIcon,\n FigmaSuperscriptIcon,\n FigmaTableIcon,\n FigmaTextStyleIcon,\n FigmaUnderlineIcon,\n FigmaUndoIcon,\n} from \"./figma-toolbar-icons\";\nimport type { UEditorFontFamilyOption, UEditorFontSizeOption, UEditorLetterSpacingOption, UEditorLineHeightOption, UEditorVariant } from \"./types\";\nimport {\n getDefaultFontFamilies,\n getDefaultFontSizes,\n getDefaultLetterSpacings,\n getDefaultLineHeights,\n normalizeStyleValue,\n} from \"./typography-options\";\n\ntype UploadImageFn = (file: File) => Promise<string> | string;\n\nexport function getTableAnchorPos(editor: Editor) {\n const tableInfo = findTableNodeInfoFromState(editor.state);\n if (tableInfo) return editor.state.selection.from;\n\n const editorDocument = editor.view.dom.ownerDocument;\n const editorWindow = editorDocument.defaultView;\n const selectionAnchor = resolveEventElement(editorWindow?.getSelection()?.anchorNode ?? null);\n const selectionCell = selectionAnchor?.closest?.(\"th,td\");\n if (isCrossRealmTableCell(selectionCell) && editor.view.dom.contains(selectionCell)) {\n const cellPos = editor.view.posAtDOM(selectionCell, 0);\n return isValidProseMirrorPosition(editor.state.doc, cellPos)\n && isValidProseMirrorPosition(editor.state.doc, cellPos + 1)\n ? cellPos + 1\n : null;\n }\n\n const activeElement = editorWindow && editorDocument.activeElement instanceof editorWindow.Element ? editorDocument.activeElement : null;\n const activeCell = activeElement?.closest?.(\"th,td\");\n if (isCrossRealmTableCell(activeCell) && editor.view.dom.contains(activeCell)) {\n const cellPos = editor.view.posAtDOM(activeCell, 0);\n return isValidProseMirrorPosition(editor.state.doc, cellPos)\n && isValidProseMirrorPosition(editor.state.doc, cellPos + 1)\n ? cellPos + 1\n : null;\n }\n\n const tables = editor.view.dom.querySelectorAll(\"table\");\n if (tables.length !== 1) return null;\n\n const firstCell = tables[0]?.querySelector(\"th,td\");\n if (!isCrossRealmTableCell(firstCell) || !editor.view.dom.contains(firstCell)) return null;\n const cellPos = editor.view.posAtDOM(firstCell, 0);\n return isValidProseMirrorPosition(editor.state.doc, cellPos)\n && isValidProseMirrorPosition(editor.state.doc, cellPos + 1)\n ? cellPos + 1\n : null;\n}\n\nconst EDITOR_UI_ACTIVE_MARKS = [\n \"blockquote\",\n \"bold\",\n \"bulletList\",\n \"code\",\n \"codeBlock\",\n \"formCheckbox\",\n \"highlight\",\n \"image\",\n \"italic\",\n \"link\",\n \"orderedList\",\n \"paragraph\",\n \"strike\",\n \"subscript\",\n \"superscript\",\n \"taskList\",\n \"underline\",\n] as const;\n\nfunction computeEditorUiRenderState(editor: Editor) {\n const textStyle = editor.getAttributes(\"textStyle\");\n const highlight = editor.getAttributes(\"highlight\");\n const image = editor.getAttributes(\"image\");\n const link = editor.getAttributes(\"link\");\n const tableCell = editor.getAttributes(\"tableCell\");\n const tableHeader = editor.getAttributes(\"tableHeader\");\n const hasTableContext = findTableNodeInfoFromState(editor.state) !== null;\n const can = editor.can();\n\n return {\n active: EDITOR_UI_ACTIVE_MARKS.map((name) => editor.isActive(name)),\n alignment: [\"left\", \"center\", \"right\", \"justify\"].map((textAlign) => editor.isActive({ textAlign })),\n heading: [1, 2, 3].map((level) => editor.isActive(\"heading\", { level })),\n textStyle: {\n color: textStyle.color ?? null,\n fontFamily: textStyle.fontFamily ?? null,\n fontSize: textStyle.fontSize ?? null,\n letterSpacing: textStyle.letterSpacing ?? null,\n lineHeight: textStyle.lineHeight ?? null,\n },\n highlightColor: highlight.color ?? null,\n image: {\n imageLayout: image.imageLayout ?? null,\n imageWidthPreset: image.imageWidthPreset ?? null,\n },\n linkHref: link.href ?? null,\n tableCell: {\n backgroundColor: tableCell.backgroundColor ?? tableHeader.backgroundColor ?? null,\n borderColor: tableCell.borderColor ?? tableHeader.borderColor ?? null,\n borderStyle: tableCell.borderStyle ?? tableHeader.borderStyle ?? null,\n borderWidth: tableCell.borderWidth ?? tableHeader.borderWidth ?? null,\n formula: tableCell.formula ?? tableHeader.formula ?? null,\n numberFormat: tableCell.numberFormat ?? tableHeader.numberFormat ?? null,\n textDirection: tableCell.textDirection ?? tableHeader.textDirection ?? null,\n textWrap: tableCell.textWrap ?? tableHeader.textWrap ?? \"wrap\",\n verticalAlign: tableCell.verticalAlign ?? tableHeader.verticalAlign ?? null,\n },\n can: {\n addColumnAfter: hasTableContext && can.addColumnAfter(),\n addColumnBefore: hasTableContext && can.addColumnBefore(),\n addRowAfter: hasTableContext && can.addRowAfter(),\n addRowBefore: hasTableContext && can.addRowBefore(),\n decreaseIndent: can.decreaseIndent(),\n increaseIndent: can.increaseIndent(),\n mergeCells: hasTableContext && can.mergeCells(),\n redo: can.redo(),\n splitCell: hasTableContext && can.splitCell(),\n undo: can.undo(),\n },\n hasTableContext,\n isEmpty: editor.isEmpty,\n };\n}\n\ntype EditorUiRenderState = ReturnType<typeof computeEditorUiRenderState>;\nconst editorUiRenderStateCache = new WeakMap<Editor, {\n state: Editor[\"state\"];\n value: EditorUiRenderState;\n}>();\n\n/**\n * Returns only the editor state that can change toolbar, menu bar or bubble-menu UI.\n * TipTap compares this snapshot deeply, so plain typing no longer forces those large\n * React trees to render when their visible state did not change. Multiple editor chrome\n * components share the same snapshot for a transaction to avoid repeating command probes.\n */\nexport function getEditorUiRenderState(editor: Editor) {\n const state = editor.state;\n const cached = editorUiRenderStateCache.get(editor);\n if (cached?.state === state) return cached.value;\n\n const value = computeEditorUiRenderState(editor);\n editorUiRenderStateCache.set(editor, { state, value });\n return value;\n}\n\nconst EditorUiRenderStateContext = React.createContext<{\n editor: Editor;\n value: EditorUiRenderState;\n} | null>(null);\n\nexport function EditorUiRenderStateProvider({\n children,\n editor,\n}: {\n children: React.ReactNode;\n editor: Editor;\n}) {\n const value = useEditorState({\n editor,\n selector: ({ editor: currentEditor }) => getEditorUiRenderState(currentEditor),\n });\n\n return (\n <EditorUiRenderStateContext.Provider value={{ editor, value }}>\n {children}\n </EditorUiRenderStateContext.Provider>\n );\n}\n\nexport function useSharedEditorUiRenderState(editor: Editor) {\n const context = React.useContext(EditorUiRenderStateContext);\n if (!context || context.editor !== editor) {\n throw new Error(\"UEditor chrome must be rendered inside EditorUiRenderStateProvider\");\n }\n\n return context.value;\n}\n\nfunction formatTableInsertLabel(template: string, rows: number, cols: number) {\n return template.replace(\"{rows}\", String(rows)).replace(\"{cols}\", String(cols));\n}\n\nexport const ToolbarButton = React.forwardRef<\n HTMLButtonElement,\n {\n onClick: (e: React.MouseEvent) => void;\n onMouseDown?: (e: React.MouseEvent) => void;\n active?: boolean;\n disabled?: boolean;\n children: React.ReactNode;\n title?: string;\n className?: string;\n }\n>(({ onClick, onMouseDown, active, disabled, children, title, className }, ref) => {\n const button = (\n <button\n ref={ref}\n type=\"button\"\n aria-label={title}\n onMouseDown={(e) => {\n onMouseDown?.(e);\n e.preventDefault();\n }}\n onClick={onClick}\n disabled={disabled}\n className={cn(\n \"flex h-7 w-7 shrink-0 cursor-pointer items-center justify-center rounded-md transition-colors duration-150\",\n \"gap-0.5 [&>svg]:h-3.5 [&>svg]:w-3.5 [&>svg]:shrink-0\",\n \"hover:bg-accent\",\n \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/20\",\n \"disabled:opacity-40 disabled:cursor-not-allowed\",\n active ? \"bg-primary/10 text-primary shadow-sm\" : \"text-[#7B8184] hover:text-foreground dark:text-muted-foreground\",\n className,\n )}\n >\n {children}\n </button>\n );\n\n if (title) {\n return (\n <Tooltip content={title} placement=\"top\" delay={{ open: 200, close: 0 }}>\n {button}\n </Tooltip>\n );\n }\n\n return button;\n});\nToolbarButton.displayName = \"ToolbarButton\";\n\nconst ToolbarDivider = () => <div aria-hidden=\"true\" className=\"mx-1 h-5 w-px shrink-0 bg-[rgba(123,129,132,0.24)]\" />;\n\nexport const TableInsertGrid = ({\n insertLabel,\n previewTemplate,\n onInsert,\n}: {\n insertLabel: string;\n previewTemplate: string;\n onInsert: (rows: number, cols: number) => void;\n}) => {\n const [selection, setSelection] = React.useState({ rows: 3, cols: 3 });\n const maxRows = 8;\n const maxCols = 8;\n\n return (\n <div className=\"mb-2 rounded-xl border border-border/60 bg-muted/20 p-2\">\n <div className=\"mb-2 text-sm font-medium text-foreground\">{formatTableInsertLabel(previewTemplate, selection.rows, selection.cols)}</div>\n <div className=\"grid grid-cols-8 gap-1\" role=\"grid\" aria-label={insertLabel}>\n {Array.from({ length: maxRows }).map((_, rowIndex) =>\n Array.from({ length: maxCols }).map((__, colIndex) => {\n const rows = rowIndex + 1;\n const cols = colIndex + 1;\n const active = rows <= selection.rows && cols <= selection.cols;\n\n return (\n <button\n key={`${rows}-${cols}`}\n type=\"button\"\n role=\"gridcell\"\n tabIndex={rows === selection.rows && cols === selection.cols ? 0 : -1}\n aria-selected={rows === selection.rows && cols === selection.cols}\n data-table-grid-cell={`${rows}-${cols}`}\n aria-label={formatTableInsertLabel(previewTemplate, rows, cols)}\n onMouseDown={(e) => e.preventDefault()}\n onMouseEnter={() => setSelection({ rows, cols })}\n onFocus={() => setSelection({ rows, cols })}\n onKeyDown={(event) => {\n const nextRows = event.key === \"ArrowUp\"\n ? Math.max(1, rows - 1)\n : event.key === \"ArrowDown\"\n ? Math.min(maxRows, rows + 1)\n : rows;\n const nextCols = event.key === \"ArrowLeft\"\n ? Math.max(1, cols - 1)\n : event.key === \"ArrowRight\"\n ? Math.min(maxCols, cols + 1)\n : cols;\n if (nextRows === rows && nextCols === cols) return;\n event.preventDefault();\n setSelection({ rows: nextRows, cols: nextCols });\n event.currentTarget.parentElement\n ?.querySelector<HTMLButtonElement>(`[data-table-grid-cell=\"${nextRows}-${nextCols}\"]`)\n ?.focus();\n }}\n onClick={() => onInsert(rows, cols)}\n className={cn(\n \"h-5 w-5 rounded-sm border transition-colors\",\n active ? \"border-primary bg-primary/20\" : \"border-border/70 bg-background hover:border-primary/60 hover:bg-primary/10\",\n )}\n />\n );\n }),\n )}\n </div>\n <div className=\"mt-2 text-xs text-muted-foreground\">{insertLabel}</div>\n </div>\n );\n};\n\nfunction applyTableCellAttribute(editor: Editor, name: string, value: string | null) {\n const { state, view } = editor;\n const applied = setCellAttr(name, value)(state, view.dispatch.bind(view));\n\n if (applied) {\n view.focus();\n return;\n }\n\n editor.chain().focus().setCellAttribute(name, value).run();\n}\n\nexport const EditorToolbar = ({\n editor,\n variant,\n isMenuBarVisible,\n onToggleMenuBar,\n uploadImage,\n imageInsertMode = \"base64\",\n maxImageFileSize = DEFAULT_UEDITOR_IMAGE_MAX_FILE_SIZE,\n allowedImageMimeTypes = DEFAULT_UEDITOR_IMAGE_MIME_TYPES,\n onImageUploadError,\n fallbackToDataUrl = true,\n fontFamilies,\n defaultFontFamily = \"Inter\",\n fontSizes,\n lineHeights,\n letterSpacings,\n}: {\n editor: Editor;\n variant: UEditorVariant;\n isMenuBarVisible?: boolean;\n onToggleMenuBar?: () => void;\n uploadImage?: UploadImageFn;\n imageInsertMode?: \"base64\" | \"upload\";\n maxImageFileSize?: number;\n allowedImageMimeTypes?: string[];\n onImageUploadError?: (error: Error, file: File) => void;\n fallbackToDataUrl?: boolean;\n fontFamilies?: UEditorFontFamilyOption[];\n defaultFontFamily?: string;\n fontSizes?: UEditorFontSizeOption[];\n lineHeights?: UEditorLineHeightOption[];\n letterSpacings?: UEditorLetterSpacingOption[];\n}) => {\n const t = useSmartTranslations(\"UEditor\");\n const editorUiState = useSharedEditorUiRenderState(editor);\n const { textColors, highlightColors } = useEditorColors();\n const [showImageInput, setShowImageInput] = useState(false);\n const [showLinkInput, setShowLinkInput] = useState(false);\n const [isTableMenuOpen, setIsTableMenuOpen] = useState(false);\n const [fontSizeDraft, setFontSizeDraft] = useState(\"\");\n const [isEditingFontSize, setIsEditingFontSize] = useState(false);\n const fileInputRef = useRef<HTMLInputElement>(null);\n const [isUploadingImage, setIsUploadingImage] = useState(false);\n const [imageUploadError, setImageUploadError] = useState<string | null>(null);\n\n const isImageSelected = editor.isActive(\"image\");\n const imageAttrs = editor.getAttributes(\"image\") as { imageLayout?: string; imageWidthPreset?: UEditorImageWidthPreset | null };\n const tableAnchorPos = getTableAnchorPos(editor);\n const tableInfo = tableAnchorPos == null ? null : findTableNodeInfoFromState(editor.state, tableAnchorPos);\n const textStyleAttrs = editor.getAttributes(\"textStyle\") as {\n fontFamily?: string;\n fontSize?: string;\n color?: string;\n lineHeight?: string;\n letterSpacing?: string;\n };\n const imageLayout = imageAttrs.imageLayout === \"left\" || imageAttrs.imageLayout === \"right\" ? imageAttrs.imageLayout : \"block\";\n const imageWidthPreset =\n imageAttrs.imageWidthPreset === \"sm\" || imageAttrs.imageWidthPreset === \"md\" || imageAttrs.imageWidthPreset === \"lg\"\n ? imageAttrs.imageWidthPreset\n : null;\n const isTableSelected = tableInfo !== null;\n const hasTableContext = isTableSelected;\n const canMergeCells = hasTableContext && editor.can().mergeCells();\n const canSplitCell = hasTableContext && editor.can().splitCell();\n const currentCellVerticalAlign =\n normalizeStyleValue(editor.getAttributes(\"tableCell\").verticalAlign || editor.getAttributes(\"tableHeader\").verticalAlign) || \"\";\n const currentCellTextDirection =\n normalizeStyleValue(editor.getAttributes(\"tableCell\").textDirection || editor.getAttributes(\"tableHeader\").textDirection) || \"horizontal\";\n const currentCellTextWrap =\n normalizeStyleValue(editor.getAttributes(\"tableCell\").textWrap || editor.getAttributes(\"tableHeader\").textWrap) || \"wrap\";\n const currentFontFamily = normalizeStyleValue(textStyleAttrs.fontFamily);\n const currentFontSize = normalizeStyleValue(textStyleAttrs.fontSize);\n const currentTextColor = normalizeStyleValue(textStyleAttrs.color) || \"inherit\";\n const currentHighlightColor = normalizeStyleValue(editor.getAttributes(\"highlight\").color) || \"\";\n const currentLineHeight = normalizeStyleValue(textStyleAttrs.lineHeight);\n const currentLetterSpacing = normalizeStyleValue(textStyleAttrs.letterSpacing);\n const availableFontFamilies = React.useMemo<UEditorFontFamilyOption[]>(() => fontFamilies ?? getDefaultFontFamilies(t), [fontFamilies, t]);\n const availableFontSizes = React.useMemo<UEditorFontSizeOption[]>(() => fontSizes ?? getDefaultFontSizes(), [fontSizes]);\n const availableLineHeights = React.useMemo<UEditorLineHeightOption[]>(() => lineHeights ?? getDefaultLineHeights(), [lineHeights]);\n const availableLetterSpacings = React.useMemo<UEditorLetterSpacingOption[]>(() => letterSpacings ?? getDefaultLetterSpacings(), [letterSpacings]);\n const currentFontFamilyDisplayValue = currentFontFamily.split(\",\")[0]?.trim() ?? currentFontFamily;\n const currentFontFamilyLabel =\n availableFontFamilies.find((option) => normalizeStyleValue(option.value) === currentFontFamily)?.label ??\n (currentFontFamilyDisplayValue || t(\"toolbar.fontDefault\"));\n const currentFontSizeLabel =\n availableFontSizes.find((option) => normalizeStyleValue(option.value) === currentFontSize)?.label ?? (currentFontSize.replace(/px$/i, \"\") || \"13\");\n const currentLineHeightLabel =\n availableLineHeights.find((option) => normalizeStyleValue(option.value) === currentLineHeight)?.label ?? t(\"toolbar.lineHeightDefault\");\n const currentLetterSpacingLabel =\n availableLetterSpacings.find((option) => normalizeStyleValue(option.value) === currentLetterSpacing)?.label ?? t(\"toolbar.letterSpacingDefault\");\n const defaultFontFamilyOption = availableFontFamilies.find((opt) => normalizeStyleValue(opt.value) === normalizeStyleValue(defaultFontFamily)) ?? availableFontFamilies[0];\n const defaultFontFamilyValue = defaultFontFamilyOption?.value ?? defaultFontFamily ?? \"Inter\";\n const displayedFontFamilyLabel = currentFontFamily ? currentFontFamilyLabel : (defaultFontFamilyOption?.label ?? defaultFontFamily ?? t(\"toolbar.fontDefault\"));\n const displayedFontFamilyValue = currentFontFamily || defaultFontFamilyValue;\n const displayedFontSizeLabel = currentFontSize ? currentFontSizeLabel : \"13\";\n const activeFontSize = currentFontSize || \"13px\";\n const isMedium = variant === \"medium\";\n const isMediumFull = variant === \"medium-full\";\n const isFull = variant === \"default\" || variant === \"full\" || variant === \"notion\" || !variant;\n\n const applyFontSizeDraft = () => {\n const parsed = Number.parseFloat(fontSizeDraft);\n if (!Number.isFinite(parsed)) return;\n\n const clamped = Math.min(512, Math.max(8, parsed));\n editor.chain().focus().setFontSize(`${clamped}px`).run();\n setFontSizeDraft(String(clamped));\n };\n\n const insertImageFiles = async (files: File[]) => {\n if (files.length === 0) return;\n\n setIsUploadingImage(true);\n setImageUploadError(null);\n\n const trackedPosition = trackEditorInsertionPosition(editor);\n try {\n const { images, hadError } = await resolveUEditorImageFiles(files, {\n maxFileSize: maxImageFileSize,\n allowedMimeTypes: allowedImageMimeTypes,\n upload: uploadImage,\n fallbackToDataUrl,\n insertMode: imageInsertMode,\n onError: onImageUploadError,\n });\n if (hadError) setImageUploadError(t(\"imageInput.uploadError\"));\n\n if (!editor.isDestroyed && images.length > 0) {\n const content = images.map((image) => ({\n type: \"image\",\n attrs: { src: image.src, alt: image.file.name },\n }));\n editor.commands.insertContentAt(trackedPosition.current, content, { updateSelection: false });\n }\n } finally {\n trackedPosition.stop();\n setIsUploadingImage(false);\n }\n };\n\n if (variant === \"minimal\") {\n return (\n <div className=\"flex flex-wrap items-center gap-0.5 border-b border-border/35 bg-muted/30 p-1.5\">\n <ToolbarButton onClick={() => editor.chain().focus().undo().run()} disabled={!editor.can().undo()} title={t(\"toolbar.undo\")}>\n <FigmaUndoIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n <ToolbarButton onClick={() => editor.chain().focus().redo().run()} disabled={!editor.can().redo()} title={t(\"toolbar.redo\")}>\n <FigmaRedoIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n <ToolbarDivider />\n <ToolbarButton onClick={() => editor.chain().focus().toggleBold().run()} active={editor.isActive(\"bold\")} title={t(\"toolbar.bold\")}>\n <FigmaBoldIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n <ToolbarButton onClick={() => editor.chain().focus().toggleItalic().run()} active={editor.isActive(\"italic\")} title={t(\"toolbar.italic\")}>\n <FigmaItalicIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n <DropdownMenu\n trigger={\n <ToolbarButton\n onClick={() => editor.chain().focus().toggleBulletList().run()}\n active={editor.isActive(\"bulletList\")}\n title={t(\"toolbar.bulletList\")}\n >\n <FigmaListIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n }\n >\n <DropdownMenuItem\n icon={CircleDot}\n label={t(\"toolbar.bulletStyleDisc\")}\n onClick={() => editor.chain().focus().toggleBulletListStyle(\"disc\").run()}\n active={editor.isActive(\"bulletList\", { bulletStyle: \"disc\" })}\n />\n <DropdownMenuItem\n icon={Minus}\n label={t(\"toolbar.bulletStyleDash\")}\n onClick={() => editor.chain().focus().toggleBulletListStyle(\"dash\").run()}\n active={editor.isActive(\"bulletList\", { bulletStyle: \"dash\" })}\n />\n <DropdownMenuItem\n icon={Circle}\n label={t(\"toolbar.bulletStyleCircle\")}\n onClick={() => editor.chain().focus().toggleBulletListStyle(\"circle\").run()}\n active={editor.isActive(\"bulletList\", { bulletStyle: \"circle\" })}\n />\n <DropdownMenuItem\n icon={Square}\n label={t(\"toolbar.bulletStyleSquare\")}\n onClick={() => editor.chain().focus().toggleBulletListStyle(\"square\").run()}\n active={editor.isActive(\"bulletList\", { bulletStyle: \"square\" })}\n />\n </DropdownMenu>\n <ToolbarButton\n onClick={() => editor.chain().focus().decreaseIndent().run()}\n disabled={!editorUiState.can.decreaseIndent}\n title={t(\"toolbar.decreaseIndent\")}\n >\n <IndentDecrease className=\"h-4 w-4\" />\n </ToolbarButton>\n <ToolbarButton\n onClick={() => editor.chain().focus().increaseIndent().run()}\n disabled={!editorUiState.can.increaseIndent}\n title={t(\"toolbar.increaseIndent\")}\n >\n <IndentIncrease className=\"h-4 w-4\" />\n </ToolbarButton>\n <DropdownMenu\n trigger={\n <ToolbarButton onClick={() => {}} active={editor.isActive(\"formCheckbox\")} title={t(\"slashCommand.formCheckbox\")}>\n <SquareCheckBig className=\"w-4 h-4\" />\n </ToolbarButton>\n }\n >\n <DropdownMenuItem\n icon={SquareCheckBig}\n label={t(\"slashCommand.formCheckbox\")}\n onClick={() => editor.chain().focus().setFormCheckbox().run()}\n />\n <DropdownMenuItem\n icon={CircleCheckBig}\n label={t(\"slashCommand.roundCheckbox\")}\n onClick={() => editor.chain().focus().setFormCheckbox({ variant: \"circle\" }).run()}\n />\n </DropdownMenu>\n <DropdownMenu\n contentClassName=\"min-w-72\"\n trigger={\n <ToolbarButton onClick={() => setShowLinkInput(!editor.isActive(\"link\"))} active={editor.isActive(\"link\")} title={t(\"toolbar.link\")}>\n <FigmaLinkIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n }\n >\n {showLinkInput ? (\n <LinkInput\n initialUrl={String(editor.getAttributes(\"link\").href ?? \"\")}\n onSubmit={(url) => {\n applyEditorLink(editor, url);\n setShowLinkInput(false);\n }}\n onCancel={() => setShowLinkInput(false)}\n />\n ) : (\n <>\n <DropdownMenuItem\n icon={LinkIcon}\n label={t(\"toolbar.link\")}\n onClick={() => setShowLinkInput(true)}\n active={editor.isActive(\"link\")}\n closeOnSelect={false}\n />\n <DropdownMenuItem\n icon={Trash2}\n label={t(\"toolbar.removeLink\")}\n onClick={() => editor.chain().focus().extendMarkRange(\"link\").unsetLink().run()}\n disabled={!editor.isActive(\"link\")}\n destructive\n />\n </>\n )}\n </DropdownMenu>\n {onToggleMenuBar && (\n <ToolbarButton\n onClick={onToggleMenuBar}\n active={isMenuBarVisible}\n title={t(isMenuBarVisible ? \"toolbar.hideMenuBar\" : \"toolbar.showMenuBar\")}\n >\n {isMenuBarVisible ? <PanelTopClose className=\"h-4 w-4\" /> : <PanelTopOpen className=\"h-4 w-4\" />}\n </ToolbarButton>\n )}\n </div>\n );\n }\n\n const VerticalAlignActiveIcon =\n currentCellVerticalAlign === \"middle\"\n ? TableVerticalAlignMiddleIcon\n : currentCellVerticalAlign === \"bottom\"\n ? TableVerticalAlignBottomIcon\n : TableVerticalAlignTopIcon;\n\n return (\n <div\n role=\"toolbar\"\n className=\"flex min-h-9 flex-wrap items-center gap-0.5 border-b border-[rgba(196,197,213,0.6)] bg-[#F4F4F4] px-1.5 py-1 dark:bg-muted/60\"\n >\n {isFull && (\n <DropdownMenu\n trigger={\n <ToolbarButton\n onClick={() => {}}\n title={t(\"toolbar.fontFamily\")}\n className=\"h-7 w-40 max-w-40 justify-between gap-1.5 border border-[rgba(196,197,213,0.6)] bg-white px-2 text-[#404040] shadow-[0_1px_2px_rgba(0,0,0,0.07)] hover:bg-white hover:text-[#404040] dark:bg-background dark:text-foreground\"\n >\n <span className=\"min-w-0 flex-1 truncate text-left text-xs font-normal\" style={{ fontFamily: displayedFontFamilyValue || undefined }}>\n {displayedFontFamilyLabel}\n </span>\n <FigmaChevronDownIcon className=\"h-3 w-3 shrink-0 text-[#7B8184]\" />\n </ToolbarButton>\n }\n contentClassName=\"max-h-80 overflow-y-auto min-w-56 p-2\"\n >\n {availableFontFamilies.map((option) => (\n <DropdownMenuItem\n key={option.value}\n label={option.label}\n onClick={() => editor.chain().focus().setFontFamily(option.value).run()}\n active={normalizeStyleValue(option.value) === (currentFontFamily || normalizeStyleValue(defaultFontFamilyValue))}\n className=\"font-medium\"\n />\n ))}\n </DropdownMenu>\n )}\n\n {(isMediumFull || isFull) && (\n <DropdownMenu\n trigger={\n <div className=\"flex h-7 w-14 items-center rounded-md border border-[rgba(196,197,213,0.6)] bg-white text-[#404040] shadow-[0_1px_2px_rgba(0,0,0,0.07)] dark:bg-background dark:text-foreground\">\n <input\n type=\"number\"\n min={8}\n max={512}\n step={1}\n value={isEditingFontSize ? fontSizeDraft : displayedFontSizeLabel}\n onFocus={() => {\n setFontSizeDraft(displayedFontSizeLabel);\n setIsEditingFontSize(true);\n }}\n onChange={(event) => setFontSizeDraft(event.target.value)}\n onBlur={() => {\n applyFontSizeDraft();\n setIsEditingFontSize(false);\n }}\n onMouseDown={(event) => event.stopPropagation()}\n onClick={(event) => event.stopPropagation()}\n onKeyDown={(event) => {\n event.stopPropagation();\n if (event.key === \"Enter\") {\n event.preventDefault();\n applyFontSizeDraft();\n setIsEditingFontSize(false);\n }\n }}\n aria-label={t(\"toolbar.fontSize\")}\n className=\"min-w-0 flex-1 bg-transparent px-2 text-xs font-normal leading-none outline-none [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none\"\n />\n <button type=\"button\" aria-label={t(\"toolbar.fontSize\")} title={t(\"toolbar.fontSize\")} className=\"px-1 text-[#7B8184]\">\n <FigmaChevronDownIcon className=\"h-3 w-3\" />\n </button>\n </div>\n }\n contentClassName=\"max-h-80 overflow-y-auto min-w-32 p-2\"\n >\n {availableFontSizes.map((option) => (\n <DropdownMenuItem\n key={option.value}\n label={option.label}\n onClick={() => {\n editor.chain().focus().setFontSize(option.value).run();\n setFontSizeDraft(option.label);\n }}\n active={normalizeStyleValue(option.value) === activeFontSize}\n />\n ))}\n </DropdownMenu>\n )}\n\n <DropdownMenu\n contentClassName=\"p-1\"\n trigger={\n <ToolbarButton onClick={() => {}} title={t(\"toolbar.textStyle\")} className=\"px-1.5 w-auto gap-0.5\">\n <FigmaTextStyleIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n }\n >\n <DropdownMenuItem\n icon={Type}\n label={t(\"toolbar.normal\")}\n onClick={() => editor.chain().focus().setParagraph().run()}\n active={editor.isActive(\"paragraph\")}\n />\n <DropdownMenuItem\n icon={Heading1Icon}\n label={t(\"toolbar.heading1\")}\n onClick={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}\n active={editor.isActive(\"heading\", { level: 1 })}\n shortcut=\"Ctrl+Alt+1\"\n />\n <DropdownMenuItem\n icon={Heading2Icon}\n label={t(\"toolbar.heading2\")}\n onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}\n active={editor.isActive(\"heading\", { level: 2 })}\n shortcut=\"Ctrl+Alt+2\"\n />\n <DropdownMenuItem\n icon={Heading3Icon}\n label={t(\"toolbar.heading3\")}\n onClick={() => editor.chain().focus().toggleHeading({ level: 3 }).run()}\n active={editor.isActive(\"heading\", { level: 3 })}\n shortcut=\"Ctrl+Alt+3\"\n />\n </DropdownMenu>\n\n {isFull && (\n <>\n <DropdownMenu\n trigger={\n <ToolbarButton onClick={() => {}} title={t(\"toolbar.lineHeight\")} className=\"gap-0.5\">\n <FigmaLineHeightIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n }\n contentClassName=\"max-h-72 overflow-y-auto p-1\"\n >\n <DropdownMenuItem\n icon={Type}\n label={t(\"toolbar.lineHeightDefault\")}\n onClick={() => editor.chain().focus().unsetLineHeight().run()}\n active={!currentLineHeight}\n />\n {availableLineHeights.map((option) => (\n <DropdownMenuItem\n key={option.value}\n label={option.label}\n onClick={() => editor.chain().focus().setLineHeight(option.value).run()}\n active={normalizeStyleValue(option.value) === currentLineHeight}\n />\n ))}\n </DropdownMenu>\n\n <DropdownMenu\n trigger={\n <ToolbarButton onClick={() => {}} title={t(\"toolbar.letterSpacing\")} className=\"gap-0.5\">\n <FigmaLetterSpacingIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n }\n contentClassName=\"max-h-72 overflow-y-auto p-1\"\n >\n <DropdownMenuItem\n icon={Type}\n label={t(\"toolbar.letterSpacingDefault\")}\n onClick={() => editor.chain().focus().unsetLetterSpacing().run()}\n active={!currentLetterSpacing}\n />\n {availableLetterSpacings.map((option) => (\n <DropdownMenuItem\n key={option.value}\n label={option.label}\n onClick={() => editor.chain().focus().setLetterSpacing(option.value).run()}\n active={normalizeStyleValue(option.value) === currentLetterSpacing}\n />\n ))}\n </DropdownMenu>\n </>\n )}\n\n <ToolbarDivider />\n\n {(isMediumFull || isFull) && (\n <DropdownMenu\n isOpen={isTableMenuOpen}\n onOpenChange={setIsTableMenuOpen}\n trigger={\n <ToolbarButton onClick={() => {}} title={t(\"toolbar.table\")}>\n <FigmaTableIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n }\n contentClassName=\"p-2 min-w-56\"\n >\n <TableInsertGrid\n insertLabel={t(\"tableMenu.insertTable\")}\n previewTemplate={t(\"tableMenu.gridPreview\")}\n onInsert={(rows, cols) => {\n editor.chain().focus().insertTable({ rows, cols, withHeaderRow: true }).run();\n setIsTableMenuOpen(false);\n }}\n />\n </DropdownMenu>\n )}\n\n <ToolbarButton onClick={() => editor.chain().focus().toggleBold().run()} active={editor.isActive(\"bold\")} title={t(\"toolbar.bold\")}>\n <FigmaBoldIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n <ToolbarButton onClick={() => editor.chain().focus().toggleItalic().run()} active={editor.isActive(\"italic\")} title={t(\"toolbar.italic\")}>\n <FigmaItalicIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n <ToolbarButton\n onClick={() => editor.chain().focus().toggleUnderline().run()}\n active={editor.isActive(\"underline\")}\n title={t(\"toolbar.underline\")}\n >\n <FigmaUnderlineIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n <ToolbarButton onClick={() => editor.chain().focus().toggleStrike().run()} active={editor.isActive(\"strike\")} title={t(\"toolbar.strike\")}>\n <FigmaStrikeIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n {(isMediumFull || isFull) && (\n <ToolbarButton onClick={() => editor.chain().focus().toggleCode().run()} active={editor.isActive(\"code\")} title={t(\"toolbar.code\")}>\n <FigmaCodeIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n )}\n {isFull && (\n <>\n <ToolbarButton\n onClick={() => editor.chain().focus().toggleSubscript().run()}\n active={editor.isActive(\"subscript\")}\n title={t(\"toolbar.subscript\")}\n >\n <FigmaSubscriptIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n <ToolbarButton\n onClick={() => editor.chain().focus().toggleSuperscript().run()}\n active={editor.isActive(\"superscript\")}\n title={t(\"toolbar.superscript\")}\n >\n <FigmaSuperscriptIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n </>\n )}\n\n <DropdownMenu\n contentClassName=\"min-w-72\"\n trigger={\n <ToolbarButton onClick={() => setShowLinkInput(!editor.isActive(\"link\"))} active={editor.isActive(\"link\")} title={t(\"toolbar.link\")}>\n <FigmaLinkIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n }\n >\n {showLinkInput ? (\n <LinkInput\n initialUrl={String(editor.getAttributes(\"link\").href ?? \"\")}\n onSubmit={(url) => {\n applyEditorLink(editor, url);\n setShowLinkInput(false);\n }}\n onCancel={() => setShowLinkInput(false)}\n />\n ) : (\n <>\n <DropdownMenuItem\n icon={LinkIcon}\n label={t(\"toolbar.link\")}\n onClick={() => setShowLinkInput(true)}\n active={editor.isActive(\"link\")}\n closeOnSelect={false}\n />\n <DropdownMenuItem\n icon={Trash2}\n label={t(\"toolbar.removeLink\")}\n onClick={() => editor.chain().focus().extendMarkRange(\"link\").unsetLink().run()}\n disabled={!editor.isActive(\"link\")}\n destructive\n />\n </>\n )}\n </DropdownMenu>\n\n <ToolbarDivider />\n\n <DropdownMenu\n trigger={\n <ToolbarButton onClick={() => {}} title={t(\"colors.textColor\")}>\n <TextColorIcon color={currentTextColor} />\n </ToolbarButton>\n }\n >\n <EditorColorPalette\n colors={textColors}\n currentColor={currentTextColor}\n onSelect={(color) => {\n if (color === \"inherit\") {\n editor.chain().focus().unsetColor().run();\n } else {\n editor.chain().focus().setColor(color).run();\n }\n }}\n label={t(\"colors.textColor\")}\n />\n </DropdownMenu>\n\n <DropdownMenu\n trigger={\n <ToolbarButton onClick={() => {}} active={editor.isActive(\"highlight\")} title={t(\"colors.highlight\")}>\n <HighlightColorIcon color={currentHighlightColor} />\n </ToolbarButton>\n }\n >\n <EditorColorPalette\n colors={highlightColors}\n currentColor={currentHighlightColor}\n onSelect={(color) => {\n if (color === \"\") {\n editor.chain().focus().unsetHighlight().run();\n } else {\n editor.chain().focus().toggleHighlight({ color }).run();\n }\n }}\n label={t(\"colors.highlight\")}\n />\n </DropdownMenu>\n\n {(isMediumFull || isFull) && (\n <>\n <ToolbarDivider />\n <DropdownMenu\n trigger={\n <ToolbarButton onClick={() => {}} title={t(\"toolbar.alignment\")}>\n <FigmaAlignLeftIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n }\n >\n <DropdownMenuItem\n icon={AlignLeft}\n label={t(\"toolbar.alignLeft\")}\n onClick={() => editor.chain().focus().setTextAlign(\"left\").run()}\n active={editor.isActive({ textAlign: \"left\" })}\n />\n <DropdownMenuItem\n icon={AlignCenter}\n label={t(\"toolbar.alignCenter\")}\n onClick={() => editor.chain().focus().setTextAlign(\"center\").run()}\n active={editor.isActive({ textAlign: \"center\" })}\n />\n <DropdownMenuItem\n icon={AlignRight}\n label={t(\"toolbar.alignRight\")}\n onClick={() => editor.chain().focus().setTextAlign(\"right\").run()}\n active={editor.isActive({ textAlign: \"right\" })}\n />\n <DropdownMenuItem\n icon={AlignJustify}\n label={t(\"toolbar.justify\")}\n onClick={() => editor.chain().focus().setTextAlign(\"justify\").run()}\n active={editor.isActive({ textAlign: \"justify\" })}\n />\n {hasTableContext && (\n <>\n <div className=\"my-1 border-t\" />\n <DropdownMenuItem\n icon={TableVerticalAlignTopIcon}\n label={t(\"tableMenu.alignVerticalTop\") || \"Align top\"}\n onClick={() => applyTableCellAttribute(editor, \"verticalAlign\", \"top\")}\n active={currentCellVerticalAlign === \"top\"}\n />\n <DropdownMenuItem\n icon={TableVerticalAlignMiddleIcon}\n label={t(\"tableMenu.alignVerticalMiddle\") || \"Align middle\"}\n onClick={() => applyTableCellAttribute(editor, \"verticalAlign\", \"middle\")}\n active={currentCellVerticalAlign === \"middle\"}\n />\n <DropdownMenuItem\n icon={TableVerticalAlignBottomIcon}\n label={t(\"tableMenu.alignVerticalBottom\") || \"Align bottom\"}\n onClick={() => applyTableCellAttribute(editor, \"verticalAlign\", \"bottom\")}\n active={currentCellVerticalAlign === \"bottom\"}\n />\n </>\n )}\n </DropdownMenu>\n {hasTableContext && (\n <>\n <DropdownMenu\n trigger={\n <ToolbarButton onClick={() => {}} title={t(\"tableMenu.textDirection\")}>\n {currentCellTextDirection === \"vertical\" ? <ArrowDown className=\"w-4 h-4\" /> : <ArrowRight className=\"w-4 h-4\" />}\n </ToolbarButton>\n }\n >\n <DropdownMenuItem\n icon={ArrowRight}\n label={t(\"tableMenu.horizontalText\")}\n onClick={() => applyTableCellAttribute(editor, \"textDirection\", null)}\n active={currentCellTextDirection === \"horizontal\"}\n />\n <DropdownMenuItem\n icon={ArrowDown}\n label={t(\"tableMenu.verticalText\")}\n onClick={() => applyTableCellAttribute(editor, \"textDirection\", \"vertical\")}\n active={currentCellTextDirection === \"vertical\"}\n />\n </DropdownMenu>\n <ToolbarButton\n onClick={() => applyTableCellAttribute(editor, \"textWrap\", currentCellTextWrap === \"nowrap\" ? \"wrap\" : \"nowrap\")}\n active={currentCellTextWrap !== \"nowrap\"}\n title={currentCellTextWrap === \"nowrap\" ? t(\"tableMenu.wrapText\") : t(\"tableMenu.noWrapText\")}\n >\n <WrapText className=\"h-4 w-4\" />\n </ToolbarButton>\n </>\n )}\n </>\n )}\n\n <ToolbarDivider />\n\n <DropdownMenu\n trigger={\n <ToolbarButton onClick={() => {}} title={t(\"toolbar.bulletList\")}>\n <FigmaListIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n }\n >\n <DropdownMenuItem\n icon={CircleDot}\n label={t(\"toolbar.bulletStyleDisc\")}\n onClick={() => editor.chain().focus().toggleBulletListStyle(\"disc\").run()}\n active={editor.isActive(\"bulletList\", { bulletStyle: \"disc\" })}\n />\n <DropdownMenuItem\n icon={Minus}\n label={t(\"toolbar.bulletStyleDash\")}\n onClick={() => editor.chain().focus().toggleBulletListStyle(\"dash\").run()}\n active={editor.isActive(\"bulletList\", { bulletStyle: \"dash\" })}\n />\n <DropdownMenuItem\n icon={Circle}\n label={t(\"toolbar.bulletStyleCircle\")}\n onClick={() => editor.chain().focus().toggleBulletListStyle(\"circle\").run()}\n active={editor.isActive(\"bulletList\", { bulletStyle: \"circle\" })}\n />\n <DropdownMenuItem\n icon={Square}\n label={t(\"toolbar.bulletStyleSquare\")}\n onClick={() => editor.chain().focus().toggleBulletListStyle(\"square\").run()}\n active={editor.isActive(\"bulletList\", { bulletStyle: \"square\" })}\n />\n <DropdownMenuItem\n icon={ListOrderedIcon}\n label={t(\"toolbar.orderedList\")}\n onClick={() => editor.chain().focus().toggleOrderedList().run()}\n active={editor.isActive(\"orderedList\")}\n shortcut=\"Ctrl+Shift+7\"\n />\n <DropdownMenuItem\n icon={ListTodo}\n label={t(\"toolbar.taskList\")}\n onClick={() => editor.chain().focus().toggleTaskList().run()}\n active={editor.isActive(\"taskList\")}\n shortcut=\"Ctrl+Shift+9\"\n />\n </DropdownMenu>\n\n <ToolbarButton\n onClick={() => editor.chain().focus().decreaseIndent().run()}\n disabled={!editorUiState.can.decreaseIndent}\n title={t(\"toolbar.decreaseIndent\")}\n >\n <IndentDecrease className=\"h-4 w-4\" />\n </ToolbarButton>\n <ToolbarButton\n onClick={() => editor.chain().focus().increaseIndent().run()}\n disabled={!editorUiState.can.increaseIndent}\n title={t(\"toolbar.increaseIndent\")}\n >\n <IndentIncrease className=\"h-4 w-4\" />\n </ToolbarButton>\n\n <DropdownMenu\n trigger={\n <ToolbarButton onClick={() => {}} active={editor.isActive(\"formCheckbox\")} title={t(\"slashCommand.formCheckbox\")}>\n <SquareCheckBig className=\"w-4 h-4\" />\n </ToolbarButton>\n }\n >\n <DropdownMenuItem\n icon={SquareCheckBig}\n label={t(\"slashCommand.formCheckbox\")}\n onClick={() => editor.chain().focus().setFormCheckbox().run()}\n />\n <DropdownMenuItem\n icon={CircleCheckBig}\n label={t(\"slashCommand.roundCheckbox\")}\n onClick={() => editor.chain().focus().setFormCheckbox({ variant: \"circle\" }).run()}\n />\n </DropdownMenu>\n\n {isMediumFull && (\n <ToolbarButton onClick={() => editor.chain().focus().toggleBlockquote().run()} active={editor.isActive(\"blockquote\")} title={t(\"toolbar.quote\")}>\n <FigmaQuoteIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n )}\n\n {isFull && (\n <DropdownMenu\n trigger={\n <ToolbarButton onClick={() => {}} title={t(\"toolbar.quote\")}>\n <FigmaQuoteIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n }\n >\n <DropdownMenuItem\n icon={QuoteIcon}\n label={t(\"toolbar.quote\")}\n onClick={() => editor.chain().focus().toggleBlockquote().run()}\n active={editor.isActive(\"blockquote\")}\n shortcut=\"Ctrl+Shift+B\"\n />\n <DropdownMenuItem\n icon={FileCode}\n label={t(\"toolbar.codeBlock\")}\n onClick={() => editor.chain().focus().toggleCodeBlock().run()}\n active={editor.isActive(\"codeBlock\")}\n shortcut=\"Ctrl+Alt+C\"\n />\n </DropdownMenu>\n )}\n\n {(isMediumFull || isFull) && (\n <DropdownMenu\n trigger={\n <ToolbarButton onClick={() => {}} title={t(\"toolbar.image\")}>\n <FigmaImageIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n }\n >\n {showImageInput ? (\n <ImageInput\n onSubmit={(url, alt) => {\n editor.chain().focus().setImage({ src: url, alt }).run();\n setShowImageInput(false);\n }}\n onCancel={() => setShowImageInput(false)}\n />\n ) : (\n <>\n <DropdownMenuItem icon={LinkIcon} label={t(\"imageInput.addFromUrl\")} onClick={() => setShowImageInput(true)} closeOnSelect={false} />\n <DropdownMenuItem\n icon={Upload}\n label={isUploadingImage ? t(\"imageInput.uploading\") : t(\"imageInput.uploadTab\")}\n disabled={isUploadingImage}\n onClick={() => fileInputRef.current?.click()}\n closeOnSelect={false}\n />\n {imageUploadError && <DropdownMenuItem label={imageUploadError} disabled destructive />}\n <input\n ref={fileInputRef}\n type=\"file\"\n accept={allowedImageMimeTypes.length > 0 ? allowedImageMimeTypes.join(\",\") : \"image/*\"}\n multiple\n className=\"hidden\"\n onChange={(e) => {\n const files = Array.from(e.target.files ?? []);\n e.target.value = \"\";\n void insertImageFiles(files);\n }}\n />\n <div className=\"my-1 border-t\" />\n <DropdownMenuItem\n icon={AlignCenter}\n label={t(\"toolbar.imageLayoutBlock\")}\n onClick={() => applyImageLayout(editor, \"block\")}\n active={isImageSelected && imageLayout === \"block\"}\n disabled={!isImageSelected}\n />\n <DropdownMenuItem\n icon={AlignLeft}\n label={t(\"toolbar.imageLayoutLeft\")}\n onClick={() => applyImageLayout(editor, \"left\")}\n active={isImageSelected && imageLayout === \"left\"}\n disabled={!isImageSelected}\n />\n <DropdownMenuItem\n icon={AlignRight}\n label={t(\"toolbar.imageLayoutRight\")}\n onClick={() => applyImageLayout(editor, \"right\")}\n active={isImageSelected && imageLayout === \"right\"}\n disabled={!isImageSelected}\n />\n <div className=\"my-1 border-t\" />\n <DropdownMenuItem\n label={t(\"toolbar.imageWidthSm\")}\n onClick={() => applyImageWidthPreset(editor, \"sm\")}\n active={isImageSelected && imageWidthPreset === \"sm\"}\n disabled={!isImageSelected}\n />\n <DropdownMenuItem\n label={t(\"toolbar.imageWidthMd\")}\n onClick={() => applyImageWidthPreset(editor, \"md\")}\n active={isImageSelected && imageWidthPreset === \"md\"}\n disabled={!isImageSelected}\n />\n <DropdownMenuItem\n label={t(\"toolbar.imageWidthLg\")}\n onClick={() => applyImageWidthPreset(editor, \"lg\")}\n active={isImageSelected && imageWidthPreset === \"lg\"}\n disabled={!isImageSelected}\n />\n <div className=\"my-1 border-t\" />\n <DropdownMenuItem\n icon={RotateCcw}\n label={t(\"toolbar.imageResetSize\")}\n onClick={() => resetImageSize(editor)}\n disabled={!isImageSelected}\n />\n <DropdownMenuItem\n icon={Trash2}\n label={t(\"toolbar.imageDelete\")}\n onClick={() => deleteSelectedImage(editor)}\n disabled={!isImageSelected}\n destructive\n />\n </>\n )}\n </DropdownMenu>\n )}\n\n <ToolbarDivider />\n\n <ToolbarButton onClick={() => editor.chain().focus().undo().run()} disabled={!editor.can().undo()} title={t(\"toolbar.undo\")}>\n <FigmaUndoIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n <ToolbarButton onClick={() => editor.chain().focus().redo().run()} disabled={!editor.can().redo()} title={t(\"toolbar.redo\")}>\n <FigmaRedoIcon className=\"h-4 w-4\" />\n </ToolbarButton>\n\n {hasTableContext && (\n <>\n <ToolbarDivider />\n <ToolbarButton\n onClick={() => editor.chain().focus().addColumnBefore().run()}\n disabled={!editor.can().addColumnBefore()}\n title={t(\"tableMenu.addColumnBefore\")}\n >\n <ArrowLeft className=\"w-4 h-4\" />\n </ToolbarButton>\n <ToolbarButton\n onClick={() => editor.chain().focus().addColumnAfter().run()}\n disabled={!editor.can().addColumnAfter()}\n title={t(\"tableMenu.addColumnAfter\")}\n >\n <ArrowRight className=\"w-4 h-4\" />\n </ToolbarButton>\n <ToolbarButton\n onClick={() => editor.chain().focus().addRowBefore().run()}\n disabled={!editor.can().addRowBefore()}\n title={t(\"tableMenu.addRowBefore\")}\n >\n <ArrowUp className=\"w-4 h-4\" />\n </ToolbarButton>\n <ToolbarButton\n onClick={() => editor.chain().focus().addRowAfter().run()}\n disabled={!editor.can().addRowAfter()}\n title={t(\"tableMenu.addRowAfter\")}\n >\n <ArrowDown className=\"w-4 h-4\" />\n </ToolbarButton>\n <ToolbarButton\n onClick={() => {\n if (canSplitCell) {\n editor.chain().focus().splitCell().run();\n return;\n }\n mergeTableCellsPreservingColumnWidths(editor);\n }}\n active={canSplitCell}\n disabled={!canMergeCells && !canSplitCell}\n title={canSplitCell ? t(\"tableMenu.splitCell\") : t(\"tableMenu.mergeCells\")}\n >\n <TableCellsMerge className=\"w-4 h-4\" />\n </ToolbarButton>\n </>\n )}\n\n {onToggleMenuBar && (\n <ToolbarButton\n onClick={onToggleMenuBar}\n active={isMenuBarVisible}\n title={t(isMenuBarVisible ? \"toolbar.hideMenuBar\" : \"toolbar.showMenuBar\")}\n >\n {isMenuBarVisible ? <PanelTopClose className=\"h-4 w-4\" /> : <PanelTopOpen className=\"h-4 w-4\" />}\n </ToolbarButton>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport React, { useMemo, useRef } from \"react\";\nimport { useSmartTranslations } from \"../../hooks/useSmartTranslations\";\nimport { Check, Palette, Paintbrush, Grid } from \"lucide-react\";\nimport { cn } from \"../../utils/cn\";\nimport { Tooltip } from \"../Tooltip\";\nimport { FigmaHighlighterIcon } from \"./figma-toolbar-icons\";\n\nexport type UEditorColorOption = { name: string; color: string; cssClass?: string; automatic?: boolean };\n\nexport const TextColorIcon = ({ color }: { color?: string }) => {\n const underlineColor = color && color !== \"inherit\" ? color : \"currentColor\";\n\n return (\n <span className=\"relative flex h-5 w-5 items-center justify-center leading-none\">\n <span className=\"text-[15px] font-semibold leading-none\">A</span>\n <span\n aria-hidden=\"true\"\n className=\"absolute bottom-0 left-1/2 h-0.5 w-4 -translate-x-1/2 rounded-full\"\n style={{ backgroundColor: underlineColor }}\n />\n </span>\n );\n};\n\nexport const HighlightColorIcon = ({ color }: { color?: string }) => {\n const underlineColor = color || \"currentColor\";\n\n return (\n <span className=\"relative flex h-5 w-5 items-center justify-center leading-none\">\n <FigmaHighlighterIcon className=\"h-4 w-4\" />\n <span\n aria-hidden=\"true\"\n className=\"absolute bottom-0 left-1/2 h-0.5 w-4 -translate-x-1/2 rounded-full\"\n style={{ backgroundColor: underlineColor }}\n />\n </span>\n );\n};\n\nexport const CellBgColorIcon = ({ color }: { color?: string }) => {\n const underlineColor = color && color !== \"inherit\" ? color : \"currentColor\";\n\n return (\n <span className=\"relative flex h-5 w-5 items-center justify-center leading-none\">\n <Paintbrush className=\"h-4 w-4\" />\n <span\n aria-hidden=\"true\"\n className=\"absolute bottom-0 left-1/2 h-0.5 w-4 -translate-x-1/2 rounded-full\"\n style={{ backgroundColor: underlineColor }}\n />\n </span>\n );\n};\n\nexport const CellBorderIcon = ({ color }: { color?: string }) => {\n const underlineColor = color && color !== \"inherit\" ? color : \"currentColor\";\n\n return (\n <span className=\"relative flex h-5 w-5 items-center justify-center leading-none\">\n <Grid className=\"h-4 w-4\" />\n <span\n aria-hidden=\"true\"\n className=\"absolute bottom-0 left-1/2 h-0.5 w-4 -translate-x-1/2 rounded-full\"\n style={{ backgroundColor: underlineColor }}\n />\n </span>\n );\n};\n\nconst EDITOR_COLOR_SWATCHES = [\n \"#000000\",\n \"#3f3f46\",\n \"#713f12\",\n \"#14532d\",\n \"#164e63\",\n \"#1e3a8a\",\n \"#3730a3\",\n \"#404040\",\n \"#b91c1c\",\n \"#c2410c\",\n \"#a16207\",\n \"#15803d\",\n \"#0f766e\",\n \"#2563eb\",\n \"#4f46e5\",\n \"#737373\",\n \"#ef4444\",\n \"#f97316\",\n \"#eab308\",\n \"#22c55e\",\n \"#14b8a6\",\n \"#3b82f6\",\n \"#7c3aed\",\n \"#a3a3a3\",\n \"#f43f5e\",\n \"#f59e0b\",\n \"#facc15\",\n \"#00e676\",\n \"#22d3ee\",\n \"#06b6d4\",\n \"#be185d\",\n \"#bdbdbd\",\n \"#f9a8d4\",\n \"#fecaca\",\n \"#fde68a\",\n \"#bbf7d0\",\n \"#a7f3d0\",\n \"#bae6fd\",\n \"#c4b5fd\",\n \"#f5f5f5\",\n];\n\nconst HIGHLIGHT_COLOR_SWATCHES = [\n \"#fef08a\",\n \"#fde68a\",\n \"#fed7aa\",\n \"#fecaca\",\n \"#fbcfe8\",\n \"#e9d5ff\",\n \"#c7d2fe\",\n \"#bfdbfe\",\n \"#bae6fd\",\n \"#ccfbf1\",\n \"#bbf7d0\",\n \"#d9f99d\",\n \"#e5e7eb\",\n \"#fca5a5\",\n \"#fdba74\",\n \"#facc15\",\n \"#86efac\",\n \"#5eead4\",\n \"#7dd3fc\",\n \"#a5b4fc\",\n \"#d8b4fe\",\n \"#f0abfc\",\n \"#f9a8d4\",\n \"#d4d4d4\",\n];\n\nfunction buildColorOptions(colors: string[], prefix: string): UEditorColorOption[] {\n return colors.map((color, index) => ({ name: `${prefix} ${index + 1}`, color }));\n}\n\nfunction getSwatchCheckClass(color: string) {\n return /^#(?:fff|ffffff)$/i.test(color) ? \"text-foreground\" : \"text-white drop-shadow-[0_1px_1px_rgba(0,0,0,0.8)]\";\n}\n\nexport const useEditorColors = () => {\n const t = useSmartTranslations(\"UEditor\");\n\n const textColors = useMemo<UEditorColorOption[]>(\n () => [\n { name: t(\"colors.default\"), color: \"inherit\", cssClass: \"text-foreground\" },\n { name: t(\"colors.muted\"), color: \"var(--muted-foreground)\", cssClass: \"text-muted-foreground\" },\n { name: t(\"colors.primary\"), color: \"var(--primary)\", cssClass: \"text-primary\" },\n { name: t(\"colors.secondary\"), color: \"var(--secondary)\", cssClass: \"text-secondary\" },\n { name: t(\"colors.success\"), color: \"var(--success)\", cssClass: \"text-success\" },\n { name: t(\"colors.warning\"), color: \"var(--warning)\", cssClass: \"text-warning\" },\n { name: t(\"colors.destructive\"), color: \"var(--destructive)\", cssClass: \"text-destructive\" },\n { name: t(\"colors.info\"), color: \"var(--info)\", cssClass: \"text-info\" },\n ...buildColorOptions(EDITOR_COLOR_SWATCHES, t(\"colors.color\")),\n ],\n [t],\n );\n\n const highlightColors = useMemo<UEditorColorOption[]>(\n () => [\n { name: t(\"colors.default\"), color: \"\", cssClass: \"\" },\n { name: t(\"colors.muted\"), color: \"var(--muted)\", cssClass: \"bg-muted\" },\n { name: t(\"colors.primary\"), color: \"color-mix(in oklch, var(--primary) 20%, transparent)\", cssClass: \"bg-primary/20\" },\n { name: t(\"colors.secondary\"), color: \"color-mix(in oklch, var(--secondary) 20%, transparent)\", cssClass: \"bg-secondary/20\" },\n { name: t(\"colors.success\"), color: \"color-mix(in oklch, var(--success) 20%, transparent)\", cssClass: \"bg-success/20\" },\n { name: t(\"colors.warning\"), color: \"color-mix(in oklch, var(--warning) 20%, transparent)\", cssClass: \"bg-warning/20\" },\n { name: t(\"colors.destructive\"), color: \"color-mix(in oklch, var(--destructive) 20%, transparent)\", cssClass: \"bg-destructive/20\" },\n { name: t(\"colors.info\"), color: \"color-mix(in oklch, var(--info) 20%, transparent)\", cssClass: \"bg-info/20\" },\n { name: t(\"colors.accent\"), color: \"var(--accent)\", cssClass: \"bg-accent\" },\n ...buildColorOptions(HIGHLIGHT_COLOR_SWATCHES, t(\"colors.color\")),\n ],\n [t],\n );\n\n return { textColors, highlightColors };\n};\n\nexport const EditorColorPalette = ({\n colors,\n currentColor,\n onSelect,\n onCustomColorSelect,\n label,\n}: {\n colors: UEditorColorOption[];\n currentColor: string;\n onSelect: (color: string) => void;\n onCustomColorSelect?: (color: string) => void;\n label: string;\n}) => {\n const t = useSmartTranslations(\"UEditor\");\n const colorInputRef = useRef<HTMLInputElement>(null);\n const automaticColor = colors[0]?.color ?? \"\";\n const paletteColors = colors.slice(1);\n const customColorSelect = onCustomColorSelect ?? onSelect;\n const [hexInput, setHexInput] = React.useState(currentColor.startsWith(\"#\") ? currentColor : \"\");\n\n React.useEffect(() => {\n setHexInput(currentColor.startsWith(\"#\") ? currentColor : \"\");\n }, [currentColor]);\n\n const commitHex = (val: string) => {\n let formatted = val.trim();\n if (!formatted) return;\n if (!formatted.startsWith(\"#\")) formatted = `#${formatted}`;\n if (/^#([0-9A-F]{3}){1,2}$/i.test(formatted)) {\n customColorSelect(formatted);\n }\n };\n\n React.useEffect(() => {\n const input = colorInputRef.current;\n if (!input) return;\n\n const commitColor = () => customColorSelect(input.value);\n input.addEventListener(\"change\", commitColor);\n return () => input.removeEventListener(\"change\", commitColor);\n }, [customColorSelect]);\n\n React.useEffect(() => {\n const input = colorInputRef.current;\n if (input) input.value = currentColor.startsWith(\"#\") ? currentColor : \"#000000\";\n }, [currentColor]);\n\n return (\n <div className=\"w-56 p-2\" data-ueditor-keep-open>\n <span className=\"px-1 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground\">{label}</span>\n <button\n type=\"button\"\n onMouseDown={(e) => e.preventDefault()}\n onClick={() => onSelect(automaticColor)}\n className={cn(\n \"mt-2 flex h-9 w-full items-center gap-3 rounded-md border px-2 text-sm transition-colors\",\n \"bg-muted/50 hover:bg-muted\",\n currentColor === automaticColor ? \"border-primary text-primary\" : \"border-transparent text-foreground\",\n )}\n >\n <span className=\"flex h-5 w-5 items-center justify-center rounded border border-border bg-background\">\n {currentColor === automaticColor && <Check className=\"h-3.5 w-3.5\" />}\n </span>\n <span className=\"flex-1 text-center\">{t(\"colors.automatic\")}</span>\n </button>\n\n <div className=\"mt-2 grid grid-cols-8 gap-1\">\n {paletteColors.map((c) => (\n <Tooltip key={`${c.name}-${c.color}`} placement=\"top\" content={<span className=\"text-xs font-medium\">{c.name}</span>}>\n <button\n type=\"button\"\n aria-label={c.name}\n onMouseDown={(e) => e.preventDefault()}\n onClick={() => onSelect(c.color)}\n className={cn(\n \"relative h-5 w-5 rounded-[3px] border transition-transform hover:scale-110\",\n currentColor === c.color ? \"border-primary ring-2 ring-primary/25\" : \"border-border/70\",\n )}\n style={{ backgroundColor: c.color || \"transparent\" }}\n >\n {currentColor === c.color && (\n <span className=\"absolute inset-0 flex items-center justify-center\">\n <Check className={cn(\"h-3.5 w-3.5\", getSwatchCheckClass(c.color))} />\n </span>\n )}\n </button>\n </Tooltip>\n ))}\n </div>\n\n <div className=\"mt-3 flex items-center gap-2\">\n <div className=\"flex h-8 flex-1 items-center gap-1.5 rounded-md border border-input bg-muted/30 px-2\">\n <span\n className=\"h-4 w-4 shrink-0 rounded-[2px] border border-border\"\n style={{ backgroundColor: hexInput.startsWith(\"#\") ? hexInput : currentColor.startsWith(\"#\") ? currentColor : \"transparent\" }}\n />\n <input\n type=\"text\"\n value={hexInput}\n onChange={(e) => setHexInput(e.target.value)}\n onBlur={() => commitHex(hexInput)}\n onMouseDown={(e) => e.stopPropagation()}\n onClick={(e) => e.stopPropagation()}\n onKeyDown={(e) => {\n e.stopPropagation();\n if (e.key === \"Enter\") {\n e.preventDefault();\n commitHex(hexInput);\n }\n }}\n placeholder=\"#HEX\"\n className=\"h-full w-full bg-transparent text-xs font-mono text-foreground outline-none placeholder:text-muted-foreground\"\n />\n </div>\n <button\n type=\"button\"\n onMouseDown={(e) => e.stopPropagation()}\n onClick={() => colorInputRef.current?.click()}\n title={t(\"colors.moreColors\")}\n className=\"flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-input bg-muted/30 text-foreground transition-colors hover:bg-muted\"\n >\n <Palette className=\"h-4 w-4 text-muted-foreground\" />\n </button>\n </div>\n\n <input\n ref={colorInputRef}\n type=\"color\"\n defaultValue={currentColor.startsWith(\"#\") ? currentColor : \"#000000\"}\n className=\"sr-only\"\n tabIndex={-1}\n />\n </div>\n );\n};\n","import React from \"react\";\n\n/**\n * Solid toolbar glyphs used by the Figma \"Rich Text Content Area\".\n * Path data is adapted from Font Awesome Free 6.7.2 (CC BY 4.0):\n * https://fontawesome.com/license/free\n */\ntype ToolbarIconProps = React.SVGProps<SVGSVGElement>;\n\nfunction createToolbarIcon(displayName: string, width: number, height: number, path: string) {\n const Icon = React.forwardRef<SVGSVGElement, ToolbarIconProps>(({ className, ...props }, ref) => (\n <svg\n ref={ref}\n aria-hidden=\"true\"\n focusable=\"false\"\n viewBox={`0 0 ${width} ${height}`}\n className={className}\n fill=\"currentColor\"\n xmlns=\"http://www.w3.org/2000/svg\"\n {...props}\n >\n <path d={path} />\n </svg>\n ));\n Icon.displayName = displayName;\n return Icon;\n}\n\nexport const FigmaChevronDownIcon = createToolbarIcon(\n \"FigmaChevronDownIcon\",\n 512,\n 512,\n \"M233.4 406.6c12.5 12.5 32.8 12.5 45.3 0l192-192c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L256 338.7 86.6 169.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l192 192z\",\n);\n\nexport const FigmaTextStyleIcon = ({ className, ...props }: ToolbarIconProps) => (\n <svg aria-hidden=\"true\" focusable=\"false\" viewBox=\"0 0 24 24\" className={className} fill=\"currentColor\" {...props}>\n <path d=\"M4 4.25C4 3.56 4.56 3 5.25 3h13.5C19.44 3 20 3.56 20 4.25v2.5a1 1 0 1 1-2 0V5h-5v14h2a1 1 0 1 1 0 2H9a1 1 0 1 1 0-2h2V5H6v1.75a1 1 0 1 1-2 0v-2.5Z\" />\n </svg>\n);\n\nexport const FigmaLineHeightIcon = createToolbarIcon(\n \"FigmaLineHeightIcon\",\n 576,\n 512,\n \"M64 128l0-32 64 0 0 320-32 0c-17.7 0-32 14.3-32 32s14.3 32 32 32l128 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-32 0 0-320 64 0 0 32c0 17.7 14.3 32 32 32s32-14.3 32-32l0-48c0-26.5-21.5-48-48-48L160 32 48 32C21.5 32 0 53.5 0 80l0 48c0 17.7 14.3 32 32 32s32-14.3 32-32zM502.6 41.4c-12.5-12.5-32.8-12.5-45.3 0l-64 64c-9.2 9.2-11.9 22.9-6.9 34.9s16.6 19.8 29.6 19.8l32 0 0 192-32 0c-12.9 0-24.6 7.8-29.6 19.8s-2.2 25.7 6.9 34.9l64 64c12.5 12.5 32.8 12.5 45.3 0l64-64c9.2-9.2 11.9-22.9 6.9-34.9s-16.6-19.8-29.6-19.8l-32 0 0-192 32 0c12.9 0 24.6-7.8 29.6-19.8s2.2-25.7-6.9-34.9l-64-64z\",\n);\n\nexport const FigmaLetterSpacingIcon = createToolbarIcon(\n \"FigmaLetterSpacingIcon\",\n 448,\n 512,\n \"M64 128l0-32 128 0 0 128-16 0c-17.7 0-32 14.3-32 32s14.3 32 32 32l96 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-16 0 0-128 128 0 0 32c0 17.7 14.3 32 32 32s32-14.3 32-32l0-48c0-26.5-21.5-48-48-48L224 32 48 32C21.5 32 0 53.5 0 80l0 48c0 17.7 14.3 32 32 32s32-14.3 32-32zM9.4 361.4c-12.5 12.5-12.5 32.8 0 45.3l64 64c9.2 9.2 22.9 11.9 34.9 6.9s19.8-16.6 19.8-29.6l0-32 192 0 0 32c0 12.9 7.8 24.6 19.8 29.6s25.7 2.2 34.9-6.9l64-64c12.5-12.5 12.5-32.8 0-45.3l-64-64c-9.2-9.2-22.9-11.9-34.9-6.9s-19.8 16.6-19.8 29.6l0 32-192 0 0-32c0-12.9-7.8-24.6-19.8-29.6s-25.7-2.2-34.9 6.9l-64 64z\",\n);\n\nexport const FigmaBoldIcon = createToolbarIcon(\n \"FigmaBoldIcon\",\n 384,\n 512,\n \"M0 64C0 46.3 14.3 32 32 32l48 0 16 0 128 0c70.7 0 128 57.3 128 128c0 31.3-11.3 60.1-30 82.3c37.1 22.4 62 63.1 62 109.7c0 70.7-57.3 128-128 128L96 480l-16 0-48 0c-17.7 0-32-14.3-32-32s14.3-32 32-32l16 0 0-160L48 96 32 96C14.3 96 0 81.7 0 64zM224 224c35.3 0 64-28.7 64-64s-28.7-64-64-64L112 96l0 128 112 0zM112 288l0 128 144 0c35.3 0 64-28.7 64-64s-28.7-64-64-64l-32 0-112 0z\",\n);\n\nexport const FigmaItalicIcon = createToolbarIcon(\n \"FigmaItalicIcon\",\n 384,\n 512,\n \"M128 64c0-17.7 14.3-32 32-32l192 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-58.7 0L160 416l64 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 480c-17.7 0-32-14.3-32-32s14.3-32 32-32l58.7 0L224 96l-64 0c-17.7 0-32-14.3-32-32z\",\n);\n\nexport const FigmaUnderlineIcon = createToolbarIcon(\n \"FigmaUnderlineIcon\",\n 448,\n 512,\n \"M16 64c0-17.7 14.3-32 32-32l96 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-16 0 0 128c0 53 43 96 96 96s96-43 96-96l0-128-16 0c-17.7 0-32-14.3-32-32s14.3-32 32-32l96 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-16 0 0 128c0 88.4-71.6 160-160 160s-160-71.6-160-160L64 96 48 96C30.3 96 16 81.7 16 64zM0 448c0-17.7 14.3-32 32-32l384 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 480c-17.7 0-32-14.3-32-32z\",\n);\n\nexport const FigmaStrikeIcon = createToolbarIcon(\n \"FigmaStrikeIcon\",\n 512,\n 512,\n \"M161.3 144c3.2-17.2 14-30.1 33.7-38.6c21.1-9 51.8-12.3 88.6-6.5c11.9 1.9 48.8 9.1 60.1 12c17.1 4.5 34.6-5.6 39.2-22.7s-5.6-34.6-22.7-39.2c-14.3-3.8-53.6-11.4-66.6-13.4c-44.7-7-88.3-4.2-123.7 10.9c-36.5 15.6-64.4 44.8-71.8 87.3c-.1 .6-.2 1.1-.2 1.7c-2.8 23.9 .5 45.6 10.1 64.6c4.5 9 10.2 16.9 16.7 23.9L32 224c-17.7 0-32 14.3-32 32s14.3 32 32 32l448 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-209.9 0-.4-.1-1.1-.3c-36-10.8-65.2-19.6-85.2-33.1c-9.3-6.3-15-12.6-18.2-19.1c-3.1-6.1-5.2-14.6-3.8-27.4zM348.9 337.2c2.7 6.5 4.4 15.8 1.9 30.1c-3 17.6-13.8 30.8-33.9 39.4c-21.1 9-51.7 12.3-88.5 6.5c-18-2.9-49.1-13.5-74.4-22.1c-5.6-1.9-11-3.7-15.9-5.4c-16.8-5.6-34.9 3.5-40.5 20.3s3.5 34.9 20.3 40.5c3.6 1.2 7.9 2.7 12.7 4.3c24.9 8.5 63.6 21.7 87.6 25.6l.2 0c44.7 7 88.3 4.2 123.7-10.9c36.5-15.6 64.4-44.8 71.8-87.3c3.6-21 2.7-40.4-3.1-58.1l-75.7 0c7 5.6 11.4 11.2 13.9 17.2z\",\n);\n\nexport const FigmaCodeIcon = createToolbarIcon(\n \"FigmaCodeIcon\",\n 640,\n 512,\n \"M392.8 1.2c-17-4.9-34.7 5-39.6 22l-128 448c-4.9 17 5 34.7 22 39.6s34.7-5 39.6-22l128-448c4.9-17-5-34.7-22-39.6zm80.6 120.1c-12.5 12.5-12.5 32.8 0 45.3L562.7 256l-89.4 89.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0l112-112c12.5-12.5 12.5-32.8 0-45.3l-112-112c-12.5-12.5-32.8-12.5-45.3 0zm-306.7 0c-12.5-12.5-32.8-12.5-45.3 0l-112 112c-12.5 12.5-12.5 32.8 0 45.3l112 112c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L77.3 256l89.4-89.4c12.5-12.5 12.5-32.8 0-45.3z\",\n);\n\nexport const FigmaSubscriptIcon = createToolbarIcon(\n \"FigmaSubscriptIcon\",\n 512,\n 512,\n \"M32 64C14.3 64 0 78.3 0 96s14.3 32 32 32l15.3 0 89.6 128L47.3 384 32 384c-17.7 0-32 14.3-32 32s14.3 32 32 32l32 0c10.4 0 20.2-5.1 26.2-13.6L176 311.8l85.8 122.6c6 8.6 15.8 13.6 26.2 13.6l32 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-15.3 0L215.1 256l89.6-128 15.3 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-32 0c-10.4 0-20.2 5.1-26.2 13.6L176 200.2 90.2 77.6C84.2 69.1 74.4 64 64 64L32 64zM480 320c0-11.1-5.7-21.4-15.2-27.2s-21.2-6.4-31.1-1.4l-32 16c-15.8 7.9-22.2 27.1-14.3 42.9C393 361.5 404.3 368 416 368l0 80c-17.7 0-32 14.3-32 32s14.3 32 32 32l64 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l0-128z\",\n);\n\nexport const FigmaSuperscriptIcon = createToolbarIcon(\n \"FigmaSuperscriptIcon\",\n 512,\n 512,\n \"M480 32c0-11.1-5.7-21.4-15.2-27.2s-21.2-6.4-31.1-1.4l-32 16c-15.8 7.9-22.2 27.1-14.3 42.9C393 73.5 404.3 80 416 80l0 80c-17.7 0-32 14.3-32 32s14.3 32 32 32l64 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l0-128zM32 64C14.3 64 0 78.3 0 96s14.3 32 32 32l15.3 0 89.6 128L47.3 384 32 384c-17.7 0-32 14.3-32 32s14.3 32 32 32l32 0c10.4 0 20.2-5.1 26.2-13.6L176 311.8l85.8 122.6c6 8.6 15.8 13.6 26.2 13.6l32 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-15.3 0L215.1 256l89.6-128 15.3 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-32 0c-10.4 0-20.2 5.1-26.2 13.6L176 200.2 90.2 77.6C84.2 69.1 74.4 64 64 64L32 64z\",\n);\n\nexport const FigmaLinkIcon = createToolbarIcon(\n \"FigmaLinkIcon\",\n 640,\n 512,\n \"M579.8 267.7c56.5-56.5 56.5-148 0-204.5c-50-50-128.8-56.5-186.3-15.4l-1.6 1.1c-14.4 10.3-17.7 30.3-7.4 44.6s30.3 17.7 44.6 7.4l1.6-1.1c32.1-22.9 76-19.3 103.8 8.6c31.5 31.5 31.5 82.5 0 114L422.3 334.8c-31.5 31.5-82.5 31.5-114 0c-27.9-27.9-31.5-71.8-8.6-103.8l1.1-1.6c10.3-14.4 6.9-34.4-7.4-44.6s-34.4-6.9-44.6 7.4l-1.1 1.6C206.5 251.2 213 330 263 380c56.5 56.5 148 56.5 204.5 0L579.8 267.7zM60.2 244.3c-56.5 56.5-56.5 148 0 204.5c50 50 128.8 56.5 186.3 15.4l1.6-1.1c14.4-10.3 17.7-30.3 7.4-44.6s-30.3-17.7-44.6-7.4l-1.6 1.1c-32.1 22.9-76 19.3-103.8-8.6C74 372 74 321 105.5 289.5L217.7 177.2c31.5-31.5 82.5-31.5 114 0c27.9 27.9 31.5 71.8 8.6 103.9l-1.1 1.6c-10.3 14.4-6.9 34.4 7.4 44.6s34.4 6.9 44.6-7.4l1.1-1.6C433.5 260.8 427 182 377 132c-56.5-56.5-148-56.5-204.5 0L60.2 244.3z\",\n);\n\nexport const FigmaSmileIcon = createToolbarIcon(\n \"FigmaSmileIcon\",\n 512,\n 512,\n \"M464 256A208 208 0 1 0 48 256a208 208 0 1 0 416 0zM0 256a256 256 0 1 1 512 0A256 256 0 1 1 0 256zm177.6 62.1C192.8 334.5 218.8 352 256 352s63.2-17.5 78.4-33.9c9-9.7 24.2-10.4 33.9-1.4s10.4 24.2 1.4 33.9c-22 23.8-60 49.4-113.6 49.4s-91.7-25.5-113.6-49.4c-9-9.7-8.4-24.9 1.4-33.9s24.9-8.4 33.9 1.4zM144.4 208a32 32 0 1 1 64 0 32 32 0 1 1 -64 0zm192-32a32 32 0 1 1 0 64 32 32 0 1 1 0-64z\",\n);\n\nexport const FigmaAlignLeftIcon = createToolbarIcon(\n \"FigmaAlignLeftIcon\",\n 448,\n 512,\n \"M288 64c0 17.7-14.3 32-32 32L32 96C14.3 96 0 81.7 0 64S14.3 32 32 32l224 0c17.7 0 32 14.3 32 32zm0 256c0 17.7-14.3 32-32 32L32 352c-17.7 0-32-14.3-32-32s14.3-32 32-32l224 0c17.7 0 32 14.3 32 32zM0 192c0-17.7 14.3-32 32-32l384 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 224c-17.7 0-32-14.3-32-32zM448 448c0 17.7-14.3 32-32 32L32 480c-17.7 0-32-14.3-32-32s14.3-32 32-32l384 0c17.7 0 32 14.3 32 32z\",\n);\n\nexport const FigmaListIcon = createToolbarIcon(\n \"FigmaListIcon\",\n 512,\n 512,\n \"M64 144a48 48 0 1 0 0-96 48 48 0 1 0 0 96zM192 64c-17.7 0-32 14.3-32 32s14.3 32 32 32l288 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L192 64zm0 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l288 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-288 0zm0 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l288 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-288 0zM64 464a48 48 0 1 0 0-96 48 48 0 1 0 0 96zm48-208a48 48 0 1 0-96 0 48 48 0 1 0 96 0z\",\n);\n\nexport const FigmaQuoteIcon = createToolbarIcon(\n \"FigmaQuoteIcon\",\n 448,\n 512,\n \"M0 216C0 149.7 53.7 96 120 96l8 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-8 0c-30.9 0-56 25.1-56 56l0 8 64 0c35.3 0 64 28.7 64 64l0 64c0 35.3-28.7 64-64 64l-64 0c-35.3 0-64-28.7-64-64l0-136zm256 0c0-66.3 53.7-120 120-120l8 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-8 0c-30.9 0-56 25.1-56 56l0 8 64 0c35.3 0 64 28.7 64 64l0 64c0 35.3-28.7 64-64 64l-64 0c-35.3 0-64-28.7-64-64l0-136z\",\n);\n\nexport const FigmaImageIcon = createToolbarIcon(\n \"FigmaImageIcon\",\n 512,\n 512,\n \"M0 96C0 60.7 28.7 32 64 32l384 0c35.3 0 64 28.7 64 64l0 320c0 35.3-28.7 64-64 64L64 480c-35.3 0-64-28.7-64-64L0 96zM323.8 202.5c-4.5-6.6-11.9-10.5-19.8-10.5s-15.4 3.9-19.8 10.5l-87 127.6L170.7 297c-4.6-5.7-11.5-9-18.7-9s-14.2 3.3-18.7 9l-64 80c-5.8 7.2-6.9 17.1-2.9 25.4s12.4 13.6 21.6 13.6l336 0c8.9 0 17.1-4.9 21.2-12.8s3.6-17.4-1.4-24.7l-120-176zM112 192a48 48 0 1 0 0-96 48 48 0 1 0 0 96z\",\n);\n\nexport const FigmaTableIcon = createToolbarIcon(\n \"FigmaTableIcon\",\n 512,\n 512,\n \"M64 256l0-96 160 0 0 96L64 256zm0 64l160 0 0 96L64 416l0-96zm224 96l0-96 160 0 0 96-160 0zM448 256l-160 0 0-96 160 0 0 96zM64 32C28.7 32 0 60.7 0 96L0 416c0 35.3 28.7 64 64 64l384 0c35.3 0 64-28.7 64-64l0-320c0-35.3-28.7-64-64-64L64 32z\",\n);\n\nexport const FigmaUndoIcon = createToolbarIcon(\n \"FigmaUndoIcon\",\n 512,\n 512,\n \"M48.5 224L40 224c-13.3 0-24-10.7-24-24L16 72c0-9.7 5.8-18.5 14.8-22.2s19.3-1.7 26.2 5.2l41.6 41.6c87.6-86.5 228.7-86.2 315.8 1c87.5 87.5 87.5 229.3 0 316.8s-229.3 87.5-316.8 0c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0c62.5 62.5 163.8 62.5 226.3 0s62.5-163.8 0-226.3c-62.2-62.2-162.7-62.5-225.3-1L185 183c6.9 6.9 8.9 17.2 5.2 26.2S177.7 224 168 224L48.5 224z\",\n);\n\nexport const FigmaRedoIcon = createToolbarIcon(\n \"FigmaRedoIcon\",\n 512,\n 512,\n \"M463.5 224l8.5 0c13.3 0 24-10.7 24-24l0-128c0-9.7-5.8-18.5-14.8-22.2s-19.3-1.7-26.2 5.2l-41.6 41.6c-87.6-86.5-228.7-86.2-315.8 1c-87.5 87.5-87.5 229.3 0 316.8s229.3 87.5 316.8 0c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0c-62.5 62.5-163.8 62.5-226.3 0s-62.5-163.8 0-226.3c62.2-62.2 162.7-62.5 225.3-1L327 183c-6.9 6.9-8.9 17.2-5.2 26.2S334.3 224 344 224l119.5 0z\",\n);\n\nexport const FigmaHighlighterIcon = createToolbarIcon(\n \"FigmaHighlighterIcon\",\n 576,\n 512,\n \"M315 315l158.4-215L444.1 70.6 229 229 315 315zm-187 5l0-71.7c0-15.3 7.2-29.6 19.5-38.6L420.6 8.4C428 2.9 437 0 446.2 0c11.4 0 22.4 4.5 30.5 12.6l54.8 54.8c8.1 8.1 12.6 19 12.6 30.5c0 9.2-2.9 18.2-8.4 25.6L334.4 396.5c-9 12.3-23.4 19.5-38.6 19.5L224 416l-25.4 25.4c-12.5 12.5-32.8 12.5-45.3 0l-50.7-50.7c-12.5-12.5-12.5-32.8 0-45.3L128 320zM7 466.3l63-63 70.6 70.6-31 31c-4.5 4.5-10.6 7-17 7L24 512c-13.3 0-24-10.7-24-24l0-4.7c0-6.4 2.5-12.5 7-17z\",\n);\n","import type { Editor } from \"@tiptap/core\";\nimport { NodeSelection, TextSelection } from \"@tiptap/pm/state\";\n\nexport type UEditorImageLayout = \"block\" | \"left\" | \"right\";\nexport type UEditorImageWidthPreset = \"sm\" | \"md\" | \"lg\";\n\nconst IMAGE_WIDTHS_BY_LAYOUT: Record<\"block\" | \"wrap\", Record<UEditorImageWidthPreset, number>> = {\n block: {\n sm: 180,\n md: 280,\n lg: 380,\n },\n wrap: {\n sm: 140,\n md: 200,\n lg: 260,\n },\n};\n\nfunction isSelectedImage(editor: Editor) {\n const { selection } = editor.state;\n return selection instanceof NodeSelection && selection.node.type.name === \"image\";\n}\n\nfunction toPositiveNumber(value: unknown): number | null {\n if (typeof value === \"number\" && Number.isFinite(value) && value > 0) return value;\n if (typeof value === \"string\") {\n const parsed = Number.parseInt(value, 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : null;\n }\n return null;\n}\n\nfunction getImageElementAtSelection(editor: Editor, pos: number): HTMLImageElement | null {\n const nodeDom = editor.view.nodeDOM(pos);\n if (!(nodeDom instanceof HTMLElement)) return null;\n if (nodeDom.tagName === \"IMG\") return nodeDom as HTMLImageElement;\n return nodeDom.querySelector(\"img\");\n}\n\nfunction getImageAspectRatio(editor: Editor, attrs: Record<string, unknown>, pos?: number): number | null {\n const widthAttr = toPositiveNumber(attrs.width);\n const heightAttr = toPositiveNumber(attrs.height);\n if (widthAttr && heightAttr) return widthAttr / heightAttr;\n\n const imageElement = typeof pos === \"number\" ? getImageElementAtSelection(editor, pos) : null;\n if (!imageElement) return null;\n\n if (imageElement.naturalWidth > 0 && imageElement.naturalHeight > 0) {\n return imageElement.naturalWidth / imageElement.naturalHeight;\n }\n\n const rect = imageElement.getBoundingClientRect();\n if (rect.width > 0 && rect.height > 0) return rect.width / rect.height;\n\n const width = toPositiveNumber(imageElement.getAttribute(\"width\")) ?? toPositiveNumber(imageElement.style.width);\n const height = toPositiveNumber(imageElement.getAttribute(\"height\")) ?? toPositiveNumber(imageElement.style.height);\n return width && height ? width / height : null;\n}\n\nfunction getImagePresetAttributes(editor: Editor, width: number, preset: UEditorImageWidthPreset, attrs: Record<string, unknown>, pos?: number) {\n const aspect = getImageAspectRatio(editor, attrs, pos);\n\n return {\n width,\n height: aspect ? Math.round(width / aspect) : toPositiveNumber(attrs.height),\n imageWidthPreset: preset,\n };\n}\n\nexport function applyImageLayout(editor: Editor, layout: UEditorImageLayout) {\n const { state, view } = editor;\n const { selection, schema } = state;\n\n if (!(selection instanceof NodeSelection) || selection.node.type.name !== \"image\") {\n editor.chain().focus().updateAttributes(\"image\", { imageLayout: layout }).run();\n return;\n }\n\n let transaction = state.tr.setNodeMarkup(selection.from, undefined, {\n ...selection.node.attrs,\n imageLayout: layout,\n });\n\n if (layout !== \"block\") {\n const nextPos = transaction.mapping.map(selection.to);\n const nextNode = transaction.doc.nodeAt(nextPos);\n\n if (!nextNode || nextNode.type.name !== \"paragraph\") {\n const paragraph = schema.nodes.paragraph?.create();\n if (paragraph) {\n transaction = transaction.insert(nextPos, paragraph);\n }\n }\n\n const resolvedPos = transaction.doc.resolve(Math.min(nextPos + 1, transaction.doc.content.size));\n transaction = transaction.setSelection(TextSelection.near(resolvedPos));\n } else {\n const resolvedPos = transaction.doc.resolve(selection.from);\n transaction = transaction.setSelection(NodeSelection.create(transaction.doc, resolvedPos.pos));\n }\n\n view.dispatch(transaction.scrollIntoView());\n view.focus();\n}\n\nexport function applyImageWidthPreset(editor: Editor, preset: UEditorImageWidthPreset) {\n const attrs = editor.getAttributes(\"image\") as { imageLayout?: string } & Record<string, unknown>;\n const mode = attrs.imageLayout === \"left\" || attrs.imageLayout === \"right\" ? \"wrap\" : \"block\";\n const width = IMAGE_WIDTHS_BY_LAYOUT[mode][preset];\n if (!isSelectedImage(editor)) {\n editor.chain().focus().updateAttributes(\"image\", getImagePresetAttributes(editor, width, preset, attrs)).run();\n return;\n }\n\n const { state, view } = editor;\n const selection = state.selection as NodeSelection;\n const nextAttrs = getImagePresetAttributes(editor, width, preset, selection.node.attrs, selection.from);\n const transaction = state.tr.setNodeMarkup(selection.from, undefined, {\n ...selection.node.attrs,\n ...nextAttrs,\n });\n view.dispatch(transaction.scrollIntoView());\n view.focus();\n}\n\nexport function resetImageSize(editor: Editor) {\n if (!isSelectedImage(editor)) {\n editor.chain().focus().updateAttributes(\"image\", {\n width: null,\n height: null,\n imageWidthPreset: null,\n }).run();\n return;\n }\n\n const { state, view } = editor;\n const selection = state.selection as NodeSelection;\n const transaction = state.tr.setNodeMarkup(selection.from, undefined, {\n ...selection.node.attrs,\n width: null,\n height: null,\n imageWidthPreset: null,\n });\n view.dispatch(transaction.scrollIntoView());\n view.focus();\n}\n\nexport function deleteSelectedImage(editor: Editor) {\n if (!isSelectedImage(editor)) return;\n editor.chain().focus().deleteSelection().run();\n}\n","import type { Editor } from \"@tiptap/core\";\nimport type { EditorState } from \"@tiptap/pm/state\";\nimport type { Node as ProseMirrorNode, ResolvedPos } from \"@tiptap/pm/model\";\nimport type { UEditorTableAlign } from \"./table-align\";\nimport { isCrossRealmHTMLElement, isCrossRealmTable, resolveEventElement } from \"./table-dom-utils\";\nimport {\n formatBasisPointsAsPercentage,\n getResponsiveTableWidthBp,\n normalizeTableWidthMode,\n resolveResponsiveTableOffsetBp,\n} from \"./table-width-model\";\n\ntype TableNodeInfo = {\n depth: number;\n pos: number;\n node: ProseMirrorNode;\n};\n\nfunction findTableNodeInfoAtResolvedPos($pos: ResolvedPos): TableNodeInfo | null {\n for (let depth = $pos.depth; depth > 0; depth -= 1) {\n const node = $pos.node(depth);\n if (node.type.name === \"table\") {\n return {\n depth,\n pos: $pos.before(depth),\n node,\n };\n }\n }\n\n return null;\n}\n\nexport function findTableNodeInfoFromState(state: EditorState, anchorPos?: number): TableNodeInfo | null {\n if (typeof anchorPos === \"number\" && Number.isFinite(anchorPos)) {\n const safePos = Math.max(0, Math.min(anchorPos, state.doc.content.size));\n return findTableNodeInfoAtResolvedPos(state.doc.resolve(safePos));\n }\n\n return findTableNodeInfoAtResolvedPos(state.selection.$from);\n}\n\nexport function applyTableAlignment(editor: Editor, tableAlign: UEditorTableAlign | null, anchorPos?: number) {\n const tableInfo = findTableNodeInfoFromState(editor.state, anchorPos);\n if (!tableInfo) return false;\n const responsive = normalizeTableWidthMode(tableInfo.node.attrs.widthMode) === \"responsive\";\n const widthBp = getResponsiveTableWidthBp(tableInfo.node);\n const offsetBp = resolveResponsiveTableOffsetBp(widthBp, tableAlign);\n\n editor.view.dispatch(\n editor.state.tr.setNodeMarkup(tableInfo.pos, tableInfo.node.type, {\n ...tableInfo.node.attrs,\n textAlign: tableAlign,\n ...(responsive ? { offsetBp } : null),\n }),\n );\n const domAtTable = editor.view.domAtPos(Math.min(tableInfo.pos + 1, editor.state.doc.content.size)).node;\n const domAtTableElement = resolveEventElement(domAtTable);\n const tableDom = editor.view.nodeDOM(tableInfo.pos);\n const tableElement = domAtTableElement?.closest?.(\"table\")\n ?? (isCrossRealmTable(tableDom)\n ? tableDom\n : isCrossRealmHTMLElement(tableDom)\n ? tableDom.querySelector(\"table\")\n : null)\n ?? (editor.view.dom.querySelectorAll(\"table\").length === 1 ? editor.view.dom.querySelector(\"table\") : null);\n\n if (isCrossRealmTable(tableElement)) {\n tableElement.style.tableLayout = \"fixed\";\n // Older alignment behavior used content-sized tables. Remove only those\n // legacy values so explicit widths from column/table resizing stay intact.\n if (tableElement.style.width === \"max-content\") {\n tableElement.style.removeProperty(\"width\");\n }\n if (tableElement.style.maxWidth === \"100%\") {\n tableElement.style.removeProperty(\"max-width\");\n }\n\n if (tableAlign) {\n tableElement.setAttribute(\"data-table-align\", tableAlign);\n tableElement.style.marginLeft = responsive\n ? formatBasisPointsAsPercentage(offsetBp)\n : tableAlign === \"center\" || tableAlign === \"right\" ? \"auto\" : \"0\";\n tableElement.style.marginRight = responsive\n ? \"auto\"\n : tableAlign === \"center\" ? \"auto\" : tableAlign === \"right\" ? \"0\" : \"auto\";\n } else {\n tableElement.removeAttribute(\"data-table-align\");\n tableElement.style.removeProperty(\"margin-left\");\n tableElement.style.removeProperty(\"margin-right\");\n }\n }\n\n return true;\n}\n","import React from \"react\";\n\ntype TableVerticalAlign = \"top\" | \"middle\" | \"bottom\";\n\ntype TableVerticalAlignIconProps = React.SVGProps<SVGSVGElement>;\n\nconst linePositions: Record<TableVerticalAlign, readonly [number, number]> = {\n top: [4.5, 7],\n middle: [7, 9.5],\n bottom: [10, 12.5],\n};\n\nfunction TableVerticalAlignIcon({ align, ...props }: TableVerticalAlignIconProps & { align: TableVerticalAlign }) {\n const [shortLine, longLine] = linePositions[align];\n\n return (\n <svg viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.35\" strokeLinecap=\"round\" strokeLinejoin=\"round\" {...props}>\n <rect x=\"2\" y=\"1.5\" width=\"12\" height=\"13\" rx=\"1\" opacity=\"0.55\" />\n <path d={`M5 ${shortLine}h6M4 ${longLine}h8`} />\n </svg>\n );\n}\n\nexport const TableVerticalAlignTopIcon = (props: TableVerticalAlignIconProps) => (\n <TableVerticalAlignIcon align=\"top\" {...props} />\n);\n\nexport const TableVerticalAlignMiddleIcon = (props: TableVerticalAlignIconProps) => (\n <TableVerticalAlignIcon align=\"middle\" {...props} />\n);\n\nexport const TableVerticalAlignBottomIcon = (props: TableVerticalAlignIconProps) => (\n <TableVerticalAlignIcon align=\"bottom\" {...props} />\n);\n","import type {\n UEditorFontFamilyOption,\n UEditorFontSizeOption,\n UEditorLetterSpacingOption,\n UEditorLineHeightOption,\n} from \"./types\";\n\nexport function normalizeStyleValue(value: unknown) {\n return typeof value === \"string\" ? value.trim().replace(/^['\"]|['\"]$/g, \"\") : \"\";\n}\n\nexport function getDefaultFontFamilies(t: (key: string) => string): UEditorFontFamilyOption[] {\n return [\n { label: \"Inter\", value: '\"Inter\", \"Noto Sans\", \"Noto Sans CJK KR\", \"Noto Sans CJK JP\", \"Segoe UI\", sans-serif' },\n { label: \"굴림\", value: '\"Gulim\", \"Apple SD Gothic Neo\", \"Noto Sans KR\", sans-serif' },\n { label: \"굴림체\", value: '\"GulimChe\", \"Gulim\", \"Apple SD Gothic Neo\", \"Noto Sans KR\", sans-serif' },\n { label: \"궁서\", value: '\"Gungsuh\", \"Nanum Myeongjo\", serif' },\n { label: \"궁서체\", value: '\"GungsuhChe\", \"Gungsuh\", \"Nanum Myeongjo\", serif' },\n { label: \"돋움\", value: '\"Dotum\", \"Apple SD Gothic Neo\", \"Noto Sans KR\", sans-serif' },\n { label: \"돋움체\", value: '\"DotumChe\", \"Dotum\", \"Apple SD Gothic Neo\", \"Noto Sans KR\", sans-serif' },\n { label: \"바탕\", value: '\"Batang\", \"Nanum Myeongjo\", serif' },\n { label: \"바탕체\", value: '\"BatangChe\", \"Batang\", \"Nanum Myeongjo\", serif' },\n { label: \"맑은고딕\", value: '\"Malgun Gothic\", \"Apple SD Gothic Neo\", \"Noto Sans KR\", sans-serif' },\n { label: \"나눔명조\", value: '\"Nanum Myeongjo\", \"Batang\", serif' },\n { label: \"System UI\", value: 'system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif' },\n { label: \"Roboto\", value: '\"Roboto\", \"Noto Sans\", \"Apple SD Gothic Neo\", \"Hiragino Kaku Gothic ProN\", sans-serif' },\n { label: \"Lexend\", value: '\"Lexend\", \"Be Vietnam Pro\", \"Segoe UI\", sans-serif' },\n { label: \"Montserrat\", value: '\"Montserrat\", \"Segoe UI\", sans-serif' },\n { label: \"Lora\", value: '\"Lora\", \"Georgia\", \"Times New Roman\", \"Nanum Myeongjo\", \"BIZ UDPMincho\", serif' },\n { label: \"Playfair Display\", value: '\"Playfair Display\", \"Times New Roman\", \"Nanum Myeongjo\", serif' },\n { label: \"Georgia\", value: 'Georgia, \"Nanum Myeongjo\", \"Batang\", \"Times New Roman\", serif' },\n { label: \"Times New Roman\", value: '\"Times New Roman\", Times, \"BIZ UDPMincho\", serif' },\n { label: \"Meiryo (JA)\", value: '\"Meiryo\", \"Hiragino Sans\", \"Noto Sans JP\", sans-serif' },\n { label: \"Apple SD Gothic Neo (KO)\", value: '\"Apple SD Gothic Neo\", \"Malgun Gothic\", \"Noto Sans KR\", sans-serif' },\n { label: \"JetBrains Mono\", value: '\"JetBrains Mono\", \"Fira Code\", \"SFMono-Regular\", Consolas, \"Noto Sans Mono CJK KR\", \"Noto Sans Mono CJK JP\", monospace' },\n ];\n}\n\nexport function getDefaultFontSizes(): UEditorFontSizeOption[] {\n return [\n { label: \"8\", value: \"8px\" },\n { label: \"9\", value: \"9px\" },\n { label: \"10\", value: \"10px\" },\n { label: \"11\", value: \"11px\" },\n { label: \"12\", value: \"12px\" },\n { label: \"13\", value: \"13px\" },\n { label: \"14\", value: \"14px\" },\n { label: \"15\", value: \"15px\" },\n { label: \"16\", value: \"16px\" },\n { label: \"17\", value: \"17px\" },\n { label: \"18\", value: \"18px\" },\n { label: \"19\", value: \"19px\" },\n { label: \"20\", value: \"20px\" },\n { label: \"21\", value: \"21px\" },\n { label: \"22\", value: \"22px\" },\n { label: \"23\", value: \"23px\" },\n { label: \"24\", value: \"24px\" },\n { label: \"25\", value: \"25px\" },\n { label: \"26\", value: \"26px\" },\n { label: \"27\", value: \"27px\" },\n { label: \"28\", value: \"28px\" },\n { label: \"36\", value: \"36px\" },\n { label: \"48\", value: \"48px\" },\n { label: \"72\", value: \"72px\" },\n { label: \"96\", value: \"96px\" },\n ];\n}\n\nexport function getDefaultLineHeights(): UEditorLineHeightOption[] {\n return [\n { label: \"1.2\", value: \"1.2\" },\n { label: \"1.5\", value: \"1.5\" },\n { label: \"1.75\", value: \"1.75\" },\n { label: \"2\", value: \"2\" },\n ];\n}\n\nexport function getDefaultLetterSpacings(): UEditorLetterSpacingOption[] {\n return [\n { label: \"-0.02em\", value: \"-0.02em\" },\n { label: \"0\", value: \"0\" },\n { label: \"0.02em\", value: \"0.02em\" },\n { label: \"0.05em\", value: \"0.05em\" },\n { label: \"0.08em\", value: \"0.08em\" },\n ];\n}\n","import { cn } from \"../../utils/cn\";\n\nexport const UEDITOR_PROSEMIRROR_CLASS_NAME = cn(\n \"prose prose-sm sm:prose dark:prose-invert max-w-none\",\n \"focus:outline-none\",\n \"px-4 py-4\",\n \"[&_.is-editor-empty]:before:content-[attr(data-placeholder)]\",\n \"[&_.is-editor-empty]:before:text-muted-foreground/50\",\n \"[&_.is-editor-empty]:before:float-left\",\n \"[&_.is-editor-empty]:before:pointer-events-none\",\n \"[&_.is-editor-empty]:before:h-0\",\n \"[&_.ProseMirror-gapcursor]:pointer-events-none\",\n \"[&_.ProseMirror-gapcursor]:absolute\",\n \"[&_.ProseMirror-gapcursor]:hidden\",\n \"[&_.ProseMirror-gapcursor:after]:content-['']\",\n \"[&_.ProseMirror-gapcursor:after]:block\",\n \"[&_.ProseMirror-gapcursor:after]:absolute\",\n \"[&_.ProseMirror-gapcursor:after]:top-[-2px]\",\n \"[&_.ProseMirror-gapcursor:after]:w-8\",\n \"[&_.ProseMirror-gapcursor:after]:border-t-2\",\n \"[&_.ProseMirror-gapcursor:after]:border-primary\",\n \"[&.ProseMirror-focused_.ProseMirror-gapcursor]:block\",\n \"[&_ul[data-bullet-style='dash']>li]:[list-style-type:'-_']\",\n \"[&_ul[data-bullet-style='dash']>li::marker]:content-['-_']\",\n \"[&_ul[data-bullet-style='circle']>li]:[list-style-type:circle]\",\n \"[&_ul[data-bullet-style='circle']>li::marker]:content-['◦_']\",\n \"[&_ul[data-bullet-style='square']>li]:[list-style-type:square]\",\n \"[&_ul[data-bullet-style='square']>li::marker]:content-['▪_']\",\n \"[&_ul[data-bullet-style='disc']>li]:[list-style-type:disc]\",\n \"[&_ul[data-type='taskList']]:list-none\",\n \"[&_ul[data-type='taskList']]:pl-0\",\n \"[&_ul[data-type='taskList']_li]:flex\",\n \"[&_ul[data-type='taskList']_li]:items-start\",\n \"[&_ul[data-type='taskList']_li]:gap-2\",\n \"[&_ul[data-type='taskList']_li>label]:mt-0.5\",\n \"[&_ul[data-type='taskList']_li>label>input]:w-4\",\n \"[&_ul[data-type='taskList']_li>label>input]:h-4\",\n \"[&_ul[data-type='taskList']_li>label>input]:rounded\",\n \"[&_ul[data-type='taskList']_li>label>input]:border-2\",\n \"[&_ul[data-type='taskList']_li>label>input]:border-primary/50\",\n \"[&_ul[data-type='taskList']_li>label>input]:accent-primary\",\n \"[&_pre]:bg-muted/40!\",\n \"[&_pre]:text-foreground!\",\n \"[&_pre]:border!\",\n \"[&_pre]:border-border/60!\",\n \"[&_pre_code]:bg-transparent!\",\n \"[&_.tableWrapper]:overflow-x-auto\",\n \"[&_.tableWrapper]:pb-1.5\",\n \"[&_.tableWrapper]:select-text\",\n \"[&_.tableWrapper]:[scrollbar-width:thin]\",\n \"[&_.tableWrapper]:[scrollbar-color:hsl(var(--border))_transparent]\",\n \"[&_.tableWrapper::-webkit-scrollbar]:h-2\",\n \"[&_.tableWrapper::-webkit-scrollbar]:w-2\",\n \"[&_.tableWrapper::-webkit-scrollbar-track]:rounded-full\",\n \"[&_.tableWrapper::-webkit-scrollbar-track]:bg-transparent\",\n \"[&_.tableWrapper::-webkit-scrollbar-thumb]:rounded-full\",\n \"[&_.tableWrapper::-webkit-scrollbar-thumb]:border\",\n \"[&_.tableWrapper::-webkit-scrollbar-thumb]:border-solid\",\n \"[&_.tableWrapper::-webkit-scrollbar-thumb]:border-transparent\",\n \"[&_.tableWrapper::-webkit-scrollbar-thumb]:bg-border/70\",\n \"[&_.tableWrapper::-webkit-scrollbar-thumb:hover]:bg-muted-foreground/45\",\n \"[&_table]:w-auto\",\n \"[&_table]:table-fixed\",\n \"[&_table]:overflow-hidden\",\n \"[&_table]:select-text\",\n \"[&_table[data-table-align='center']]:mx-auto\",\n \"[&_table[data-table-align='right']]:ml-auto\",\n \"[&_table[data-table-align='right']]:mr-0\",\n \"[&_td]:relative\",\n \"[&_td]:align-top\",\n \"[&_td]:box-border\",\n \"[&_td]:select-text\",\n \"[&_td]:px-[var(--ueditor-table-cell-padding-x,0.5rem)]\",\n \"[&_td]:py-0\",\n \"[&_td]:whitespace-normal\",\n \"[&_td]:wrap-anywhere\",\n \"[&_td]:[word-break:normal]\",\n \"[&_td[data-text-wrap='nowrap']]:whitespace-nowrap\",\n \"[&_td[data-text-wrap='nowrap']]:[overflow-wrap:normal]\",\n \"[&_td_p]:my-0\",\n \"[&_th]:relative\",\n \"[&_th]:align-top\",\n \"[&_th]:box-border\",\n \"[&_th]:select-text\",\n \"[&_th]:px-[var(--ueditor-table-cell-padding-x,0.5rem)]\",\n \"[&_th]:py-0\",\n \"[&_th]:whitespace-normal\",\n \"[&_th]:wrap-anywhere\",\n \"[&_th]:[word-break:normal]\",\n \"[&_th[data-text-wrap='nowrap']]:whitespace-nowrap\",\n \"[&_th[data-text-wrap='nowrap']]:[overflow-wrap:normal]\",\n \"[&_th_p]:my-0\",\n \"[&_td[data-formula]]:pr-7\",\n \"[&_th[data-formula]]:pr-7\",\n \"[&_td[data-formula]]:before:pointer-events-none\",\n \"[&_th[data-formula]]:before:pointer-events-none\",\n \"[&_td[data-formula]]:before:absolute\",\n \"[&_th[data-formula]]:before:absolute\",\n \"[&_td[data-formula]]:before:right-1\",\n \"[&_th[data-formula]]:before:right-1\",\n \"[&_td[data-formula]]:before:top-1\",\n \"[&_th[data-formula]]:before:top-1\",\n \"[&_td[data-formula]]:before:z-[1]\",\n \"[&_th[data-formula]]:before:z-[1]\",\n \"[&_td[data-formula]]:before:rounded-sm\",\n \"[&_th[data-formula]]:before:rounded-sm\",\n \"[&_td[data-formula]]:before:bg-primary/10\",\n \"[&_th[data-formula]]:before:bg-primary/10\",\n \"[&_td[data-formula]]:before:px-1\",\n \"[&_th[data-formula]]:before:px-1\",\n \"[&_td[data-formula]]:before:font-mono\",\n \"[&_th[data-formula]]:before:font-mono\",\n \"[&_td[data-formula]]:before:text-[9px]\",\n \"[&_th[data-formula]]:before:text-[9px]\",\n \"[&_td[data-formula]]:before:font-semibold\",\n \"[&_th[data-formula]]:before:font-semibold\",\n \"[&_td[data-formula]]:before:leading-4\",\n \"[&_th[data-formula]]:before:leading-4\",\n \"[&_td[data-formula]]:before:text-primary\",\n \"[&_th[data-formula]]:before:text-primary\",\n \"[&_td[data-formula]]:before:content-['fx']\",\n \"[&_th[data-formula]]:before:content-['fx']\",\n \"[&_td[data-formula-state='error']]:bg-destructive/5\",\n \"[&_th[data-formula-state='error']]:bg-destructive/5\",\n \"[&_td[data-formula-state='error']]:before:bg-destructive/10\",\n \"[&_th[data-formula-state='error']]:before:bg-destructive/10\",\n \"[&_td[data-formula-state='error']]:before:text-destructive\",\n \"[&_th[data-formula-state='error']]:before:text-destructive\",\n \"[&_td[colwidth]]:min-w-0\",\n \"[&_th[colwidth]]:min-w-0\",\n \"[&_td[data-colwidth]]:min-w-0\",\n \"[&_th[data-colwidth]]:min-w-0\",\n \"[&_.selectedCell]:after:content-['']\",\n \"[&_.selectedCell]:after:absolute\",\n \"[&_.selectedCell]:after:inset-0\",\n \"[&_.selectedCell]:after:z-[2]\",\n \"[&_.selectedCell]:after:bg-primary/8\",\n \"[&_.selectedCell]:after:pointer-events-none\",\n \"[&_.column-resize-handle]:pointer-events-auto\",\n \"[&_.column-resize-handle]:cursor-col-resize\",\n \"[&_.column-resize-handle]:absolute\",\n \"[&_.column-resize-handle]:top-[-1px]\",\n \"[&_.column-resize-handle]:bottom-[-1px]\",\n \"[&_.column-resize-handle]:right-[-5px]\",\n \"[&_.column-resize-handle]:z-30\",\n \"[&_.column-resize-handle]:w-2.5\",\n \"[&_.column-resize-handle]:bg-transparent\",\n \"[&_.column-resize-handle]:rounded-none\",\n \"[&_.column-resize-handle]:opacity-0\",\n \"[&_.column-resize-handle]:transition-opacity\",\n \"[&_.column-resize-handle]:duration-200\",\n \"[&_.column-resize-handle]:delay-100\",\n \"[&_.column-resize-handle]:ease-out\",\n \"[&_.column-resize-handle]:after:hidden\",\n \"[&_.column-resize-dragging]:min-w-0\",\n \"[&.resize-cursor]:cursor-col-resize\",\n \"[&.resize-row-cursor]:cursor-row-resize\",\n \"[&_img.ProseMirror-selectednode]:ring-2\",\n \"[&_img.ProseMirror-selectednode]:ring-primary/60\",\n \"[&_img.ProseMirror-selectednode]:ring-offset-2\",\n \"[&_img.ProseMirror-selectednode]:ring-offset-background\",\n \"[&_hr]:border-t-2\",\n \"[&_hr]:border-primary/30\",\n \"[&_hr]:my-8\",\n \"[&_h1]:text-3xl\",\n \"[&_h1]:font-bold\",\n \"[&_h1]:mt-6\",\n \"[&_h1]:mb-4\",\n \"[&_h1]:text-foreground\",\n \"[&_h2]:text-2xl\",\n \"[&_h2]:font-semibold\",\n \"[&_h2]:mt-5\",\n \"[&_h2]:mb-3\",\n \"[&_h2]:text-foreground\",\n \"[&_h3]:text-xl\",\n \"[&_h3]:font-semibold\",\n \"[&_h3]:mt-4\",\n \"[&_h3]:mb-2\",\n \"[&_h3]:text-foreground\",\n \"[&_ul:not([data-type='taskList'])]:list-disc\",\n \"[&_ul:not([data-type='taskList'])]:pl-6\",\n \"[&_ul:not([data-type='taskList'])]:my-3\",\n \"[&_ol]:list-decimal\",\n \"[&_ol]:pl-6\",\n \"[&_ol]:my-3\",\n \"[&_li]:my-1\",\n \"[&_li]:pl-1\",\n \"[&_li_p]:my-0\",\n \"[&_blockquote]:border-l-4\",\n \"[&_blockquote]:border-primary\",\n \"[&_blockquote]:pl-4\",\n \"[&_blockquote]:py-2\",\n \"[&_blockquote]:my-4\",\n \"[&_blockquote]:bg-muted/30\",\n \"[&_blockquote]:rounded-r-lg\",\n \"[&_blockquote]:italic\",\n \"[&_blockquote]:text-muted-foreground\",\n \"[&_blockquote_p]:my-0\",\n \"[&_[data-image-layout='left']+p]:mt-1\",\n \"[&_[data-image-layout='left']+p]:min-h-[5rem]\",\n \"[&_[data-image-layout='right']+p]:mt-1\",\n \"[&_[data-image-layout='right']+p]:min-h-[5rem]\",\n \"max-md:[&_[data-image-layout='left']]:float-none\",\n \"max-md:[&_[data-image-layout='left']]:mr-0\",\n \"max-md:[&_[data-image-layout='left']]:ml-0\",\n \"max-md:[&_[data-image-layout='left']]:max-w-full\",\n \"max-md:[&_[data-image-layout='right']]:float-none\",\n \"max-md:[&_[data-image-layout='right']]:mr-0\",\n \"max-md:[&_[data-image-layout='right']]:ml-0\",\n \"max-md:[&_[data-image-layout='right']]:max-w-full\",\n \"max-md:[&_[data-image-layout='left']+p]:min-h-0\",\n \"max-md:[&_[data-image-layout='right']+p]:min-h-0\",\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAGA,OAAO,SAAS,gBAAgB;AAGhC,SAAS,oBAAoB;AAgOb,SAuBoB,KAvBpB;AApNhB,IAAM,sBAAsB,MAAM,cAA+C,IAAI;A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A,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":["base","TextSelection","selectedRect","TableMap","Plugin","found","Plugin","iA","iB","found","Node","found","i","type","nfa","edge","expr","node","states","parent","TransformError","found","mac","shift","readFromCache: (key: Node) => TableMap | undefined","addToCache: (key: Node, value: TableMap) => TableMap","cache: (Node | TableMap)[]","TableMap","width: number","height: number","map: number[]","problems: Problem[] | null","result: number[]","seen: Record<number, boolean>","colWidths: ColWidths","result: ColWidths","tableNodeTypes","cellAround","cellAround","pointsAtCell","TableMap","result: CellAttrs","CellSelection","TableMap","pointsAtCell","seen: Record<number, boolean>","CellBookmark","anchor: number","head: number","TableMap","rows: (Node | null)[][]","colCount","row: (Node | null)[]","newRows: Node[]","oldRow: Node","newCells: Node[]","target: number","TableMap","moveTableColumn","moveTableRow","tableNodeTypes","toggleHeaderRow: Command","toggleHeaderColumn: Command","toggleHeaderCell: Command","tableNodeTypes","cellSel: CellSelection","dirStr: 'up' | 'down' | 'left' | 'right'","columnResizingPluginKey","TableMap","TableMap","TableMap","cellValue","TextSelection","TableMap","selectedRect","useState","jsx","jsxs","useState","TextSelection","React","useRef","useState","React","useRef","Check","React","jsx","jsx","jsxs","useRef","React","Check","NodeSelection","TextSelection","jsx","jsxs","Fragment","jsx","jsxs","selectionCell","cellPos","React","useState","useRef"]}